@lykosjs/openapi 0.0.0-stage → 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/dist/index.js ADDED
@@ -0,0 +1,1237 @@
1
+ // @bun
2
+ // src/ui/swagger-ui.ts
3
+ import { existsSync } from "fs";
4
+ import { readFile } from "fs/promises";
5
+ import { createRequire } from "module";
6
+ import { dirname, join } from "path";
7
+ var ASSETS = [
8
+ { file: "swagger-ui.css", type: "text/css; charset=utf-8" },
9
+ { file: "swagger-ui-bundle.js", type: "text/javascript; charset=utf-8" }
10
+ ];
11
+ var SECURITY_HEADERS = {
12
+ "x-content-type-options": "nosniff",
13
+ "referrer-policy": "no-referrer"
14
+ };
15
+ var CONTENT_SECURITY_POLICY = [
16
+ "default-src 'none'",
17
+ "script-src 'self'",
18
+ "style-src 'self' 'unsafe-inline'",
19
+ "img-src 'self' data:",
20
+ "font-src 'self' data:",
21
+ "connect-src 'self'",
22
+ "base-uri 'none'",
23
+ "form-action 'none'",
24
+ "frame-ancestors 'none'"
25
+ ].join("; ");
26
+ function escapeHtml(value) {
27
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
28
+ }
29
+ function locateSwaggerUiDirectory() {
30
+ const require2 = createRequire(import.meta.url);
31
+ try {
32
+ const directory = dirname(require2.resolve("swagger-ui-dist/package.json"));
33
+ for (const asset of ASSETS) {
34
+ if (!existsSync(join(directory, asset.file))) {
35
+ throw new Error(`missing file ${asset.file}`);
36
+ }
37
+ }
38
+ return directory;
39
+ } catch (error) {
40
+ const reason = error instanceof Error ? error.message : String(error);
41
+ throw new Error(`[LykosJS OpenAPI] Swagger UI assets are unavailable (${reason}). Reinstall "@lykosjs/openapi" so that its "swagger-ui-dist" dependency is present, or disable the UI with docs: false.`);
42
+ }
43
+ }
44
+ function assetBase(docsPath) {
45
+ return `${docsPath === "/" ? "" : docsPath}/assets`;
46
+ }
47
+ function renderHtml(docsPath, title) {
48
+ const base = escapeHtml(assetBase(docsPath));
49
+ return `<!doctype html>
50
+ <html lang="en">
51
+ <head>
52
+ <meta charset="utf-8" />
53
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
54
+ <title>${escapeHtml(title)}</title>
55
+ <link rel="stylesheet" href="${base}/swagger-ui.css" />
56
+ </head>
57
+ <body>
58
+ <div id="swagger-ui"></div>
59
+ <script src="${base}/swagger-ui-bundle.js"></script>
60
+ <script src="${base}/init.js"></script>
61
+ </body>
62
+ </html>
63
+ `;
64
+ }
65
+ function renderInitScript(jsonPath, ui) {
66
+ return `window.addElykosListener('load', function () {
67
+ window.ui = SwaggerUIBundle({
68
+ url: ${JSON.stringify(jsonPath)},
69
+ dom_id: '#swagger-ui',
70
+ deepLinking: true,
71
+ persistAuthorization: ${JSON.stringify(ui.persistAuthorization)},
72
+ docExpansion: ${JSON.stringify(ui.docExpansion)},
73
+ validatorUrl: null,
74
+ presets: [SwaggerUIBundle.presets.apis],
75
+ layout: 'BaseLayout'
76
+ })
77
+ })
78
+ `;
79
+ }
80
+ function createDocsRoutes(input) {
81
+ const routes = [];
82
+ if (input.jsonPath !== undefined) {
83
+ const { json } = input;
84
+ routes.push({
85
+ path: input.jsonPath,
86
+ handler: () => new Response(json, {
87
+ headers: {
88
+ "content-type": "application/json; charset=utf-8",
89
+ "cache-control": "no-cache",
90
+ ...SECURITY_HEADERS
91
+ }
92
+ })
93
+ });
94
+ }
95
+ if (input.docsPath !== undefined && input.jsonPath !== undefined) {
96
+ const directory = locateSwaggerUiDirectory();
97
+ const base = assetBase(input.docsPath);
98
+ const html = renderHtml(input.docsPath, input.ui.title);
99
+ const init = renderInitScript(input.jsonPath, input.ui);
100
+ routes.push({
101
+ path: input.docsPath,
102
+ handler: () => new Response(html, {
103
+ headers: {
104
+ "content-type": "text/html; charset=utf-8",
105
+ "content-security-policy": CONTENT_SECURITY_POLICY,
106
+ "cache-control": "no-cache",
107
+ ...SECURITY_HEADERS
108
+ }
109
+ })
110
+ });
111
+ routes.push({
112
+ path: `${base}/init.js`,
113
+ handler: () => new Response(init, {
114
+ headers: {
115
+ "content-type": "text/javascript; charset=utf-8",
116
+ "cache-control": "no-cache",
117
+ ...SECURITY_HEADERS
118
+ }
119
+ })
120
+ });
121
+ for (const asset of ASSETS) {
122
+ let cached;
123
+ routes.push({
124
+ path: `${base}/${asset.file}`,
125
+ handler: async () => {
126
+ cached ??= readFile(join(directory, asset.file)).catch((error) => {
127
+ cached = undefined;
128
+ throw error;
129
+ });
130
+ const data = await cached;
131
+ return new Response(new Uint8Array(data), {
132
+ headers: {
133
+ "content-type": asset.type,
134
+ "cache-control": "private, max-age=3600",
135
+ ...SECURITY_HEADERS
136
+ }
137
+ });
138
+ }
139
+ });
140
+ }
141
+ }
142
+ return routes;
143
+ }
144
+
145
+ // src/utils/path.ts
146
+ var STATIC_SEGMENT = /^[A-Za-z0-9._~%@!$&'()*+,;=-]+$/;
147
+ var PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
148
+ function build(segments) {
149
+ const canonical = "/" + segments.map((s) => s.kind === "param" ? `{${s.name}}` : s.value).join("/");
150
+ const shape = "/" + segments.map((s) => s.kind === "param" ? "{}" : s.value).join("/");
151
+ const params = segments.flatMap((s) => s.kind === "param" ? [s.name] : []);
152
+ return { canonical, shape, params, segments };
153
+ }
154
+ function isUnsafeDecoded(segment) {
155
+ let decoded;
156
+ try {
157
+ decoded = decodeURIComponent(segment);
158
+ } catch {
159
+ return true;
160
+ }
161
+ return decoded === "." || decoded === ".." || decoded.includes("/") || decoded.includes("\\");
162
+ }
163
+ function parsePath(path) {
164
+ if (typeof path !== "string" || path === "") {
165
+ return { ok: false, reason: "path must be a non-empty string" };
166
+ }
167
+ if (!path.startsWith("/")) {
168
+ return { ok: false, reason: 'path must start with "/"' };
169
+ }
170
+ if (/[?#\s\\]/.test(path) || /[\u0000-\u001f\u007f]/.test(path)) {
171
+ return {
172
+ ok: false,
173
+ reason: 'path must not contain "?", "#", "\\", whitespace or control characters'
174
+ };
175
+ }
176
+ const segments = [];
177
+ const seen = new Set;
178
+ for (const raw of path.split("/")) {
179
+ if (raw === "")
180
+ continue;
181
+ if (raw === "." || raw === ".." || isUnsafeDecoded(raw)) {
182
+ return { ok: false, reason: `path segment "${raw}" is not allowed (path traversal)` };
183
+ }
184
+ let name;
185
+ if (raw.startsWith(":")) {
186
+ name = raw.slice(1);
187
+ } else if (raw.startsWith("{") && raw.endsWith("}")) {
188
+ name = raw.slice(1, -1);
189
+ }
190
+ if (name !== undefined) {
191
+ if (!PARAM_NAME.test(name)) {
192
+ return {
193
+ ok: false,
194
+ reason: `invalid parameter segment "${raw}" (names must match ${PARAM_NAME.source})`
195
+ };
196
+ }
197
+ if (seen.has(name)) {
198
+ return { ok: false, reason: `parameter "${name}" appears more than once` };
199
+ }
200
+ seen.add(name);
201
+ segments.push({ kind: "param", name });
202
+ continue;
203
+ }
204
+ if (!STATIC_SEGMENT.test(raw)) {
205
+ return { ok: false, reason: `invalid path segment "${raw}"` };
206
+ }
207
+ segments.push({ kind: "static", value: raw });
208
+ }
209
+ return { ok: true, path: build(segments) };
210
+ }
211
+ function parseRegisteredPath(path) {
212
+ const segments = path.split("/").filter(Boolean).map((raw) => raw.startsWith(":") ? { kind: "param", name: raw.slice(1) } : { kind: "static", value: raw });
213
+ return build(segments);
214
+ }
215
+ function routeMatchesStaticPath(route, target) {
216
+ if (route.segments.length !== target.segments.length)
217
+ return false;
218
+ return route.segments.every((segment, index) => {
219
+ if (segment.kind === "param")
220
+ return true;
221
+ const other = target.segments[index];
222
+ return other !== undefined && other.kind === "static" && other.value === segment.value;
223
+ });
224
+ }
225
+
226
+ // src/validation/route-validator.ts
227
+ function rawPath(route) {
228
+ return route.path;
229
+ }
230
+ function validateRegisteredRoutes(routes, registered) {
231
+ const exact = new Set;
232
+ const byShape = new Map;
233
+ const byCanonical = new Map;
234
+ for (const route of registered) {
235
+ const parsed = parseRegisteredPath(route.path);
236
+ exact.add(`${route.method} ${parsed.canonical}`);
237
+ byShape.set(parsed.shape, [...byShape.get(parsed.shape) ?? [], route]);
238
+ byCanonical.set(parsed.canonical, [...byCanonical.get(parsed.canonical) ?? [], route]);
239
+ }
240
+ const issues = [];
241
+ const active = [];
242
+ for (const route of routes) {
243
+ if (exact.has(`${route.method} ${route.path}`)) {
244
+ active.push(route);
245
+ continue;
246
+ }
247
+ if (!route.isRequired)
248
+ continue;
249
+ const hints = [];
250
+ const sameShape = byShape.get(route.shape) ?? [];
251
+ const sameName = sameShape.filter((r) => r.method === route.method);
252
+ if (sameName.length > 0) {
253
+ hints.push(`parameter names must match exactly; LykosJS registered ${sameName.map((r) => `${r.method} ${rawPath(r)}`).join(", ")}`);
254
+ }
255
+ const otherMethods = sameShape.filter((r) => r.method !== route.method);
256
+ if (otherMethods.length > 0 && sameName.length === 0) {
257
+ hints.push(`this path is registered with: ${[...new Set(otherMethods.map((r) => r.method))].join(", ")}`);
258
+ }
259
+ issues.push({
260
+ kind: "missing-route",
261
+ key: route.key,
262
+ method: route.method,
263
+ path: route.path,
264
+ hints
265
+ });
266
+ }
267
+ return { issues, active };
268
+ }
269
+ function findDocsConflicts(endpoints, registered) {
270
+ const issues = [];
271
+ const getRoutes = registered.filter((route) => route.method === "GET");
272
+ for (const endpoint of endpoints) {
273
+ const parsed = parsePath(endpoint.path);
274
+ if (!parsed.ok)
275
+ continue;
276
+ for (const route of getRoutes) {
277
+ if (routeMatchesStaticPath(parseRegisteredPath(route.path), parsed.path)) {
278
+ issues.push({
279
+ kind: "docs-conflict",
280
+ target: endpoint.target,
281
+ path: endpoint.path,
282
+ message: `collides with the registered route GET ${route.path}; choose another "docs"/"json" path`
283
+ });
284
+ break;
285
+ }
286
+ }
287
+ }
288
+ return issues;
289
+ }
290
+
291
+ // src/validation/validation-error.ts
292
+ var PREFIX = "[LykosJS OpenAPI]";
293
+ function formatIssue(issue) {
294
+ switch (issue.kind) {
295
+ case "config":
296
+ return `- ${issue.location}: ${issue.message}`;
297
+ case "docs-conflict":
298
+ return `- ${issue.target} (${issue.path}): ${issue.message}`;
299
+ case "missing-route":
300
+ return [
301
+ `Documentation Key: ${issue.key}`,
302
+ `Method: ${issue.method}`,
303
+ `Path: ${issue.path}`,
304
+ ...issue.hints.map((hint) => `Hint: ${hint}`)
305
+ ].join(`
306
+ `);
307
+ }
308
+ }
309
+ function formatIssues(issues) {
310
+ const missing = issues.filter((issue) => issue.kind === "missing-route");
311
+ const config = issues.filter((issue) => issue.kind === "config");
312
+ const conflicts = issues.filter((issue) => issue.kind === "docs-conflict");
313
+ const sections = [];
314
+ if (config.length > 0) {
315
+ sections.push(`${PREFIX} Invalid Configuration
316
+
317
+ ${config.map(formatIssue).join(`
318
+ `)}`);
319
+ }
320
+ if (missing.length > 0) {
321
+ const title = missing.length === 1 ? "Missing registered route:" : `Missing registered routes (${missing.length}):`;
322
+ sections.push(`${PREFIX} Strict Validation Failed
323
+
324
+ ${title}
325
+
326
+ ${missing.map(formatIssue).join(`
327
+
328
+ `)}
329
+
330
+ ${missing.length === 1 ? "The documented endpoint was" : "The documented endpoints were"} not registered in LykosJS.`);
331
+ }
332
+ if (conflicts.length > 0) {
333
+ sections.push(`${PREFIX} Documentation Path Conflict
334
+
335
+ ${conflicts.map(formatIssue).join(`
336
+ `)}`);
337
+ }
338
+ return sections.join(`
339
+
340
+ `);
341
+ }
342
+
343
+ class OpenAPIValidationError extends Error {
344
+ issues;
345
+ constructor(issues, message) {
346
+ super(message ?? formatIssues(issues));
347
+ this.name = "OpenAPIValidationError";
348
+ this.issues = Object.freeze([...issues]);
349
+ }
350
+ }
351
+
352
+ // src/core/generator.ts
353
+ function methodKey(method) {
354
+ switch (method) {
355
+ case "GET":
356
+ return "get";
357
+ case "POST":
358
+ return "post";
359
+ case "PUT":
360
+ return "put";
361
+ case "PATCH":
362
+ return "patch";
363
+ case "DELETE":
364
+ return "delete";
365
+ case "HEAD":
366
+ return "head";
367
+ }
368
+ }
369
+ function toParameters(schema, location) {
370
+ return schema.fields.map((field) => ({
371
+ name: field.name,
372
+ in: location,
373
+ required: location === "path" ? true : field.required,
374
+ schema: field.schema
375
+ }));
376
+ }
377
+ function buildParameters(route) {
378
+ const declared = new Map(route.params?.fields.map((field) => [field.name, field]) ?? []);
379
+ const pathParameters = route.pathParams.map((name) => ({
380
+ name,
381
+ in: "path",
382
+ required: true,
383
+ schema: declared.get(name)?.schema ?? { type: "string" }
384
+ }));
385
+ return [
386
+ ...pathParameters,
387
+ ...route.query ? toParameters(route.query, "query") : [],
388
+ ...route.headers ? toParameters(route.headers, "header") : []
389
+ ];
390
+ }
391
+ function buildOperation(route) {
392
+ const responses = {};
393
+ for (const response of route.responses) {
394
+ responses[String(response.status)] = response.schema ? {
395
+ description: response.description,
396
+ content: { [response.contentType]: { schema: response.schema.objectSchema } }
397
+ } : { description: response.description };
398
+ }
399
+ const parameters = buildParameters(route);
400
+ const operation = {
401
+ ...route.summary === undefined ? {} : { summary: route.summary },
402
+ ...route.description === undefined ? {} : { description: route.description },
403
+ ...route.tags !== undefined && route.tags.length > 0 ? { tags: [...route.tags] } : {},
404
+ operationId: route.key,
405
+ ...route.deprecated ? { deprecated: true } : {},
406
+ ...parameters.length > 0 ? { parameters } : {},
407
+ ...route.body ? {
408
+ requestBody: {
409
+ required: route.body.schema.fields.some((field) => field.required),
410
+ content: { [route.body.contentType]: { schema: route.body.schema.objectSchema } }
411
+ }
412
+ } : {},
413
+ responses,
414
+ ...route.security.length > 0 ? { security: route.security.map((name) => ({ [name]: [] })) } : {}
415
+ };
416
+ return operation;
417
+ }
418
+ function generateDocument(input) {
419
+ const paths = {};
420
+ for (const route of input.routes) {
421
+ const item = paths[route.path] ?? {};
422
+ const key = methodKey(route.method);
423
+ if (item[key] !== undefined) {
424
+ throw new Error(`[LykosJS OpenAPI] Refusing to overwrite ${route.method} ${route.path} (documentation key "${route.key}")`);
425
+ }
426
+ item[key] = buildOperation(route);
427
+ paths[route.path] = item;
428
+ }
429
+ const document = {
430
+ openapi: "3.1.0",
431
+ info: structuredClone(input.info),
432
+ paths
433
+ };
434
+ if (input.servers.length > 0)
435
+ document.servers = structuredClone([...input.servers]);
436
+ if (Object.keys(input.securitySchemes).length > 0) {
437
+ document.components = { securitySchemes: structuredClone({ ...input.securitySchemes }) };
438
+ }
439
+ return document;
440
+ }
441
+
442
+ // src/utils/guards.ts
443
+ function isRecord(value) {
444
+ return typeof value === "object" && value !== null && !Array.isArray(value);
445
+ }
446
+ function isNonEmptyString(value) {
447
+ return typeof value === "string" && value.trim() !== "";
448
+ }
449
+ function hasControlCharacters(value) {
450
+ for (let i = 0;i < value.length; i++) {
451
+ const code = value.charCodeAt(i);
452
+ if (code < 32 || code === 127)
453
+ return true;
454
+ }
455
+ return false;
456
+ }
457
+ function isHttpUrl(value) {
458
+ try {
459
+ const url = new URL(value);
460
+ return url.protocol === "http:" || url.protocol === "https:";
461
+ } catch {
462
+ return false;
463
+ }
464
+ }
465
+
466
+ // src/schemas/schema-converter.ts
467
+ class SchemaConversionError extends Error {
468
+ problems;
469
+ constructor(problems) {
470
+ super(problems.join("; "));
471
+ this.name = "SchemaConversionError";
472
+ this.problems = problems;
473
+ }
474
+ }
475
+ var KINDS = new Set([
476
+ "string",
477
+ "text",
478
+ "number",
479
+ "boolean",
480
+ "array",
481
+ "enum",
482
+ "date",
483
+ "object"
484
+ ]);
485
+ var DATE_PATTERN = "^\\d{4}-\\d{2}-\\d{2}(?:T\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?(?:Z|[+-]\\d{2}:\\d{2}))?$";
486
+ var DATE_DESCRIPTION = "ISO 8601: YYYY-MM-DD, or a date-time with an explicit offset (Z or \xB1HH:mm).";
487
+ function isObject(value) {
488
+ return typeof value === "object" && value !== null;
489
+ }
490
+ function readDefinition(builder) {
491
+ if (!isObject(builder))
492
+ return;
493
+ const definition = builder["definition"];
494
+ if (!isObject(definition))
495
+ return;
496
+ const kind = definition["kind"];
497
+ if (typeof kind !== "string" || !KINDS.has(kind))
498
+ return;
499
+ if (!isObject(definition["limits"]))
500
+ return;
501
+ return definition;
502
+ }
503
+ function jsonTypeOf(kind) {
504
+ switch (kind) {
505
+ case "string":
506
+ case "text":
507
+ case "enum":
508
+ case "date":
509
+ return "string";
510
+ case "number":
511
+ return "number";
512
+ case "boolean":
513
+ return "boolean";
514
+ case "array":
515
+ return "array";
516
+ case "object":
517
+ return "object";
518
+ }
519
+ }
520
+ function toObjectSchema(fields) {
521
+ const properties = {};
522
+ const required = [];
523
+ for (const field of fields) {
524
+ properties[field.name] = field.schema;
525
+ if (field.required)
526
+ required.push(field.name);
527
+ }
528
+ return {
529
+ type: "object",
530
+ properties,
531
+ ...required.length > 0 ? { required } : {}
532
+ };
533
+ }
534
+ function convertField(path, key, def, problems) {
535
+ const { kind, required, nullable, limits } = def;
536
+ if (required && nullable) {
537
+ problems.push(`field "${path}": ".required()" and ".nullable()" cannot be combined`);
538
+ return [];
539
+ }
540
+ const before = problems.length;
541
+ const schema = {};
542
+ const type = jsonTypeOf(kind);
543
+ schema.type = nullable ? [type, "null"] : type;
544
+ const isText = kind === "string" || kind === "text";
545
+ if (isText) {
546
+ if (def.email)
547
+ schema.format = "email";
548
+ if (def.url) {
549
+ schema.format = "uri";
550
+ schema.pattern = "^https?://";
551
+ }
552
+ let minLength = limits.minLength;
553
+ if (required)
554
+ minLength = Math.max(minLength ?? 0, 1);
555
+ if (minLength !== undefined)
556
+ schema.minLength = minLength;
557
+ if (limits.maxLength !== undefined)
558
+ schema.maxLength = limits.maxLength;
559
+ }
560
+ if (kind === "number") {
561
+ if (limits.min !== undefined)
562
+ schema.minimum = limits.min;
563
+ if (limits.max !== undefined)
564
+ schema.maximum = limits.max;
565
+ }
566
+ if (kind === "array") {
567
+ if (limits.minItems !== undefined)
568
+ schema.minItems = limits.minItems;
569
+ if (limits.maxItems !== undefined)
570
+ schema.maxItems = limits.maxItems;
571
+ }
572
+ if (kind === "enum") {
573
+ if (def.options === undefined || def.options.length === 0) {
574
+ problems.push(`field "${path}": enum validator has no options`);
575
+ } else {
576
+ schema.enum = nullable ? [...def.options, null] : [...def.options];
577
+ }
578
+ }
579
+ if (kind === "date") {
580
+ schema.pattern = DATE_PATTERN;
581
+ schema.description = DATE_DESCRIPTION;
582
+ }
583
+ if (kind === "object") {
584
+ if (def.shape === undefined) {
585
+ problems.push(`field "${path}": object validator has no shape`);
586
+ } else {
587
+ const nested = toObjectSchema(convertFields(def.shape, `${path}.`, problems));
588
+ schema.properties = nested.properties;
589
+ if (nested.required !== undefined)
590
+ schema.required = nested.required;
591
+ }
592
+ }
593
+ if (problems.length > before)
594
+ return [];
595
+ const converted = [{ name: key, required, schema }];
596
+ if (def.confirmed) {
597
+ const { minLength: _min, maxLength: _max, ...confirmationSchema } = schema;
598
+ converted.push({
599
+ name: `${key}Confirmation`,
600
+ required,
601
+ schema: { ...confirmationSchema, description: `Must be identical to "${key}".` }
602
+ });
603
+ }
604
+ return converted;
605
+ }
606
+ function convertFields(schema, prefix, problems) {
607
+ const fields = [];
608
+ const declared = new Set(Object.keys(schema));
609
+ const seen = new Set;
610
+ for (const [key, builder] of Object.entries(schema)) {
611
+ const path = prefix + key;
612
+ if (key === "" || key === "__proto__") {
613
+ problems.push(`invalid field name "${path}"`);
614
+ continue;
615
+ }
616
+ const def = readDefinition(builder);
617
+ if (def === undefined) {
618
+ problems.push(`field "${path}": expected a LykosJS validator such as Validator.string(3, 50).required(). ` + `Rule arrays (rules([...])) are no longer supported`);
619
+ continue;
620
+ }
621
+ const converted = convertField(path, key, def, problems);
622
+ for (const [index, field] of converted.entries()) {
623
+ if (index > 0 && declared.has(field.name))
624
+ continue;
625
+ if (seen.has(field.name))
626
+ continue;
627
+ seen.add(field.name);
628
+ fields.push(field);
629
+ }
630
+ }
631
+ return fields;
632
+ }
633
+ function convertSchema(schema) {
634
+ if (!isRecord(schema)) {
635
+ throw new SchemaConversionError([
636
+ "schema must be an object mapping field names to LykosJS validators"
637
+ ]);
638
+ }
639
+ const problems = [];
640
+ const fields = convertFields(schema, "", problems);
641
+ if (problems.length > 0)
642
+ throw new SchemaConversionError(problems);
643
+ return { fields, objectSchema: toObjectSchema(fields) };
644
+ }
645
+
646
+ // src/core/resolve-options.ts
647
+ var METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"]);
648
+ var BODY_CONTENT_TYPES = new Set([
649
+ "application/json",
650
+ "application/x-www-form-urlencoded",
651
+ "multipart/form-data"
652
+ ]);
653
+ var MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/;
654
+ var ROUTE_KEY = /^[A-Za-z_][A-Za-z0-9_.-]*$/;
655
+ var SCHEME_NAME = /^[A-Za-z0-9._-]+$/;
656
+ var METHODS_WITHOUT_BODY = new Set(["GET", "HEAD"]);
657
+ var RESERVED_HEADERS = new Set(["accept", "content-type", "authorization"]);
658
+ var BODYLESS_STATUS = (status) => status >= 100 && status < 200 || status === 204 || status === 304;
659
+ var DEFAULT_DOCS = "/docs";
660
+ var DEFAULT_JSON = "/docs/json";
661
+
662
+ class Collector {
663
+ issues = [];
664
+ add(location, message) {
665
+ this.issues.push({ kind: "config", location, message });
666
+ }
667
+ unknownKeys(value, allowed, location) {
668
+ for (const key of Object.keys(value)) {
669
+ if (!allowed.includes(key)) {
670
+ this.add(location, `unknown property "${key}" (allowed: ${allowed.join(", ")})`);
671
+ }
672
+ }
673
+ }
674
+ }
675
+ function optionalString(c, source, key, location) {
676
+ const value = source[key];
677
+ if (value === undefined)
678
+ return;
679
+ if (typeof value !== "string") {
680
+ c.add(`${location}.${key}`, "must be a string");
681
+ return;
682
+ }
683
+ return value;
684
+ }
685
+ function resolveInfo(c, raw) {
686
+ const fallback = { title: "", version: "" };
687
+ if (!isRecord(raw)) {
688
+ c.add("info", 'is required and must be an object with at least "title" and "version"');
689
+ return fallback;
690
+ }
691
+ c.unknownKeys(raw, ["title", "version", "description", "termsOfService", "contact", "license"], "info");
692
+ const title = raw["title"];
693
+ const version = raw["version"];
694
+ if (!isNonEmptyString(title))
695
+ c.add("info.title", "is required and must be a non-empty string");
696
+ if (!isNonEmptyString(version))
697
+ c.add("info.version", "is required and must be a non-empty string");
698
+ const info = {
699
+ title: isNonEmptyString(title) ? title : "",
700
+ version: isNonEmptyString(version) ? version : ""
701
+ };
702
+ const description = optionalString(c, raw, "description", "info");
703
+ if (description !== undefined)
704
+ info.description = description;
705
+ const terms = optionalString(c, raw, "termsOfService", "info");
706
+ if (terms !== undefined) {
707
+ if (isHttpUrl(terms))
708
+ info.termsOfService = terms;
709
+ else
710
+ c.add("info.termsOfService", "must be an absolute http(s) URL");
711
+ }
712
+ const contact = raw["contact"];
713
+ if (contact !== undefined) {
714
+ if (!isRecord(contact)) {
715
+ c.add("info.contact", "must be an object");
716
+ } else {
717
+ c.unknownKeys(contact, ["name", "email", "url"], "info.contact");
718
+ const out = {};
719
+ const name = optionalString(c, contact, "name", "info.contact");
720
+ if (name !== undefined)
721
+ out.name = name;
722
+ const email = optionalString(c, contact, "email", "info.contact");
723
+ if (email !== undefined) {
724
+ if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))
725
+ out.email = email;
726
+ else
727
+ c.add("info.contact.email", "must be a valid email address");
728
+ }
729
+ const url = optionalString(c, contact, "url", "info.contact");
730
+ if (url !== undefined) {
731
+ if (isHttpUrl(url))
732
+ out.url = url;
733
+ else
734
+ c.add("info.contact.url", "must be an absolute http(s) URL");
735
+ }
736
+ info.contact = out;
737
+ }
738
+ }
739
+ const license = raw["license"];
740
+ if (license !== undefined) {
741
+ if (!isRecord(license)) {
742
+ c.add("info.license", "must be an object");
743
+ } else {
744
+ c.unknownKeys(license, ["name", "url"], "info.license");
745
+ const name = license["name"];
746
+ if (!isNonEmptyString(name)) {
747
+ c.add("info.license.name", "is required and must be a non-empty string");
748
+ } else {
749
+ const out = { name };
750
+ const url = optionalString(c, license, "url", "info.license");
751
+ if (url !== undefined) {
752
+ if (isHttpUrl(url))
753
+ out.url = url;
754
+ else
755
+ c.add("info.license.url", "must be an absolute http(s) URL");
756
+ }
757
+ info.license = out;
758
+ }
759
+ }
760
+ }
761
+ return info;
762
+ }
763
+ function resolveServers(c, raw) {
764
+ if (raw === undefined)
765
+ return [];
766
+ if (!Array.isArray(raw)) {
767
+ c.add("servers", "must be an array");
768
+ return [];
769
+ }
770
+ const servers = [];
771
+ raw.forEach((entry, index) => {
772
+ const location = `servers[${index}]`;
773
+ if (!isRecord(entry))
774
+ return c.add(location, "must be an object");
775
+ c.unknownKeys(entry, ["url", "description"], location);
776
+ const url = entry["url"];
777
+ if (typeof url !== "string" || !(isHttpUrl(url) || url.startsWith("/") && !/[\s\\]/.test(url))) {
778
+ return c.add(`${location}.url`, 'must be an absolute http(s) URL or a path starting with "/"');
779
+ }
780
+ const description = optionalString(c, entry, "description", location);
781
+ servers.push(description === undefined ? { url } : { url, description });
782
+ });
783
+ return servers;
784
+ }
785
+ function resolveSecuritySchemes(c, raw) {
786
+ const schemes = {};
787
+ if (raw === undefined)
788
+ return schemes;
789
+ if (!isRecord(raw)) {
790
+ c.add("securitySchemes", "must be an object");
791
+ return schemes;
792
+ }
793
+ for (const [name, value] of Object.entries(raw)) {
794
+ const location = `securitySchemes.${name}`;
795
+ if (!SCHEME_NAME.test(name)) {
796
+ c.add(location, `invalid scheme name (allowed characters: ${SCHEME_NAME.source})`);
797
+ continue;
798
+ }
799
+ if (!isRecord(value)) {
800
+ c.add(location, "must be an object");
801
+ continue;
802
+ }
803
+ const description = optionalString(c, value, "description", location);
804
+ const withDescription = (scheme) => description === undefined ? scheme : { ...scheme, description };
805
+ if (value["type"] === "http") {
806
+ c.unknownKeys(value, ["type", "scheme", "bearerFormat", "description"], location);
807
+ if (value["scheme"] !== "bearer") {
808
+ c.add(`${location}.scheme`, 'only "bearer" is supported for type "http"');
809
+ continue;
810
+ }
811
+ const bearerFormat = optionalString(c, value, "bearerFormat", location);
812
+ schemes[name] = withDescription({
813
+ type: "http",
814
+ scheme: "bearer",
815
+ ...bearerFormat === undefined ? {} : { bearerFormat }
816
+ });
817
+ } else if (value["type"] === "apiKey") {
818
+ c.unknownKeys(value, ["type", "in", "name", "description"], location);
819
+ const where = value["in"];
820
+ const keyName = value["name"];
821
+ if (where !== "header" && where !== "query" && where !== "cookie") {
822
+ c.add(`${location}.in`, 'must be "header", "query" or "cookie"');
823
+ continue;
824
+ }
825
+ if (!isNonEmptyString(keyName) || /[\s]/.test(keyName)) {
826
+ c.add(`${location}.name`, "is required and must be a non-empty string without whitespace");
827
+ continue;
828
+ }
829
+ schemes[name] = withDescription({ type: "apiKey", in: where, name: keyName });
830
+ } else {
831
+ c.add(`${location}.type`, 'must be "http" (bearer) or "apiKey"');
832
+ }
833
+ }
834
+ return schemes;
835
+ }
836
+ function resolveEndpointPath(c, raw, location) {
837
+ if (raw === undefined)
838
+ return;
839
+ if (raw === false)
840
+ return false;
841
+ const parsed = parsePath(raw);
842
+ if (!parsed.ok) {
843
+ c.add(location, parsed.reason);
844
+ return;
845
+ }
846
+ if (parsed.path.params.length > 0) {
847
+ c.add(location, "documentation paths cannot contain parameters");
848
+ return;
849
+ }
850
+ return parsed.path.canonical;
851
+ }
852
+ function resolveSwaggerUI(c, raw, title) {
853
+ const ui = { title, persistAuthorization: false, docExpansion: "list" };
854
+ if (raw === undefined)
855
+ return ui;
856
+ if (!isRecord(raw)) {
857
+ c.add("swaggerUI", "must be an object");
858
+ return ui;
859
+ }
860
+ c.unknownKeys(raw, ["title", "persistAuthorization", "docExpansion"], "swaggerUI");
861
+ const uiTitle = raw["title"];
862
+ if (uiTitle !== undefined) {
863
+ if (isNonEmptyString(uiTitle) && !hasControlCharacters(uiTitle))
864
+ ui.title = uiTitle;
865
+ else
866
+ c.add("swaggerUI.title", "must be a non-empty single-line string");
867
+ }
868
+ const persist = raw["persistAuthorization"];
869
+ if (persist !== undefined) {
870
+ if (typeof persist === "boolean")
871
+ ui.persistAuthorization = persist;
872
+ else
873
+ c.add("swaggerUI.persistAuthorization", "must be a boolean");
874
+ }
875
+ const expansion = raw["docExpansion"];
876
+ if (expansion !== undefined) {
877
+ if (expansion === "list" || expansion === "full" || expansion === "none") {
878
+ ui.docExpansion = expansion;
879
+ } else {
880
+ c.add("swaggerUI.docExpansion", 'must be "list", "full" or "none"');
881
+ }
882
+ }
883
+ return ui;
884
+ }
885
+ function convert(c, raw, location) {
886
+ try {
887
+ return convertSchema(raw);
888
+ } catch (error) {
889
+ if (error instanceof SchemaConversionError) {
890
+ for (const problem of error.problems)
891
+ c.add(location, problem);
892
+ return;
893
+ }
894
+ throw error;
895
+ }
896
+ }
897
+ function resolveRoute(c, key, raw, securityNames) {
898
+ const base = `routes.${key}`;
899
+ if (!ROUTE_KEY.test(key)) {
900
+ c.add(base, `invalid documentation key (allowed characters: ${ROUTE_KEY.source})`);
901
+ return;
902
+ }
903
+ if (!isRecord(raw)) {
904
+ c.add(base, "must be an object");
905
+ return;
906
+ }
907
+ const before = c.issues.length;
908
+ c.unknownKeys(raw, [
909
+ "method",
910
+ "path",
911
+ "summary",
912
+ "description",
913
+ "tags",
914
+ "isRequired",
915
+ "deprecated",
916
+ "request",
917
+ "response",
918
+ "security"
919
+ ], base);
920
+ const rawMethod = raw["method"];
921
+ let method;
922
+ if (typeof rawMethod !== "string" || !METHODS.has(rawMethod)) {
923
+ c.add(`${base}.method`, rawMethod === "OPTIONS" ? "OPTIONS cannot be documented: LykosJS answers every OPTIONS request (CORS preflight) before routing" : `must be one of ${[...METHODS].join(", ")}`);
924
+ } else {
925
+ method = rawMethod;
926
+ }
927
+ const parsedPath = parsePath(raw["path"]);
928
+ if (!parsedPath.ok)
929
+ c.add(`${base}.path`, parsedPath.reason);
930
+ const summary = optionalString(c, raw, "summary", base);
931
+ const description = optionalString(c, raw, "description", base);
932
+ if (summary !== undefined && hasControlCharacters(summary)) {
933
+ c.add(`${base}.summary`, "must be a single-line string");
934
+ }
935
+ let tags;
936
+ if (raw["tags"] !== undefined) {
937
+ const rawTags = raw["tags"];
938
+ if (!Array.isArray(rawTags) || !rawTags.every(isNonEmptyString)) {
939
+ c.add(`${base}.tags`, "must be an array of non-empty strings");
940
+ } else {
941
+ tags = [...new Set(rawTags)];
942
+ }
943
+ }
944
+ const isRequired = raw["isRequired"];
945
+ if (isRequired !== undefined && typeof isRequired !== "boolean") {
946
+ c.add(`${base}.isRequired`, "must be a boolean");
947
+ }
948
+ const deprecated = raw["deprecated"];
949
+ if (deprecated !== undefined && typeof deprecated !== "boolean") {
950
+ c.add(`${base}.deprecated`, "must be a boolean");
951
+ }
952
+ let security = [];
953
+ if (raw["security"] !== undefined) {
954
+ const rawSecurity = raw["security"];
955
+ if (!Array.isArray(rawSecurity) || !rawSecurity.every(isNonEmptyString)) {
956
+ c.add(`${base}.security`, "must be an array of security scheme names");
957
+ } else {
958
+ security = [...new Set(rawSecurity)];
959
+ for (const name of security) {
960
+ if (!securityNames.has(name)) {
961
+ c.add(`${base}.security`, `unknown security scheme "${name}" (declare it in securitySchemes)`);
962
+ }
963
+ }
964
+ }
965
+ }
966
+ let body;
967
+ let query;
968
+ let params;
969
+ let headers;
970
+ const pathParamNames = parsedPath.ok ? parsedPath.path.params : [];
971
+ const request = raw["request"];
972
+ if (request !== undefined) {
973
+ const rl = `${base}.request`;
974
+ if (!isRecord(request)) {
975
+ c.add(rl, "must be an object");
976
+ } else {
977
+ c.unknownKeys(request, ["body", "contentType", "query", "params", "headers"], rl);
978
+ const contentType = request["contentType"];
979
+ if (contentType !== undefined && (typeof contentType !== "string" || !BODY_CONTENT_TYPES.has(contentType))) {
980
+ c.add(`${rl}.contentType`, `must be one of ${[...BODY_CONTENT_TYPES].join(", ")}`);
981
+ }
982
+ if (request["body"] !== undefined) {
983
+ if (method !== undefined && METHODS_WITHOUT_BODY.has(method)) {
984
+ c.add(`${rl}.body`, `${method} requests must not have a request body`);
985
+ } else {
986
+ const schema = convert(c, request["body"], `${rl}.body`);
987
+ if (schema) {
988
+ body = {
989
+ schema,
990
+ contentType: typeof contentType === "string" ? contentType : "application/json"
991
+ };
992
+ }
993
+ }
994
+ } else if (contentType !== undefined) {
995
+ c.add(`${rl}.contentType`, 'is only valid together with "body"');
996
+ }
997
+ if (request["query"] !== undefined)
998
+ query = convert(c, request["query"], `${rl}.query`);
999
+ if (request["headers"] !== undefined) {
1000
+ headers = convert(c, request["headers"], `${rl}.headers`);
1001
+ for (const field of headers?.fields ?? []) {
1002
+ if (RESERVED_HEADERS.has(field.name.toLowerCase())) {
1003
+ c.add(`${rl}.headers`, `header "${field.name}" is reserved by OpenAPI; document it with "security" or "body.contentType" instead`);
1004
+ }
1005
+ }
1006
+ }
1007
+ if (request["params"] !== undefined) {
1008
+ params = convert(c, request["params"], `${rl}.params`);
1009
+ for (const field of params?.fields ?? []) {
1010
+ if (!pathParamNames.includes(field.name)) {
1011
+ c.add(`${rl}.params`, `field "${field.name}" is not a parameter of path "${typeof raw["path"] === "string" ? raw["path"] : ""}"`);
1012
+ } else if (Array.isArray(field.schema.type)) {
1013
+ c.add(`${rl}.params`, `path parameter "${field.name}" cannot be nullable`);
1014
+ }
1015
+ }
1016
+ }
1017
+ }
1018
+ }
1019
+ const responses = [];
1020
+ const rawResponses = raw["response"];
1021
+ if (!isRecord(rawResponses)) {
1022
+ c.add(`${base}.response`, "is required and must be an object keyed by HTTP status code");
1023
+ } else {
1024
+ const entries = Object.entries(rawResponses);
1025
+ if (entries.length === 0)
1026
+ c.add(`${base}.response`, "must document at least one status code");
1027
+ for (const [statusKey, value] of entries) {
1028
+ const rl = `${base}.response.${statusKey}`;
1029
+ const status = Number(statusKey);
1030
+ if (!/^[1-5]\d\d$/.test(statusKey) || !Number.isInteger(status)) {
1031
+ c.add(rl, "invalid HTTP status code (expected an integer between 100 and 599)");
1032
+ continue;
1033
+ }
1034
+ if (!isRecord(value)) {
1035
+ c.add(rl, "must be an object");
1036
+ continue;
1037
+ }
1038
+ c.unknownKeys(value, ["description", "schema", "contentType"], rl);
1039
+ const responseDescription = value["description"];
1040
+ if (!isNonEmptyString(responseDescription)) {
1041
+ c.add(`${rl}.description`, "is required and must be a non-empty string");
1042
+ continue;
1043
+ }
1044
+ const rawContentType = value["contentType"];
1045
+ if (rawContentType !== undefined && (typeof rawContentType !== "string" || !MEDIA_TYPE.test(rawContentType))) {
1046
+ c.add(`${rl}.contentType`, 'must be a valid lowercase media type (e.g. "application/json")');
1047
+ continue;
1048
+ }
1049
+ let schema;
1050
+ if (value["schema"] !== undefined) {
1051
+ if (BODYLESS_STATUS(status)) {
1052
+ c.add(`${rl}.schema`, `status ${status} cannot have a response body`);
1053
+ } else {
1054
+ schema = convert(c, value["schema"], `${rl}.schema`);
1055
+ }
1056
+ } else if (rawContentType !== undefined) {
1057
+ c.add(`${rl}.contentType`, 'is only valid together with "schema"');
1058
+ }
1059
+ responses.push({
1060
+ status,
1061
+ description: responseDescription,
1062
+ ...schema ? { schema } : {},
1063
+ contentType: typeof rawContentType === "string" ? rawContentType : "application/json"
1064
+ });
1065
+ }
1066
+ }
1067
+ if (c.issues.length > before || method === undefined || !parsedPath.ok)
1068
+ return;
1069
+ return {
1070
+ key,
1071
+ method,
1072
+ path: parsedPath.path.canonical,
1073
+ shape: parsedPath.path.shape,
1074
+ pathParams: parsedPath.path.params,
1075
+ ...summary === undefined ? {} : { summary },
1076
+ ...description === undefined ? {} : { description },
1077
+ ...tags === undefined ? {} : { tags },
1078
+ deprecated: deprecated === true,
1079
+ isRequired: isRequired !== false,
1080
+ security,
1081
+ ...body ? { body } : {},
1082
+ ...query ? { query } : {},
1083
+ ...params ? { params } : {},
1084
+ ...headers ? { headers } : {},
1085
+ responses: responses.sort((a, b) => a.status - b.status)
1086
+ };
1087
+ }
1088
+ var TOP_LEVEL_KEYS = [
1089
+ "info",
1090
+ "docs",
1091
+ "json",
1092
+ "routes",
1093
+ "servers",
1094
+ "securitySchemes",
1095
+ "middlewares",
1096
+ "swaggerUI"
1097
+ ];
1098
+ function resolveOptions(options) {
1099
+ const c = new Collector;
1100
+ if (!isRecord(options)) {
1101
+ throw new OpenAPIValidationError([
1102
+ { kind: "config", location: "options", message: "must be an object" }
1103
+ ]);
1104
+ }
1105
+ c.unknownKeys(options, TOP_LEVEL_KEYS, "options");
1106
+ const info = resolveInfo(c, options["info"]);
1107
+ const servers = resolveServers(c, options["servers"]);
1108
+ const securitySchemes = resolveSecuritySchemes(c, options["securitySchemes"]);
1109
+ const docs = resolveEndpointPath(c, options["docs"], "docs");
1110
+ const json = resolveEndpointPath(c, options["json"], "json");
1111
+ const docsPath = docs === undefined ? DEFAULT_DOCS : docs === false ? undefined : docs;
1112
+ const jsonPath = json === undefined ? DEFAULT_JSON : json === false ? undefined : json;
1113
+ if (docsPath !== undefined && jsonPath === undefined) {
1114
+ c.add("json", 'cannot be disabled while Swagger UI ("docs") is enabled: the UI reads the JSON endpoint');
1115
+ }
1116
+ if (docsPath !== undefined && docsPath === jsonPath) {
1117
+ c.add("json", '"docs" and "json" must use different paths');
1118
+ }
1119
+ const rawMiddlewares = options["middlewares"];
1120
+ let middlewares = [];
1121
+ if (rawMiddlewares !== undefined) {
1122
+ if (!Array.isArray(rawMiddlewares) || !rawMiddlewares.every((m) => typeof m === "function")) {
1123
+ c.add("middlewares", "must be an array of LykosJS middleware functions");
1124
+ } else {
1125
+ middlewares = [...rawMiddlewares];
1126
+ }
1127
+ }
1128
+ const swaggerUI = resolveSwaggerUI(c, options["swaggerUI"], info.title || "API Documentation");
1129
+ const routes = [];
1130
+ const rawRoutes = options["routes"];
1131
+ if (!isRecord(rawRoutes)) {
1132
+ c.add("routes", "is required and must be an object (use {} for no routes)");
1133
+ } else {
1134
+ const securityNames = new Set(Object.keys(securitySchemes));
1135
+ for (const [key, value] of Object.entries(rawRoutes)) {
1136
+ const route = resolveRoute(c, key, value, securityNames);
1137
+ if (route)
1138
+ routes.push(route);
1139
+ }
1140
+ const seen = new Map;
1141
+ for (const route of routes) {
1142
+ const identity = `${route.method} ${route.shape}`;
1143
+ const previous = seen.get(identity);
1144
+ if (previous) {
1145
+ c.add(`routes.${route.key}`, `conflicts with routes.${previous.key}: both document ${route.method} ${route.path} (${previous.path})`);
1146
+ } else {
1147
+ seen.set(identity, route);
1148
+ }
1149
+ }
1150
+ }
1151
+ if (c.issues.length > 0)
1152
+ throw new OpenAPIValidationError(c.issues);
1153
+ return {
1154
+ info,
1155
+ servers,
1156
+ securitySchemes,
1157
+ docsPath,
1158
+ jsonPath,
1159
+ middlewares,
1160
+ swaggerUI,
1161
+ routes
1162
+ };
1163
+ }
1164
+
1165
+ // src/core/openapi.ts
1166
+ function assertApplication(app) {
1167
+ const candidate = app;
1168
+ if (typeof candidate !== "object" || candidate === null || typeof candidate.GET !== "function") {
1169
+ throw new OpenAPIValidationError([], "[LykosJS OpenAPI] setup() expects a LykosJS application instance.");
1170
+ }
1171
+ if (typeof candidate.readRoutes !== "function") {
1172
+ throw new OpenAPIValidationError([], "[LykosJS OpenAPI] Incompatible LykosJS application: it has no readRoutes() route introspection API.");
1173
+ }
1174
+ }
1175
+
1176
+ class OpenAPIManager {
1177
+ #options;
1178
+ #app;
1179
+ #document;
1180
+ constructor(options) {
1181
+ this.#options = resolveOptions(options);
1182
+ }
1183
+ generate(app) {
1184
+ assertApplication(app);
1185
+ return this.#build(app);
1186
+ }
1187
+ setup(app) {
1188
+ assertApplication(app);
1189
+ if (this.#app !== undefined) {
1190
+ if (this.#app === app)
1191
+ return;
1192
+ throw new OpenAPIValidationError([], "[LykosJS OpenAPI] This OpenAPI instance is already set up with another application. Create a new OpenAPI instance per application.");
1193
+ }
1194
+ const { docsPath, jsonPath, middlewares, swaggerUI } = this.#options;
1195
+ const document = this.#build(app);
1196
+ const json = JSON.stringify(document);
1197
+ const routes = createDocsRoutes({ docsPath, jsonPath, json, ui: swaggerUI });
1198
+ for (const route of routes) {
1199
+ app.GET(route.path, route.handler, ...middlewares);
1200
+ }
1201
+ this.#document = document;
1202
+ this.#app = app;
1203
+ }
1204
+ getDocument() {
1205
+ if (this.#document === undefined) {
1206
+ throw new Error("[LykosJS OpenAPI] getDocument() is only available after setup(app).");
1207
+ }
1208
+ return structuredClone(this.#document);
1209
+ }
1210
+ #build(app) {
1211
+ const registered = app.readRoutes();
1212
+ const { docsPath, jsonPath } = this.#options;
1213
+ const issues = [];
1214
+ const { issues: missing, active } = validateRegisteredRoutes(this.#options.routes, registered);
1215
+ issues.push(...missing);
1216
+ const endpoints = [
1217
+ ...jsonPath === undefined ? [] : [{ target: "json", path: jsonPath }],
1218
+ ...docsPath === undefined ? [] : [
1219
+ { target: "docs", path: docsPath },
1220
+ { target: "docs assets", path: `${assetBase(docsPath)}/init.js` }
1221
+ ]
1222
+ ];
1223
+ issues.push(...findDocsConflicts(endpoints, registered));
1224
+ if (issues.length > 0)
1225
+ throw new OpenAPIValidationError(issues);
1226
+ return generateDocument({
1227
+ info: this.#options.info,
1228
+ servers: this.#options.servers,
1229
+ securitySchemes: this.#options.securitySchemes,
1230
+ routes: active
1231
+ });
1232
+ }
1233
+ }
1234
+ export {
1235
+ OpenAPIManager,
1236
+ OpenAPIValidationError
1237
+ };