@sdk-it/openapi 0.0.0-stage → 0.51.4
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/README.md +236 -2
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +113 -0
- package/dist/index.js.map +7 -0
- package/dist/lib/definition.d.ts +58 -0
- package/dist/lib/definition.d.ts.map +1 -0
- package/dist/lib/generate-document.d.ts +19 -0
- package/dist/lib/generate-document.d.ts.map +1 -0
- package/package.json +35 -4
package/README.md
CHANGED
|
@@ -1,3 +1,237 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @sdk-it/openapi
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Produces the OpenAPI document of a TypeScript backend from its code. `@sdk-it/spec` loads a document; this package writes one.
|
|
4
|
+
|
|
5
|
+
The backend says, in one TypeScript module, what its code cannot tell: the document's `info`, its servers and security schemes, its tag descriptions, and the transformers it wants. The analysis finds the routes, their inputs and their responses.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
// apps/backend/openapi.ts
|
|
9
|
+
import { defineOpenApi } from '@sdk-it/openapi';
|
|
10
|
+
|
|
11
|
+
export default defineOpenApi({
|
|
12
|
+
tsconfig: new URL('./tsconfig.app.json', import.meta.url),
|
|
13
|
+
document: {
|
|
14
|
+
openapi: '3.1.0',
|
|
15
|
+
info: { title: 'Meddit API', version: '1.0.0' },
|
|
16
|
+
},
|
|
17
|
+
});
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Three hosts read this module:
|
|
21
|
+
|
|
22
|
+
- `sdk-it generate` writes a client package from it.
|
|
23
|
+
- The content mapper, `sdkIt.imports()` and the Node register hook serve it as a module to an app that imports the backend's document (`import { createBackend } from './backend.openapi'`).
|
|
24
|
+
- Any script calls `generateDocument` itself.
|
|
25
|
+
|
|
26
|
+
## Produce a document
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { generateDocument } from '@sdk-it/openapi';
|
|
30
|
+
|
|
31
|
+
import definition from './openapi.ts';
|
|
32
|
+
|
|
33
|
+
const { document, sourceFiles } = await generateDocument(definition);
|
|
34
|
+
// document: the OpenAPI document
|
|
35
|
+
// sourceFiles: every file of the backend's program outside node_modules; a change to one can change the document
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
`generateDocument` writes nothing. Writing the document, watching `sourceFiles` and rendering a client are the host's job.
|
|
39
|
+
|
|
40
|
+
## Describe what the code cannot tell
|
|
41
|
+
|
|
42
|
+
`document` holds only what code cannot know:
|
|
43
|
+
|
|
44
|
+
- `openapi` and `info`, both required; the package invents no title and no version
|
|
45
|
+
- `servers`
|
|
46
|
+
- `security`
|
|
47
|
+
- `externalDocs`
|
|
48
|
+
- `components.securitySchemes`
|
|
49
|
+
- tag objects (`description`, `x-*`)
|
|
50
|
+
|
|
51
|
+
Everything else comes from the analysis: the paths, every schema and every response. That includes what `validate()`, a middleware and the app's notFound handler send. What `app.onError` sends for each thrown error is the next analysis fact ([ADR 0008](docs/adr/0008-the-analysis-documents-what-the-error-handler-sends-for-each-error-a-route-can-throw.md)); until it lands, write it with a transformer. A `BaseDocument` cannot hold `paths`, `components.schemas` or `components.responses`, so nothing written by hand competes with what the analysis finds. Each tag an operation names gets a tag object, with the fields of the base's tag object of that name. A fact the analysis still misses goes in a transformer, as code.
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
document: {
|
|
55
|
+
openapi: '3.1.0',
|
|
56
|
+
info: { title: 'Agent API', version: '1.0.0' },
|
|
57
|
+
servers: [{ url: 'https://api.example.com' }],
|
|
58
|
+
security: [{ bearer: [] }],
|
|
59
|
+
tags: [{ name: 'users', description: 'User management.' }],
|
|
60
|
+
components: {
|
|
61
|
+
securitySchemes: { bearer: { type: 'http', scheme: 'bearer' } },
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## What the analysis documents for each route
|
|
67
|
+
|
|
68
|
+
| Response | Comes from |
|
|
69
|
+
| -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
70
|
+
| what the handler returns (`c.json`, `output.ok`, streams) | `@sdk-it/hono`'s response analyzer |
|
|
71
|
+
| `validate()`'s 400 and 415 | `@sdk-it/hono`, one shared component each |
|
|
72
|
+
| what a middleware the route passes sends itself (`c.json({ error }, 401)`) | the middleware's own returns ([ADR 0005](docs/adr/0005-the-analysis-documents-the-responses-a-middleware-sends-itself.md)) |
|
|
73
|
+
| what `app.notFound` sends, on a route that returns `c.notFound()` | the app's notFound handler, or Hono's default 404 ([ADR 0008](docs/adr/0008-the-analysis-documents-what-the-error-handler-sends-for-each-error-a-route-can-throw.md)) |
|
|
74
|
+
|
|
75
|
+
## Map a type to a schema
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
types: {
|
|
79
|
+
UIMessage: { type: 'object' },
|
|
80
|
+
},
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
When the analysis meets a type of that name, it writes that schema in its place. `types` is added onto the defaults (streams and binary arrays as `{}`, `DateConstructor` as `{ type: 'string' }`). The Prisma preset adds `Decimal: { type: 'string' }`.
|
|
84
|
+
|
|
85
|
+
## Mark routes with their security
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
middlewareSecurity: [
|
|
89
|
+
{
|
|
90
|
+
middleware: { import: 'authenticate', from: new URL('./src/middlewares/auth.ts', import.meta.url) },
|
|
91
|
+
security: [{ bearer: [] }],
|
|
92
|
+
},
|
|
93
|
+
],
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Each route that a matching middleware guards gets that `security`. A route that no rule matches gets `security: []`, which means public.
|
|
97
|
+
|
|
98
|
+
## Transform operations and the document
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
transformers: {
|
|
102
|
+
operation: [
|
|
103
|
+
(operation, { method, path }) => {
|
|
104
|
+
if (path.startsWith('/admin')) operation.tags = ['admin'];
|
|
105
|
+
},
|
|
106
|
+
],
|
|
107
|
+
document: [
|
|
108
|
+
(document) => {
|
|
109
|
+
document.info.description = 'Generated from the backend.';
|
|
110
|
+
},
|
|
111
|
+
],
|
|
112
|
+
},
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Operation transformers run once for each operation, in the order given, on the document the analysis and the base put together. Document transformers then run once, in the order given, on the finished document. A transformer changes its argument in place, may be `async`, and returns nothing.
|
|
116
|
+
|
|
117
|
+
## Prisma
|
|
118
|
+
|
|
119
|
+
When a route file imports `Prisma` or `$Enums` from a Prisma client by name, the Prisma preset applies:
|
|
120
|
+
|
|
121
|
+
- An `against` may read those two imports.
|
|
122
|
+
- `Decimal` maps to `{ type: 'string' }`.
|
|
123
|
+
- A client that is not generated fails with `PrismaClientNotGeneratedError`.
|
|
124
|
+
|
|
125
|
+
Prisma's `JsonValue` and `JsonObject` need nothing: the analysis writes them as recursive components.
|
|
126
|
+
|
|
127
|
+
`allowedNamedImports` names more imports that an `against` may read, such as a second Prisma client imported under another name:
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
allowedNamedImports: ['CentralPrisma'],
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## Signatures
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
export function defineOpenApi(definition: OpenApiDefinition): OpenApiDefinition;
|
|
137
|
+
export function generateDocument(
|
|
138
|
+
definition: OpenApiDefinition,
|
|
139
|
+
): Promise<GeneratedDocument>;
|
|
140
|
+
|
|
141
|
+
export interface OpenApiDefinition {
|
|
142
|
+
tsconfig: URL;
|
|
143
|
+
document: BaseDocument;
|
|
144
|
+
types?: Readonly<Record<string, SchemaObject>>;
|
|
145
|
+
allowedNamedImports?: readonly string[];
|
|
146
|
+
middlewareSecurity?: readonly MiddlewareSecurityRule[];
|
|
147
|
+
transformers?: {
|
|
148
|
+
operation?: readonly OperationTransformer[];
|
|
149
|
+
document?: readonly DocumentTransformer[];
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** What code cannot know about an OpenAPI 3.1 or 3.2 document. */
|
|
154
|
+
export interface BaseDocument {
|
|
155
|
+
openapi: '3.1.0' | '3.2.0';
|
|
156
|
+
info: InfoObject;
|
|
157
|
+
servers?: ServerObject[];
|
|
158
|
+
security?: SecurityRequirementObject[];
|
|
159
|
+
externalDocs?: ExternalDocumentationObject;
|
|
160
|
+
tags?: TagObject[];
|
|
161
|
+
components?: { securitySchemes?: Record<string, SecuritySchemeObject> };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export interface MiddlewareSecurityRule {
|
|
165
|
+
middleware: { import: string; from: URL };
|
|
166
|
+
security: SecurityRequirementObject[];
|
|
167
|
+
values?: { scheme: string; argument: number; mode: 'any' | 'all' };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export type OperationTransformer = (
|
|
171
|
+
operation: OperationObject,
|
|
172
|
+
context: { method: HttpMethod; path: string; document: OpenAPIObject },
|
|
173
|
+
) => void | Promise<void>;
|
|
174
|
+
|
|
175
|
+
export type DocumentTransformer = (
|
|
176
|
+
document: OpenAPIObject,
|
|
177
|
+
) => void | Promise<void>;
|
|
178
|
+
|
|
179
|
+
export interface GeneratedDocument {
|
|
180
|
+
document: OpenAPIObject;
|
|
181
|
+
sourceFiles: string[];
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export class PrismaClientNotGeneratedError extends Error {
|
|
185
|
+
readonly routeFile: string;
|
|
186
|
+
readonly importName: string;
|
|
187
|
+
}
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
## What happens on each call
|
|
191
|
+
|
|
192
|
+
| You call | Underneath |
|
|
193
|
+
| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
194
|
+
| `generateDocument(definition)` | `openAnalysisProject(fileURLToPath(tsconfig))` from `@sdk-it/core` opens the backend's program |
|
|
195
|
+
| | the Prisma preset applies when a route file imports `Prisma` or `$Enums` by name |
|
|
196
|
+
| | `analyze(project, { responseAnalyzer, types, allowedNamedImports, middlewareSecurity })` from `@sdk-it/generic`, with `@sdk-it/hono`'s `responseAnalyzer` |
|
|
197
|
+
| | each operation transformer runs on each operation |
|
|
198
|
+
| | the document is `document`'s fields, the analysis's `paths` and `components`, and a tag object for each tag an operation names (the base's fields kept) |
|
|
199
|
+
| | each document transformer runs on the document |
|
|
200
|
+
| | `sourceFiles` is the program's files outside `node_modules`, workspace packages read as source included |
|
|
201
|
+
|
|
202
|
+
## Errors
|
|
203
|
+
|
|
204
|
+
| Error | When | The caller's next step |
|
|
205
|
+
| ----------------------------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------- |
|
|
206
|
+
| `PrismaClientNotGeneratedError` | a route file imports `Prisma` or `$Enums`, and the client does not load | run the Prisma client's generate target |
|
|
207
|
+
| `UnresolvedTypeError` (`@sdk-it/core`) | a response type does not resolve | fix the type; the error names the route and the response's position |
|
|
208
|
+
| `UnloadedImportError` (`@sdk-it/generic`) | another named import an `against` reads does not load | fix the import |
|
|
209
|
+
|
|
210
|
+
## The same concepts in other systems
|
|
211
|
+
|
|
212
|
+
| System | Same concept |
|
|
213
|
+
| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
214
|
+
| .NET `Microsoft.AspNetCore.OpenApi` | `AddOpenApi(options => …)` builds the app's document from its endpoints. Operation and document transformers (`AddOperationTransformer`, `AddDocumentTransformer`) run in the order added, operations first. |
|
|
215
|
+
| .NET `Microsoft.Extensions.ApiDescription.Server` | generates the document at build time |
|
|
216
|
+
| Go huma | `huma.OpenAPI` is built from registered operations; `config.Components.SecuritySchemes` holds the schemes |
|
|
217
|
+
| `hono-openapi` | `generateSpecs(app, { documentation })`: a base document merged into the generated one |
|
|
218
|
+
|
|
219
|
+
## Why not a package from npm
|
|
220
|
+
|
|
221
|
+
Requirement: document a Hono route as written, `router.get(path, validate(...), handler)`, with the response type read from what the handler returns, and no annotation on the route.
|
|
222
|
+
|
|
223
|
+
| Package | Version (2026-11-21) | Weekly downloads | Result on that route |
|
|
224
|
+
| ------------------- | -------------------- | ---------------- | --------------------------------------------------------------------------- |
|
|
225
|
+
| `hono-openapi` | 1.6.0 | 4.4M | `"paths": {}`: it documents only routes that `describeRoute(...)` annotates |
|
|
226
|
+
| `@hono/zod-openapi` | 1.6.3 | 5.0M | `"paths": {}`: it documents only routes that `createRoute(...)` declares |
|
|
227
|
+
|
|
228
|
+
Node 26 has no built-in that produces an OpenAPI document. The `@stdlib` scope has none.
|
|
229
|
+
|
|
230
|
+
## Who uses what
|
|
231
|
+
|
|
232
|
+
| Consumer | Uses |
|
|
233
|
+
| ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------- |
|
|
234
|
+
| `@sdk-it/cli` | `generateDocument`; `defineConfig({ openapi, name, packageName })` takes an `OpenApiDefinition` |
|
|
235
|
+
| `@sdk-it/content-mapper` | `generateDocument` for a derived document: it watches `sourceFiles`, renders the client and writes the document |
|
|
236
|
+
| `@sdk-it/vite` `sdkIt.imports()` | the same, through content-mapper's `DerivedDocument` |
|
|
237
|
+
| 15 hand-written `openapi.ts` scripts in 13 repos | replaced by an `openapi.ts` that calls `defineOpenApi`; one migration backlog item per repo |
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,qBAAqB,CAAC;AACpC,cAAc,4BAA4B,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// packages/openapi/src/lib/definition.ts
|
|
2
|
+
function defineOpenApi(definition) {
|
|
3
|
+
return definition;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
// packages/openapi/src/lib/generate-document.ts
|
|
7
|
+
import { isImportDeclaration, isNamedImports } from "@typescript/native/ast/is";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { methods } from "@sdk-it/core";
|
|
10
|
+
import {
|
|
11
|
+
openAnalysisProject,
|
|
12
|
+
sourceFiles
|
|
13
|
+
} from "@sdk-it/core/program.js";
|
|
14
|
+
import { UnloadedImportError, analyze } from "@sdk-it/generic";
|
|
15
|
+
import { responseAnalyzer } from "@sdk-it/hono";
|
|
16
|
+
var prismaBindings = ["$Enums", "Prisma"];
|
|
17
|
+
var PrismaClientNotGeneratedError = class extends Error {
|
|
18
|
+
routeFile;
|
|
19
|
+
importName;
|
|
20
|
+
constructor(message, routeFile, importName, cause) {
|
|
21
|
+
super(message, { cause });
|
|
22
|
+
this.name = "PrismaClientNotGeneratedError";
|
|
23
|
+
this.routeFile = routeFile;
|
|
24
|
+
this.importName = importName;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
async function generateDocument(definition) {
|
|
28
|
+
using project = openAnalysisProject(fileURLToPath(definition.tsconfig));
|
|
29
|
+
const prisma = importsPrisma(project);
|
|
30
|
+
let analysis;
|
|
31
|
+
try {
|
|
32
|
+
analysis = await analyze(project, {
|
|
33
|
+
responseAnalyzer,
|
|
34
|
+
types: {
|
|
35
|
+
...prisma ? { Decimal: { type: "string" } } : {},
|
|
36
|
+
...definition.types
|
|
37
|
+
},
|
|
38
|
+
allowedNamedImports: [
|
|
39
|
+
...prisma ? prismaBindings : [],
|
|
40
|
+
...definition.allowedNamedImports ?? []
|
|
41
|
+
],
|
|
42
|
+
...definition.middlewareSecurity ? {
|
|
43
|
+
middlewareSecurity: definition.middlewareSecurity.map((rule) => ({
|
|
44
|
+
...rule,
|
|
45
|
+
middleware: {
|
|
46
|
+
import: rule.middleware.import,
|
|
47
|
+
from: fileURLToPath(rule.middleware.from)
|
|
48
|
+
}
|
|
49
|
+
}))
|
|
50
|
+
} : {}
|
|
51
|
+
});
|
|
52
|
+
} catch (error) {
|
|
53
|
+
if (prisma && error instanceof UnloadedImportError && error.binding.property !== void 0 && prismaBindings.includes(error.binding.property)) {
|
|
54
|
+
throw new PrismaClientNotGeneratedError(
|
|
55
|
+
`${error.message}
|
|
56
|
+
Run the Prisma client's generate target (prisma generate).`,
|
|
57
|
+
error.binding.referrer,
|
|
58
|
+
error.binding.property,
|
|
59
|
+
error
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
const base = structuredClone(definition.document);
|
|
65
|
+
const document = {
|
|
66
|
+
...base,
|
|
67
|
+
tags: tagObjects(base.tags ?? [], analysis.tags),
|
|
68
|
+
paths: analysis.paths,
|
|
69
|
+
components: { ...base.components, schemas: analysis.components.schemas }
|
|
70
|
+
};
|
|
71
|
+
for (const transformer of definition.transformers?.operation ?? []) {
|
|
72
|
+
for (const [path, item] of Object.entries(document.paths ?? {})) {
|
|
73
|
+
for (const method of methods) {
|
|
74
|
+
const operation = item[method];
|
|
75
|
+
if (operation) {
|
|
76
|
+
await transformer(operation, { method, path, document });
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
for (const transformer of definition.transformers?.document ?? []) {
|
|
82
|
+
await transformer(document);
|
|
83
|
+
}
|
|
84
|
+
return {
|
|
85
|
+
document,
|
|
86
|
+
sourceFiles: Array.from(
|
|
87
|
+
sourceFiles(project.program),
|
|
88
|
+
(file) => file.fileName
|
|
89
|
+
).filter((fileName) => !fileName.includes("/node_modules/"))
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
function tagObjects(declared, named) {
|
|
93
|
+
const known = new Set(declared.map((tag) => tag.name));
|
|
94
|
+
return [
|
|
95
|
+
...declared,
|
|
96
|
+
...named.filter((name) => !known.has(name)).map((name) => ({ name }))
|
|
97
|
+
];
|
|
98
|
+
}
|
|
99
|
+
function importsPrisma(project) {
|
|
100
|
+
return sourceFiles(project.program).some(
|
|
101
|
+
(sourceFile) => sourceFile.statements.some(
|
|
102
|
+
(statement) => isImportDeclaration(statement) && statement.importClause?.namedBindings !== void 0 && isNamedImports(statement.importClause.namedBindings) && statement.importClause.namedBindings.elements.some(
|
|
103
|
+
(element) => prismaBindings.includes((element.propertyName ?? element.name).text)
|
|
104
|
+
)
|
|
105
|
+
)
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
export {
|
|
109
|
+
PrismaClientNotGeneratedError,
|
|
110
|
+
defineOpenApi,
|
|
111
|
+
generateDocument
|
|
112
|
+
};
|
|
113
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/lib/definition.ts", "../src/lib/generate-document.ts"],
|
|
4
|
+
"sourcesContent": ["import type {\n ExternalDocumentationObject,\n InfoObject,\n OpenAPIObject,\n OperationObject,\n ReferenceObject,\n SchemaObject,\n SecurityRequirementObject,\n SecuritySchemeObject,\n ServerObject,\n TagObject,\n} from 'openapi3-ts/oas31';\n\nimport type { Method } from '@sdk-it/core';\n\n/**\n * What code cannot know about a backend's OpenAPI 3.1 or 3.2 document. The\n * paths, schemas and responses come from the analysis, so a base document\n * cannot hold them.\n */\nexport interface BaseDocument {\n openapi: '3.1.0' | '3.2.0';\n info: InfoObject;\n servers?: ServerObject[];\n security?: SecurityRequirementObject[];\n externalDocs?: ExternalDocumentationObject;\n /** Tag objects; each tag an operation names gets this object's fields. */\n tags?: TagObject[];\n components?: {\n securitySchemes?: Record<string, SecuritySchemeObject | ReferenceObject>;\n };\n}\n\n/** A middleware, named by its export and its file, and the security requirements of each route it guards. */\nexport interface MiddlewareSecurityRule {\n middleware: { import: string; from: URL };\n security: SecurityRequirementObject[];\n values?: { scheme: string; argument: number; mode: 'any' | 'all' };\n}\n\n/** Changes one operation in place, after the document is put together. */\nexport type OperationTransformer = (\n operation: OperationObject,\n context: { method: Method; path: string; document: OpenAPIObject },\n) => void | Promise<void>;\n\n/** Changes the document in place, after every operation transformer has run. */\nexport type DocumentTransformer = (\n document: OpenAPIObject,\n) => void | Promise<void>;\n\n/** How a backend's OpenAPI document is produced: what its module default-exports. */\nexport interface OpenApiDefinition {\n /** The backend's tsconfig, as a URL, so the document does not depend on the reader's working directory. */\n tsconfig: URL;\n document: BaseDocument;\n /** A TypeScript type name and the JSON Schema written in its place, added onto the defaults. */\n types?: Readonly<Record<string, SchemaObject>>;\n /** Named imports an `against` may read, beyond `z`, namespace imports and the Prisma preset's. */\n allowedNamedImports?: readonly string[];\n middlewareSecurity?: readonly MiddlewareSecurityRule[];\n transformers?: {\n operation?: readonly OperationTransformer[];\n document?: readonly DocumentTransformer[];\n };\n}\n\n/** The definition, as written; it gives the module's default export its type. */\nexport function defineOpenApi(\n definition: OpenApiDefinition,\n): OpenApiDefinition {\n return definition;\n}\n", "import { isImportDeclaration, isNamedImports } from '@typescript/native/ast/is';\nimport { fileURLToPath } from 'node:url';\nimport type { OpenAPIObject, TagObject } from 'openapi3-ts/oas31';\n\nimport { methods } from '@sdk-it/core';\nimport {\n type AnalysisProject,\n openAnalysisProject,\n sourceFiles,\n} from '@sdk-it/core/program.js';\nimport { UnloadedImportError, analyze } from '@sdk-it/generic';\nimport { responseAnalyzer } from '@sdk-it/hono';\n\nimport type { OpenApiDefinition } from './definition.ts';\n\n/** The exports of a generated Prisma client that an `against` may read. */\nconst prismaBindings = ['$Enums', 'Prisma'];\n\nexport interface GeneratedDocument {\n document: OpenAPIObject;\n /** Every file of the backend's program outside node_modules: a change to one can change the document. */\n sourceFiles: string[];\n}\n\n/**\n * A route file imports `Prisma` or `$Enums` from a Prisma client that does\n * not load, which is a client nobody generated.\n */\nexport class PrismaClientNotGeneratedError extends Error {\n readonly routeFile: string;\n readonly importName: string;\n constructor(\n message: string,\n routeFile: string,\n importName: string,\n cause: unknown,\n ) {\n super(message, { cause });\n this.name = 'PrismaClientNotGeneratedError';\n this.routeFile = routeFile;\n this.importName = importName;\n }\n}\n\n/** The backend's OpenAPI document, from its definition. Writes nothing. */\nexport async function generateDocument(\n definition: OpenApiDefinition,\n): Promise<GeneratedDocument> {\n using project = openAnalysisProject(fileURLToPath(definition.tsconfig));\n const prisma = importsPrisma(project);\n let analysis: Awaited<ReturnType<typeof analyze>>;\n try {\n analysis = await analyze(project, {\n responseAnalyzer,\n types: {\n ...(prisma ? { Decimal: { type: 'string' } } : {}),\n ...definition.types,\n },\n allowedNamedImports: [\n ...(prisma ? prismaBindings : []),\n ...(definition.allowedNamedImports ?? []),\n ],\n ...(definition.middlewareSecurity\n ? {\n middlewareSecurity: definition.middlewareSecurity.map((rule) => ({\n ...rule,\n middleware: {\n import: rule.middleware.import,\n from: fileURLToPath(rule.middleware.from),\n },\n })),\n }\n : {}),\n });\n } catch (error) {\n if (\n prisma &&\n error instanceof UnloadedImportError &&\n error.binding.property !== undefined &&\n prismaBindings.includes(error.binding.property)\n ) {\n throw new PrismaClientNotGeneratedError(\n `${error.message}\\nRun the Prisma client's generate target (prisma generate).`,\n error.binding.referrer,\n error.binding.property,\n error,\n );\n }\n throw error;\n }\n\n const base = structuredClone(definition.document);\n const document: OpenAPIObject = {\n ...base,\n tags: tagObjects(base.tags ?? [], analysis.tags),\n paths: analysis.paths,\n components: { ...base.components, schemas: analysis.components.schemas },\n };\n for (const transformer of definition.transformers?.operation ?? []) {\n for (const [path, item] of Object.entries(document.paths ?? {})) {\n for (const method of methods) {\n const operation = item[method];\n if (operation) {\n await transformer(operation, { method, path, document });\n }\n }\n }\n }\n for (const transformer of definition.transformers?.document ?? []) {\n await transformer(document);\n }\n\n return {\n document,\n sourceFiles: Array.from(\n sourceFiles(project.program),\n (file) => file.fileName,\n ).filter((fileName) => !fileName.includes('/node_modules/')),\n };\n}\n\n/** A tag object for each tag the base declares or an operation names, the base's first. */\nfunction tagObjects(declared: TagObject[], named: string[]): TagObject[] {\n const known = new Set(declared.map((tag) => tag.name));\n return [\n ...declared,\n ...named.filter((name) => !known.has(name)).map((name) => ({ name })),\n ];\n}\n\n/** Whether a source file imports `Prisma` or `$Enums` by name. */\nfunction importsPrisma(project: AnalysisProject): boolean {\n return sourceFiles(project.program).some((sourceFile) =>\n sourceFile.statements.some(\n (statement) =>\n isImportDeclaration(statement) &&\n statement.importClause?.namedBindings !== undefined &&\n isNamedImports(statement.importClause.namedBindings) &&\n statement.importClause.namedBindings.elements.some((element) =>\n prismaBindings.includes((element.propertyName ?? element.name).text),\n ),\n ),\n );\n}\n"],
|
|
5
|
+
"mappings": ";AAoEO,SAAS,cACd,YACmB;AACnB,SAAO;AACT;;;ACxEA,SAAS,qBAAqB,sBAAsB;AACpD,SAAS,qBAAqB;AAG9B,SAAS,eAAe;AACxB;AAAA,EAEE;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB,eAAe;AAC7C,SAAS,wBAAwB;AAKjC,IAAM,iBAAiB,CAAC,UAAU,QAAQ;AAYnC,IAAM,gCAAN,cAA4C,MAAM;AAAA,EAC9C;AAAA,EACA;AAAA,EACT,YACE,SACA,WACA,YACA,OACA;AACA,UAAM,SAAS,EAAE,MAAM,CAAC;AACxB,SAAK,OAAO;AACZ,SAAK,YAAY;AACjB,SAAK,aAAa;AAAA,EACpB;AACF;AAGA,eAAsB,iBACpB,YAC4B;AAC5B,QAAM,UAAU,oBAAoB,cAAc,WAAW,QAAQ,CAAC;AACtE,QAAM,SAAS,cAAc,OAAO;AACpC,MAAI;AACJ,MAAI;AACF,eAAW,MAAM,QAAQ,SAAS;AAAA,MAChC;AAAA,MACA,OAAO;AAAA,QACL,GAAI,SAAS,EAAE,SAAS,EAAE,MAAM,SAAS,EAAE,IAAI,CAAC;AAAA,QAChD,GAAG,WAAW;AAAA,MAChB;AAAA,MACA,qBAAqB;AAAA,QACnB,GAAI,SAAS,iBAAiB,CAAC;AAAA,QAC/B,GAAI,WAAW,uBAAuB,CAAC;AAAA,MACzC;AAAA,MACA,GAAI,WAAW,qBACX;AAAA,QACE,oBAAoB,WAAW,mBAAmB,IAAI,CAAC,UAAU;AAAA,UAC/D,GAAG;AAAA,UACH,YAAY;AAAA,YACV,QAAQ,KAAK,WAAW;AAAA,YACxB,MAAM,cAAc,KAAK,WAAW,IAAI;A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,SAAS,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC;AACrD,SAAO;AAAA,IACL,GAAG;AAAA,IACH,GAAG,MAAM,OAAO,CAAC,SAAS,CAAC,MAAM,IAAI,IAAI,CAAC,EAAE,IAAI,CAAC,UAAU,EAAE,KAAK,EAAE;AAAA,EACtE;AACF;AAGA,SAAS,cAAc,SAAmC;AACxD,SAAO,YAAY,QAAQ,OAAO,EAAE;AAAA,IAAK,CAAC,eACxC,WAAW,WAAW;AAAA,MACpB,CAAC,cACC,oBAAoB,SAAS,KAC7B,UAAU,cAAc,kBAAkB,UAC1C,eAAe,UAAU,aAAa,aAAa,KACnD,UAAU,aAAa,cAAc,SAAS;AAAA,QAAK,CAAC,YAClD,eAAe,UAAU,QAAQ,gBAAgB,QAAQ,MAAM,IAAI;AAAA,MACrE;AAAA,IACJ;AAAA,EACF;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { ExternalDocumentationObject, InfoObject, OpenAPIObject, OperationObject, ReferenceObject, SchemaObject, SecurityRequirementObject, SecuritySchemeObject, ServerObject, TagObject } from 'openapi3-ts/oas31';
|
|
2
|
+
import type { Method } from '@sdk-it/core';
|
|
3
|
+
/**
|
|
4
|
+
* What code cannot know about a backend's OpenAPI 3.1 or 3.2 document. The
|
|
5
|
+
* paths, schemas and responses come from the analysis, so a base document
|
|
6
|
+
* cannot hold them.
|
|
7
|
+
*/
|
|
8
|
+
export interface BaseDocument {
|
|
9
|
+
openapi: '3.1.0' | '3.2.0';
|
|
10
|
+
info: InfoObject;
|
|
11
|
+
servers?: ServerObject[];
|
|
12
|
+
security?: SecurityRequirementObject[];
|
|
13
|
+
externalDocs?: ExternalDocumentationObject;
|
|
14
|
+
/** Tag objects; each tag an operation names gets this object's fields. */
|
|
15
|
+
tags?: TagObject[];
|
|
16
|
+
components?: {
|
|
17
|
+
securitySchemes?: Record<string, SecuritySchemeObject | ReferenceObject>;
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
/** A middleware, named by its export and its file, and the security requirements of each route it guards. */
|
|
21
|
+
export interface MiddlewareSecurityRule {
|
|
22
|
+
middleware: {
|
|
23
|
+
import: string;
|
|
24
|
+
from: URL;
|
|
25
|
+
};
|
|
26
|
+
security: SecurityRequirementObject[];
|
|
27
|
+
values?: {
|
|
28
|
+
scheme: string;
|
|
29
|
+
argument: number;
|
|
30
|
+
mode: 'any' | 'all';
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** Changes one operation in place, after the document is put together. */
|
|
34
|
+
export type OperationTransformer = (operation: OperationObject, context: {
|
|
35
|
+
method: Method;
|
|
36
|
+
path: string;
|
|
37
|
+
document: OpenAPIObject;
|
|
38
|
+
}) => void | Promise<void>;
|
|
39
|
+
/** Changes the document in place, after every operation transformer has run. */
|
|
40
|
+
export type DocumentTransformer = (document: OpenAPIObject) => void | Promise<void>;
|
|
41
|
+
/** How a backend's OpenAPI document is produced: what its module default-exports. */
|
|
42
|
+
export interface OpenApiDefinition {
|
|
43
|
+
/** The backend's tsconfig, as a URL, so the document does not depend on the reader's working directory. */
|
|
44
|
+
tsconfig: URL;
|
|
45
|
+
document: BaseDocument;
|
|
46
|
+
/** A TypeScript type name and the JSON Schema written in its place, added onto the defaults. */
|
|
47
|
+
types?: Readonly<Record<string, SchemaObject>>;
|
|
48
|
+
/** Named imports an `against` may read, beyond `z`, namespace imports and the Prisma preset's. */
|
|
49
|
+
allowedNamedImports?: readonly string[];
|
|
50
|
+
middlewareSecurity?: readonly MiddlewareSecurityRule[];
|
|
51
|
+
transformers?: {
|
|
52
|
+
operation?: readonly OperationTransformer[];
|
|
53
|
+
document?: readonly DocumentTransformer[];
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
/** The definition, as written; it gives the module's default export its type. */
|
|
57
|
+
export declare function defineOpenApi(definition: OpenApiDefinition): OpenApiDefinition;
|
|
58
|
+
//# sourceMappingURL=definition.d.ts.map
|
|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AAE,KAC/D,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAE1B,gFAAgF;AAChF,MAAM,MAAM,mBAAmB,GAAG,CAChC,QAAQ,EAAE,aAAa,KACpB,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAE1B,qFAAqF;AACrF,MAAM,WAAW,iBAAiB;IAChC,2GAA2G;IAC3G,QAAQ,EAAE,GAAG,CAAC;IACd,QAAQ,EAAE,YAAY,CAAC;IACvB,gGAAgG;IAChG,KAAK,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC,CAAC;IAC/C,kGAAkG;IAClG,mBAAmB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACxC,kBAAkB,CAAC,EAAE,SAAS,sBAAsB,EAAE,CAAC;IACvD,YAAY,CAAC,EAAE;QACb,SAAS,CAAC,EAAE,SAAS,oBAAoB,EAAE,CAAC;QAC5C,QAAQ,CAAC,EAAE,SAAS,mBAAmB,EAAE,CAAC;KAC3C,CAAC;CACH;AAED,iFAAiF;AACjF,wBAAgB,aAAa,CAC3B,UAAU,EAAE,iBAAiB,GAC5B,iBAAiB,CAEnB"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { OpenAPIObject } from 'openapi3-ts/oas31';
|
|
2
|
+
import type { OpenApiDefinition } from './definition.ts';
|
|
3
|
+
export interface GeneratedDocument {
|
|
4
|
+
document: OpenAPIObject;
|
|
5
|
+
/** Every file of the backend's program outside node_modules: a change to one can change the document. */
|
|
6
|
+
sourceFiles: string[];
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* A route file imports `Prisma` or `$Enums` from a Prisma client that does
|
|
10
|
+
* not load, which is a client nobody generated.
|
|
11
|
+
*/
|
|
12
|
+
export declare class PrismaClientNotGeneratedError extends Error {
|
|
13
|
+
readonly routeFile: string;
|
|
14
|
+
readonly importName: string;
|
|
15
|
+
constructor(message: string, routeFile: string, importName: string, cause: unknown);
|
|
16
|
+
}
|
|
17
|
+
/** The backend's OpenAPI document, from its definition. Writes nothing. */
|
|
18
|
+
export declare function generateDocument(definition: OpenApiDefinition): Promise<GeneratedDocument>;
|
|
19
|
+
//# sourceMappingURL=generate-document.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generate-document.d.ts","sources":["../../src/lib/generate-document.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAa,MAAM,mBAAmB,CAAC;AAWlE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAKzD,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,aAAa,CAAC;IACxB,yGAAyG;IACzG,WAAW,EAAE,MAAM,EAAE,CAAC;CACvB;AAED;;;GAGG;AACH,qBAAa,6BAA8B,SAAQ,KAAK;IACtD,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,YACE,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,MAAM,EAClB,KAAK,EAAE,OAAO,EAMf;CACF;AAED,2EAA2E;AAC3E,wBAAsB,gBAAgB,CACpC,UAAU,EAAE,iBAAiB,GAC5B,OAAO,CAAC,iBAAiB,CAAC,CAwE5B"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,37 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sdk-it/openapi",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.51.4",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "https://github.com/JanuaryLabs/sdk-it",
|
|
8
|
+
"directory": "packages/openapi"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://github.com/JanuaryLabs/sdk-it/tree/main/packages/openapi#readme",
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public"
|
|
13
|
+
},
|
|
14
|
+
"exports": {
|
|
15
|
+
"./package.json": "./package.json",
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"import": "./dist/index.js",
|
|
19
|
+
"default": "./dist/index.js"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"dist",
|
|
24
|
+
"!**/*.tsbuildinfo",
|
|
25
|
+
"!**/*.test.*"
|
|
26
|
+
],
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"@sdk-it/core": "0.51.4",
|
|
29
|
+
"@sdk-it/generic": "0.51.4",
|
|
30
|
+
"@sdk-it/hono": "0.51.4",
|
|
31
|
+
"@typescript/native": "npm:typescript@7.1.0-beta",
|
|
32
|
+
"openapi3-ts": "^4.6.2"
|
|
33
|
+
},
|
|
34
|
+
"devDependencies": {
|
|
35
|
+
"@sdk-it/testing": "*"
|
|
36
|
+
}
|
|
37
|
+
}
|