@sdk-it/generic 0.46.10 → 0.47.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/README.md +53 -15
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +306 -210
- package/dist/index.js.map +3 -3
- package/dist/lib/generic.d.ts +2 -9
- package/dist/lib/generic.d.ts.map +1 -1
- package/dist/lib/response-analyzer.d.ts +5 -3
- package/dist/lib/response-analyzer.d.ts.map +1 -1
- package/package.json +19 -6
package/README.md
CHANGED
|
@@ -16,7 +16,7 @@ For a Hono project:
|
|
|
16
16
|
|
|
17
17
|
```bash
|
|
18
18
|
npm install @sdk-it/hono hono zod
|
|
19
|
-
npm install --save-dev @sdk-it/core @sdk-it/generic
|
|
19
|
+
npm install --save-dev @sdk-it/core @sdk-it/generic
|
|
20
20
|
```
|
|
21
21
|
|
|
22
22
|
## Analyze a Hono project
|
|
@@ -57,10 +57,12 @@ Analyze the TypeScript project and write the resulting OpenAPI document:
|
|
|
57
57
|
// openapi.ts
|
|
58
58
|
import { writeFile } from 'node:fs/promises';
|
|
59
59
|
|
|
60
|
+
import { openAnalysisProject } from '@sdk-it/core/program.js';
|
|
60
61
|
import { analyze } from '@sdk-it/generic';
|
|
61
62
|
import { responseAnalyzer } from '@sdk-it/hono';
|
|
62
63
|
|
|
63
|
-
|
|
64
|
+
using project = openAnalysisProject('./tsconfig.json');
|
|
65
|
+
const { paths, components, tags } = await analyze(project, {
|
|
64
66
|
responseAnalyzer,
|
|
65
67
|
});
|
|
66
68
|
|
|
@@ -78,6 +80,9 @@ const spec = {
|
|
|
78
80
|
await writeFile('openapi.json', JSON.stringify(spec, null, 2));
|
|
79
81
|
```
|
|
80
82
|
|
|
83
|
+
The project owns a native TypeScript process. `using` disposes the project when
|
|
84
|
+
the scope ends.
|
|
85
|
+
|
|
81
86
|
Run the script with Node.js 24 or newer:
|
|
82
87
|
|
|
83
88
|
```bash
|
|
@@ -95,19 +100,18 @@ file name as its tag:
|
|
|
95
100
|
```typescript
|
|
96
101
|
import { basename } from 'node:path';
|
|
97
102
|
|
|
103
|
+
import { openAnalysisProject } from '@sdk-it/core/program.js';
|
|
98
104
|
import { analyze } from '@sdk-it/generic';
|
|
99
105
|
import { responseAnalyzer } from '@sdk-it/hono';
|
|
100
106
|
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
return {};
|
|
108
|
-
},
|
|
107
|
+
using project = openAnalysisProject('./apps/backend/tsconfig.app.json');
|
|
108
|
+
const { paths, components } = await analyze(project, {
|
|
109
|
+
responseAnalyzer,
|
|
110
|
+
onOperation(sourceFile, _method, _path, operation) {
|
|
111
|
+
operation.tags = [basename(sourceFile, '.ts')];
|
|
112
|
+
return {};
|
|
109
113
|
},
|
|
110
|
-
);
|
|
114
|
+
});
|
|
111
115
|
```
|
|
112
116
|
|
|
113
117
|
## Customize type mappings
|
|
@@ -117,11 +121,13 @@ For example, map Prisma's `Decimal` to a string so it keeps its precision on
|
|
|
117
121
|
the wire:
|
|
118
122
|
|
|
119
123
|
```typescript
|
|
120
|
-
import { defaultTypesMap } from '@sdk-it/core';
|
|
124
|
+
import { defaultTypesMap } from '@sdk-it/core/deriver.js';
|
|
125
|
+
import { openAnalysisProject } from '@sdk-it/core/program.js';
|
|
121
126
|
import { analyze } from '@sdk-it/generic';
|
|
122
127
|
import { responseAnalyzer } from '@sdk-it/hono';
|
|
123
128
|
|
|
124
|
-
|
|
129
|
+
using project = openAnalysisProject('./tsconfig.json');
|
|
130
|
+
const { paths, components } = await analyze(project, {
|
|
125
131
|
responseAnalyzer,
|
|
126
132
|
typesMap: {
|
|
127
133
|
...defaultTypesMap,
|
|
@@ -187,10 +193,12 @@ Then inject that namespace when analyzing the project:
|
|
|
187
193
|
```typescript
|
|
188
194
|
import { fileURLToPath } from 'node:url';
|
|
189
195
|
|
|
196
|
+
import { openAnalysisProject } from '@sdk-it/core/program.js';
|
|
190
197
|
import { analyze } from '@sdk-it/generic';
|
|
191
198
|
import { responseAnalyzer } from '@sdk-it/hono';
|
|
192
199
|
|
|
193
|
-
|
|
200
|
+
using project = openAnalysisProject('./tsconfig.json');
|
|
201
|
+
const { paths, components } = await analyze(project, {
|
|
194
202
|
responseAnalyzer,
|
|
195
203
|
imports: [
|
|
196
204
|
{
|
|
@@ -204,6 +212,34 @@ const { paths, components } = await analyze('./tsconfig.json', {
|
|
|
204
212
|
The injected file must be loadable by the Node.js process running the
|
|
205
213
|
analyzer.
|
|
206
214
|
|
|
215
|
+
## Name recursive schemas
|
|
216
|
+
|
|
217
|
+
A Zod schema with `.meta({ id })` becomes the component
|
|
218
|
+
`#/components/schemas/<id>`, and every reference to it points there. A
|
|
219
|
+
recursive schema must have an id, because an unnamed cycle cannot become a
|
|
220
|
+
component. `z.json()` is recursive, so name it:
|
|
221
|
+
|
|
222
|
+
```typescript
|
|
223
|
+
const jsonValue = z.json().meta({ id: 'JsonValue' });
|
|
224
|
+
|
|
225
|
+
app.post(
|
|
226
|
+
'/shortcuts',
|
|
227
|
+
validate((payload) => ({
|
|
228
|
+
integrations: {
|
|
229
|
+
select: payload.body.integrations,
|
|
230
|
+
against: z.record(z.string(), jsonValue),
|
|
231
|
+
},
|
|
232
|
+
})),
|
|
233
|
+
(c) => c.json({ ok: true }),
|
|
234
|
+
);
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
Without the id, analysis fails with
|
|
238
|
+
`POST /shortcuts body field integrations: A recursive schema has no name; give it .meta({ id }) so it becomes a named component.`
|
|
239
|
+
Give one id to one schema only: the same id on two different schemas also
|
|
240
|
+
fails analysis. The generated TypeScript client and `@sdk-it/rpc` validate the
|
|
241
|
+
named component recursively.
|
|
242
|
+
|
|
207
243
|
## Derive operation security from middleware
|
|
208
244
|
|
|
209
245
|
Declare each OpenAPI security scheme once, then associate authentication and
|
|
@@ -212,12 +248,14 @@ authorization middleware by its exported symbol and source file:
|
|
|
212
248
|
```typescript
|
|
213
249
|
import { fileURLToPath } from 'node:url';
|
|
214
250
|
|
|
251
|
+
import { openAnalysisProject } from '@sdk-it/core/program.js';
|
|
215
252
|
import { analyze } from '@sdk-it/generic';
|
|
216
253
|
import { responseAnalyzer } from '@sdk-it/hono';
|
|
217
254
|
|
|
218
255
|
const authModule = fileURLToPath(new URL('./src/auth.ts', import.meta.url));
|
|
219
256
|
|
|
220
|
-
|
|
257
|
+
using project = openAnalysisProject('./tsconfig.json');
|
|
258
|
+
const { paths, components } = await analyze(project, {
|
|
221
259
|
responseAnalyzer,
|
|
222
260
|
securitySchemes: {
|
|
223
261
|
bearer: { type: 'http', scheme: 'bearer' },
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","
|
|
1
|
+
{"version":3,"file":"index.d.ts","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAC;AACjC,cAAc,4BAA4B,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,43 +1,66 @@
|
|
|
1
1
|
// packages/generic/src/lib/generic.ts
|
|
2
|
-
import
|
|
2
|
+
import {
|
|
3
|
+
NodeFlags,
|
|
4
|
+
getJSDocTags,
|
|
5
|
+
getTextOfJSDocComment
|
|
6
|
+
} from "@typescript/native/ast";
|
|
7
|
+
import {
|
|
8
|
+
isArrayLiteralExpression,
|
|
9
|
+
isArrowFunction,
|
|
10
|
+
isAsExpression,
|
|
11
|
+
isAwaitExpression,
|
|
12
|
+
isBlock,
|
|
13
|
+
isCallExpression as isCall,
|
|
14
|
+
isConditionalExpression,
|
|
15
|
+
isConstructorDeclaration,
|
|
16
|
+
isElementAccessExpression,
|
|
17
|
+
isEnumMember,
|
|
18
|
+
isFunctionDeclaration,
|
|
19
|
+
isFunctionExpression,
|
|
20
|
+
isGetAccessorDeclaration,
|
|
21
|
+
isIdentifier,
|
|
22
|
+
isMethodDeclaration,
|
|
23
|
+
isNamespaceImport,
|
|
24
|
+
isNewExpression,
|
|
25
|
+
isNonNullExpression,
|
|
26
|
+
isObjectLiteralExpression,
|
|
27
|
+
isOmittedExpression,
|
|
28
|
+
isParenthesizedExpression,
|
|
29
|
+
isPropertyAccessExpression,
|
|
30
|
+
isPropertyAssignment,
|
|
31
|
+
isReturnStatement,
|
|
32
|
+
isSatisfiesExpression,
|
|
33
|
+
isSetAccessorDeclaration,
|
|
34
|
+
isSpreadElement,
|
|
35
|
+
isStringLiteral,
|
|
36
|
+
isStringLiteralLikeNode,
|
|
37
|
+
isThrowStatement,
|
|
38
|
+
isTypeAssertion,
|
|
39
|
+
isVariableDeclaration,
|
|
40
|
+
isVariableDeclarationList
|
|
41
|
+
} from "@typescript/native/ast/is";
|
|
42
|
+
import {
|
|
43
|
+
SymbolFlags
|
|
44
|
+
} from "@typescript/native/sync";
|
|
3
45
|
import { realpathSync } from "node:fs";
|
|
4
46
|
import { resolve } from "node:path";
|
|
47
|
+
import { debuglog } from "node:util";
|
|
5
48
|
import { camelcase } from "stringcase";
|
|
6
|
-
import ts from "typescript";
|
|
7
49
|
import {
|
|
8
50
|
Paths,
|
|
9
|
-
TypeDeriver,
|
|
10
|
-
getProgram,
|
|
11
|
-
isCallExpression,
|
|
12
51
|
isHttpMethod,
|
|
13
|
-
|
|
52
|
+
isSemanticSource,
|
|
14
53
|
toSchema
|
|
15
54
|
} from "@sdk-it/core";
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
if (declarations.length === 0) {
|
|
22
|
-
return void 0;
|
|
23
|
-
}
|
|
24
|
-
const sourceFile = declarations[0].getSourceFile();
|
|
25
|
-
return sourceFile?.fileName;
|
|
26
|
-
}
|
|
27
|
-
function isExternalFunction(symbol) {
|
|
28
|
-
const fileName = symbolFile(symbol);
|
|
29
|
-
return fileName ? fileName.includes("node_modules") : false;
|
|
30
|
-
}
|
|
31
|
-
function isLocalFunction(symbol) {
|
|
32
|
-
if (!symbol) {
|
|
33
|
-
return false;
|
|
34
|
-
}
|
|
35
|
-
return !isExternalFunction(symbol);
|
|
36
|
-
}
|
|
55
|
+
import { TypeDeriver, nodeLocation } from "@sdk-it/core/deriver.js";
|
|
56
|
+
import {
|
|
57
|
+
isCallExpression,
|
|
58
|
+
sourceFiles
|
|
59
|
+
} from "@sdk-it/core/program.js";
|
|
37
60
|
function resolvedSymbol(expression, typeChecker) {
|
|
38
|
-
const location =
|
|
61
|
+
const location = isPropertyAccessExpression(expression) ? expression.name : expression;
|
|
39
62
|
const symbol = typeChecker.getSymbolAtLocation(location);
|
|
40
|
-
return symbol && symbol.flags &
|
|
63
|
+
return symbol && symbol.flags & SymbolFlags.Alias ? typeChecker.getAliasedSymbol(symbol) : symbol;
|
|
41
64
|
}
|
|
42
65
|
function realPath(path) {
|
|
43
66
|
const resolved = resolve(path);
|
|
@@ -52,16 +75,17 @@ function matchesMiddleware(symbol, middleware) {
|
|
|
52
75
|
return false;
|
|
53
76
|
}
|
|
54
77
|
const from = realPath(middleware.from);
|
|
55
|
-
return
|
|
56
|
-
|
|
57
|
-
|
|
78
|
+
return symbol.declarations.some((handle) => {
|
|
79
|
+
const fileName = handle.resolve()?.getSourceFile().fileName;
|
|
80
|
+
return fileName !== void 0 && realPath(fileName) === from;
|
|
81
|
+
});
|
|
58
82
|
}
|
|
59
83
|
function middlewareSecurity(args, security, typeChecker) {
|
|
60
84
|
let requirements;
|
|
61
85
|
for (const arg of args) {
|
|
62
|
-
const call =
|
|
86
|
+
const call = isCall(arg) ? arg : void 0;
|
|
63
87
|
const reference = call ? call.expression : arg;
|
|
64
|
-
if (!
|
|
88
|
+
if (!isIdentifier(reference) && !isPropertyAccessExpression(reference)) {
|
|
65
89
|
continue;
|
|
66
90
|
}
|
|
67
91
|
const symbol = resolvedSymbol(reference, typeChecker);
|
|
@@ -122,20 +146,20 @@ function securityWithValues(call, rule, valuesConfig, typeChecker) {
|
|
|
122
146
|
});
|
|
123
147
|
}
|
|
124
148
|
function constantStrings(expression, typeChecker, visited = /* @__PURE__ */ new Set()) {
|
|
125
|
-
while (
|
|
149
|
+
while (isParenthesizedExpression(expression) || isAsExpression(expression) || isTypeAssertion(expression) || isSatisfiesExpression(expression) || isNonNullExpression(expression)) {
|
|
126
150
|
expression = expression.expression;
|
|
127
151
|
}
|
|
128
|
-
if (
|
|
152
|
+
if (isStringLiteralLikeNode(expression)) {
|
|
129
153
|
return [expression.text];
|
|
130
154
|
}
|
|
131
|
-
if (
|
|
155
|
+
if (isArrayLiteralExpression(expression)) {
|
|
132
156
|
const result = [];
|
|
133
157
|
for (const element of expression.elements) {
|
|
134
|
-
if (
|
|
158
|
+
if (isOmittedExpression(element)) {
|
|
135
159
|
continue;
|
|
136
160
|
}
|
|
137
161
|
const values = constantStrings(
|
|
138
|
-
|
|
162
|
+
isSpreadElement(element) ? element.expression : element,
|
|
139
163
|
typeChecker,
|
|
140
164
|
visited
|
|
141
165
|
);
|
|
@@ -146,21 +170,22 @@ function constantStrings(expression, typeChecker, visited = /* @__PURE__ */ new
|
|
|
146
170
|
}
|
|
147
171
|
return result;
|
|
148
172
|
}
|
|
149
|
-
if (
|
|
173
|
+
if (isPropertyAccessExpression(expression)) {
|
|
150
174
|
const value = typeChecker.getConstantValue(expression);
|
|
151
175
|
if (typeof value === "string") {
|
|
152
176
|
return [value];
|
|
153
177
|
}
|
|
154
178
|
}
|
|
155
|
-
if (
|
|
179
|
+
if (isIdentifier(expression) || isPropertyAccessExpression(expression)) {
|
|
156
180
|
const symbol = resolvedSymbol(expression, typeChecker);
|
|
157
|
-
for (const
|
|
158
|
-
|
|
181
|
+
for (const handle of symbol?.declarations ?? []) {
|
|
182
|
+
const declaration = handle.resolve();
|
|
183
|
+
if (!declaration || visited.has(declaration)) {
|
|
159
184
|
continue;
|
|
160
185
|
}
|
|
161
186
|
visited.add(declaration);
|
|
162
187
|
try {
|
|
163
|
-
if ((
|
|
188
|
+
if ((isVariableDeclaration(declaration) || isEnumMember(declaration)) && declaration.initializer) {
|
|
164
189
|
const values = constantStrings(
|
|
165
190
|
declaration.initializer,
|
|
166
191
|
typeChecker,
|
|
@@ -197,95 +222,143 @@ function andSecurity(left, right) {
|
|
|
197
222
|
}
|
|
198
223
|
function requirementKey(requirement) {
|
|
199
224
|
return JSON.stringify(
|
|
200
|
-
Object.keys(requirement).sort().map((scheme) => [scheme,
|
|
225
|
+
Object.keys(requirement).sort().map((scheme) => [scheme, requirement[scheme].toSorted()])
|
|
201
226
|
);
|
|
202
227
|
}
|
|
203
|
-
|
|
228
|
+
function returnedCalls(expression) {
|
|
229
|
+
if (isAwaitExpression(expression) || isParenthesizedExpression(expression) || isAsExpression(expression) || isTypeAssertion(expression) || isSatisfiesExpression(expression) || isNonNullExpression(expression)) {
|
|
230
|
+
return returnedCalls(expression.expression);
|
|
231
|
+
}
|
|
232
|
+
if (isConditionalExpression(expression)) {
|
|
233
|
+
return [
|
|
234
|
+
...returnedCalls(expression.whenTrue),
|
|
235
|
+
...returnedCalls(expression.whenFalse)
|
|
236
|
+
];
|
|
237
|
+
}
|
|
238
|
+
return isCall(expression) ? [expression] : [];
|
|
239
|
+
}
|
|
240
|
+
function returnTokens(node, typeChecker) {
|
|
204
241
|
const tokens = [];
|
|
205
|
-
const
|
|
206
|
-
const
|
|
207
|
-
|
|
208
|
-
|
|
242
|
+
const maxDepth = 5;
|
|
243
|
+
const visitedFunctions = {
|
|
244
|
+
returned: /* @__PURE__ */ new Set(),
|
|
245
|
+
discarded: /* @__PURE__ */ new Set()
|
|
246
|
+
};
|
|
247
|
+
const follow = (callExpression, depth, returned) => {
|
|
248
|
+
if (depth >= maxDepth) {
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
let symbol;
|
|
252
|
+
if (isIdentifier(callExpression.expression)) {
|
|
253
|
+
symbol = typeChecker.getSymbolAtLocation(callExpression.expression);
|
|
254
|
+
} else if (isPropertyAccessExpression(callExpression.expression)) {
|
|
255
|
+
symbol = typeChecker.getSymbolAtLocation(callExpression.expression.name);
|
|
256
|
+
}
|
|
257
|
+
if (symbol && symbol.flags & SymbolFlags.Alias) {
|
|
258
|
+
symbol = typeChecker.getAliasedSymbol(symbol);
|
|
259
|
+
}
|
|
260
|
+
if (!symbol) {
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
const visited = returned ? visitedFunctions.returned : visitedFunctions.discarded;
|
|
264
|
+
for (const handle of symbol.declarations) {
|
|
265
|
+
const declaration = handle.resolve();
|
|
266
|
+
if (!declaration || visited.has(declaration)) {
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
if (isFunctionWithBody(declaration) && declaration.body) {
|
|
270
|
+
visited.add(declaration);
|
|
271
|
+
visitor(declaration.body, depth + 1, returned);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
const visitor = (node2, depth, returned) => {
|
|
209
276
|
if (depth > maxDepth) {
|
|
210
277
|
return;
|
|
211
278
|
}
|
|
212
|
-
if (
|
|
279
|
+
if (isThrowStatement(node2)) {
|
|
213
280
|
let expression = node2.expression;
|
|
214
281
|
const visited = /* @__PURE__ */ new Set();
|
|
215
282
|
while (true) {
|
|
216
|
-
if (
|
|
283
|
+
if (isParenthesizedExpression(expression) || isAsExpression(expression) || isTypeAssertion(expression) || isSatisfiesExpression(expression) || isNonNullExpression(expression)) {
|
|
217
284
|
expression = expression.expression;
|
|
218
285
|
continue;
|
|
219
286
|
}
|
|
220
|
-
if (!
|
|
287
|
+
if (!isIdentifier(expression) && !isPropertyAccessExpression(expression))
|
|
221
288
|
break;
|
|
222
|
-
if (
|
|
289
|
+
if (isPropertyAccessExpression(expression) && !typeChecker.getSymbolAtLocation(expression.expression)?.declarations.some(isNamespaceImport.Handle))
|
|
223
290
|
break;
|
|
224
291
|
const declaration = resolvedSymbol(
|
|
225
292
|
expression,
|
|
226
293
|
typeChecker
|
|
227
|
-
)?.valueDeclaration;
|
|
228
|
-
if (!declaration || visited.has(declaration) || !
|
|
294
|
+
)?.valueDeclaration?.resolve();
|
|
295
|
+
if (!declaration || visited.has(declaration) || !isVariableDeclaration(declaration) || !isVariableDeclarationList(declaration.parent) || !(declaration.parent.flags & NodeFlags.Const) || !declaration.initializer)
|
|
229
296
|
break;
|
|
230
297
|
visited.add(declaration);
|
|
231
298
|
expression = declaration.initializer;
|
|
232
299
|
}
|
|
233
|
-
if (
|
|
300
|
+
if (isNewExpression(expression)) {
|
|
234
301
|
tokens.push({
|
|
235
302
|
token: `throw.new.${expression.expression.getText()}`,
|
|
236
303
|
node: expression
|
|
237
304
|
});
|
|
305
|
+
} else if (isCall(expression)) {
|
|
306
|
+
const thrown = typeChecker.getTypeAtLocation(expression).getSymbol()?.name;
|
|
307
|
+
if (thrown) {
|
|
308
|
+
tokens.push({ token: `throw.call.${thrown}`, node: expression });
|
|
309
|
+
}
|
|
238
310
|
}
|
|
239
311
|
}
|
|
240
|
-
if (
|
|
241
|
-
|
|
312
|
+
if (isReturnStatement(node2) && node2.expression) {
|
|
313
|
+
visitReturned(node2.expression, depth, returned);
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
if (isArrowFunction(node2) && !isBlock(node2.body)) {
|
|
317
|
+
for (const parameter of node2.parameters) {
|
|
318
|
+
visitor(parameter, depth, false);
|
|
319
|
+
}
|
|
320
|
+
visitReturned(node2.body, depth, returned);
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
if (isCall(node2)) {
|
|
324
|
+
follow(node2, depth, false);
|
|
325
|
+
}
|
|
326
|
+
node2.forEachChild(
|
|
327
|
+
(child) => visitor(child, depth, returned && !isFunctionWithBody(child))
|
|
328
|
+
);
|
|
329
|
+
};
|
|
330
|
+
const visitReturned = (expression, depth, returned) => {
|
|
331
|
+
if (isParenthesizedExpression(expression)) {
|
|
332
|
+
visitReturned(expression.expression, depth, returned);
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
if (returned) {
|
|
336
|
+
if (isCall(expression)) {
|
|
242
337
|
tokens.push({
|
|
243
|
-
token:
|
|
244
|
-
node:
|
|
338
|
+
token: expression.expression.getText(),
|
|
339
|
+
node: expression
|
|
245
340
|
});
|
|
246
341
|
}
|
|
247
|
-
if (
|
|
342
|
+
if (isNewExpression(expression)) {
|
|
248
343
|
tokens.push({
|
|
249
|
-
token: `new.${
|
|
250
|
-
node:
|
|
344
|
+
token: `new.${expression.expression.getText()}`,
|
|
345
|
+
node: expression
|
|
251
346
|
});
|
|
252
347
|
}
|
|
253
|
-
ts.forEachChild(node2.expression, (child) => visitor(child, depth));
|
|
254
|
-
return;
|
|
255
348
|
}
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
callExpression.expression.name
|
|
264
|
-
);
|
|
265
|
-
}
|
|
266
|
-
if (symbol && symbol.flags & ts.SymbolFlags.Alias) {
|
|
267
|
-
symbol = typeChecker.getAliasedSymbol(symbol);
|
|
268
|
-
}
|
|
269
|
-
const shouldFollow = consider3rdParty || isLocalFunction(symbol);
|
|
270
|
-
if (shouldFollow && symbol) {
|
|
271
|
-
const declarations = symbol?.declarations ?? [];
|
|
272
|
-
for (const declaration of declarations) {
|
|
273
|
-
if (visitedFunctions.has(declaration)) {
|
|
274
|
-
continue;
|
|
275
|
-
}
|
|
276
|
-
if (isFunctionWithBody(declaration) && declaration.body) {
|
|
277
|
-
visitedFunctions.add(declaration);
|
|
278
|
-
visitor(declaration.body, depth + 1);
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
}
|
|
349
|
+
for (const call of returnedCalls(expression)) {
|
|
350
|
+
follow(call, depth, returned);
|
|
351
|
+
}
|
|
352
|
+
if (isFunctionWithBody(expression)) {
|
|
353
|
+
visitor(expression, depth, returned);
|
|
354
|
+
} else {
|
|
355
|
+
expression.forEachChild((child) => visitor(child, depth, returned));
|
|
282
356
|
}
|
|
283
|
-
ts.forEachChild(node2, (child) => visitor(child, depth));
|
|
284
357
|
};
|
|
285
|
-
visitor(node, 0);
|
|
358
|
+
visitor(node, 0, true);
|
|
286
359
|
return tokens;
|
|
287
|
-
}
|
|
288
|
-
var logger =
|
|
360
|
+
}
|
|
361
|
+
var logger = debuglog("@sdk-it/generic");
|
|
289
362
|
var jsDocsTags = [
|
|
290
363
|
"openapi",
|
|
291
364
|
"tags",
|
|
@@ -303,34 +376,36 @@ function parseJSDocComment(node) {
|
|
|
303
376
|
let access = "";
|
|
304
377
|
let tool = "";
|
|
305
378
|
let toolDescription = "";
|
|
306
|
-
for (const tag of
|
|
307
|
-
|
|
308
|
-
(
|
|
309
|
-
)) {
|
|
310
|
-
if (typeof tag.comment !== "string") {
|
|
379
|
+
for (const tag of getJSDocTags(node)) {
|
|
380
|
+
const tagName = jsDocsTags.find((name2) => name2 === tag.tagName.text);
|
|
381
|
+
if (tagName === void 0) {
|
|
311
382
|
continue;
|
|
312
383
|
}
|
|
313
|
-
|
|
384
|
+
const comment = getTextOfJSDocComment(tag.comment);
|
|
385
|
+
if (comment === void 0) {
|
|
386
|
+
continue;
|
|
387
|
+
}
|
|
388
|
+
switch (tagName) {
|
|
314
389
|
case "openapi":
|
|
315
|
-
name =
|
|
390
|
+
name = comment;
|
|
316
391
|
break;
|
|
317
392
|
case "tags":
|
|
318
|
-
tags =
|
|
393
|
+
tags = comment.split(",").map((tag2) => tag2.trim());
|
|
319
394
|
break;
|
|
320
395
|
case "description":
|
|
321
|
-
description =
|
|
396
|
+
description = comment;
|
|
322
397
|
break;
|
|
323
398
|
case "summary":
|
|
324
|
-
summary =
|
|
399
|
+
summary = comment;
|
|
325
400
|
break;
|
|
326
401
|
case "access":
|
|
327
|
-
access =
|
|
402
|
+
access = comment.trim().toLowerCase();
|
|
328
403
|
break;
|
|
329
404
|
case "tool":
|
|
330
|
-
tool =
|
|
405
|
+
tool = comment.trim();
|
|
331
406
|
break;
|
|
332
407
|
case "toolDescription":
|
|
333
|
-
toolDescription =
|
|
408
|
+
toolDescription = comment.trim();
|
|
334
409
|
break;
|
|
335
410
|
}
|
|
336
411
|
}
|
|
@@ -345,14 +420,14 @@ function parseJSDocComment(node) {
|
|
|
345
420
|
};
|
|
346
421
|
}
|
|
347
422
|
function visit(node, responseAnalyzer2, paths, typeChecker, typeDeriver, security) {
|
|
348
|
-
if (!
|
|
423
|
+
if (!isCall(node) || node.arguments.length < 2) {
|
|
349
424
|
return moveOn();
|
|
350
425
|
}
|
|
351
|
-
if (!
|
|
426
|
+
if (!isPropertyAccessExpression(node.expression) || !isIdentifier(node.expression.name) || !isHttpMethod(node.expression.name.text)) {
|
|
352
427
|
return moveOn();
|
|
353
428
|
}
|
|
354
429
|
const [pathNode] = node.arguments;
|
|
355
|
-
if (!
|
|
430
|
+
if (!isStringLiteral(pathNode)) {
|
|
356
431
|
return moveOn();
|
|
357
432
|
}
|
|
358
433
|
const method = node.expression.name.text;
|
|
@@ -364,7 +439,7 @@ function visit(node, responseAnalyzer2, paths, typeChecker, typeDeriver, securit
|
|
|
364
439
|
return moveOn();
|
|
365
440
|
}
|
|
366
441
|
const handler = node.arguments.at(-1);
|
|
367
|
-
if (!handler || !
|
|
442
|
+
if (!handler || !isArrowFunction(handler)) {
|
|
368
443
|
return moveOn();
|
|
369
444
|
}
|
|
370
445
|
const metadata = parseJSDocComment(node.parent);
|
|
@@ -383,29 +458,29 @@ function visit(node, responseAnalyzer2, paths, typeChecker, typeDeriver, securit
|
|
|
383
458
|
} else {
|
|
384
459
|
selector = validate.arguments[0];
|
|
385
460
|
}
|
|
386
|
-
if (!
|
|
461
|
+
if (!isArrowFunction(selector)) {
|
|
387
462
|
return moveOn();
|
|
388
463
|
}
|
|
389
|
-
if (!selector || !
|
|
464
|
+
if (!selector || !isParenthesizedExpression(selector.body) || !isObjectLiteralExpression(selector.body.expression)) {
|
|
390
465
|
return moveOn();
|
|
391
466
|
}
|
|
392
467
|
const middlewareDeclarations = [];
|
|
393
468
|
for (const arg of node.arguments.slice(1, -1)) {
|
|
394
|
-
if (
|
|
395
|
-
if (
|
|
469
|
+
if (isCall(arg)) {
|
|
470
|
+
if (isIdentifier(arg.expression)) {
|
|
396
471
|
const middlewareFnName = arg.expression.text;
|
|
397
472
|
let symbol = typeChecker.getSymbolAtLocation(arg.expression);
|
|
398
|
-
if (symbol && symbol.flags &
|
|
473
|
+
if (symbol && symbol.flags & SymbolFlags.Alias) {
|
|
399
474
|
symbol = typeChecker.getAliasedSymbol(symbol);
|
|
400
475
|
}
|
|
401
476
|
const allDeclarations = [
|
|
402
477
|
symbol?.valueDeclaration,
|
|
403
478
|
...symbol?.declarations ?? []
|
|
404
|
-
].filter((
|
|
479
|
+
].map((handle) => handle?.resolve()).filter((declaration2) => declaration2 !== void 0);
|
|
405
480
|
let declaration = allDeclarations.find(isFunctionWithBody);
|
|
406
481
|
if (!declaration) {
|
|
407
482
|
for (const decl of allDeclarations) {
|
|
408
|
-
if (
|
|
483
|
+
if (isVariableDeclaration(decl) && decl.initializer) {
|
|
409
484
|
if (isFunctionWithBody(decl.initializer)) {
|
|
410
485
|
declaration = decl.initializer;
|
|
411
486
|
break;
|
|
@@ -420,7 +495,7 @@ function visit(node, responseAnalyzer2, paths, typeChecker, typeDeriver, securit
|
|
|
420
495
|
});
|
|
421
496
|
}
|
|
422
497
|
}
|
|
423
|
-
if (
|
|
498
|
+
if (isIdentifier(arg.expression) && arg.expression.text === "validate") {
|
|
424
499
|
continue;
|
|
425
500
|
}
|
|
426
501
|
const firstArg = arg.arguments[0];
|
|
@@ -429,9 +504,7 @@ function visit(node, responseAnalyzer2, paths, typeChecker, typeDeriver, securit
|
|
|
429
504
|
}
|
|
430
505
|
}
|
|
431
506
|
}
|
|
432
|
-
const props = selector.body.expression.properties.filter(
|
|
433
|
-
ts.isPropertyAssignment
|
|
434
|
-
);
|
|
507
|
+
const props = selector.body.expression.properties.filter(isPropertyAssignment);
|
|
435
508
|
const sourceFile = node.getSourceFile();
|
|
436
509
|
typeDeriver.setTrace({
|
|
437
510
|
file: sourceFile.fileName,
|
|
@@ -456,7 +529,7 @@ function visit(node, responseAnalyzer2, paths, typeChecker, typeDeriver, securit
|
|
|
456
529
|
operationName,
|
|
457
530
|
path,
|
|
458
531
|
method,
|
|
459
|
-
contentType ?
|
|
532
|
+
contentType ? isStringLiteral(contentType) ? contentType.text : void 0 : void 0,
|
|
460
533
|
toSelectors(props),
|
|
461
534
|
responses,
|
|
462
535
|
sourceFile.fileName,
|
|
@@ -466,8 +539,7 @@ function visit(node, responseAnalyzer2, paths, typeChecker, typeDeriver, securit
|
|
|
466
539
|
}
|
|
467
540
|
);
|
|
468
541
|
function moveOn() {
|
|
469
|
-
|
|
470
|
-
node,
|
|
542
|
+
node.forEachChild(
|
|
471
543
|
(node2) => visit(node2, responseAnalyzer2, paths, typeChecker, typeDeriver, security)
|
|
472
544
|
);
|
|
473
545
|
}
|
|
@@ -475,11 +547,11 @@ function visit(node, responseAnalyzer2, paths, typeChecker, typeDeriver, securit
|
|
|
475
547
|
function toSelectors(props) {
|
|
476
548
|
const selectors = [];
|
|
477
549
|
for (const prop of props) {
|
|
478
|
-
if (!
|
|
550
|
+
if (!isObjectLiteralExpression(prop.initializer)) {
|
|
479
551
|
continue;
|
|
480
552
|
}
|
|
481
553
|
const name = prop.name.getText();
|
|
482
|
-
const select = prop.initializer.properties.filter(
|
|
554
|
+
const select = prop.initializer.properties.filter(isPropertyAssignment).find((prop2) => prop2.name.getText() === "select");
|
|
483
555
|
if (!select) {
|
|
484
556
|
console.warn(
|
|
485
557
|
`\u26A0 No select found in ${name}
|
|
@@ -487,7 +559,7 @@ function toSelectors(props) {
|
|
|
487
559
|
);
|
|
488
560
|
continue;
|
|
489
561
|
}
|
|
490
|
-
const against = prop.initializer.properties.filter(
|
|
562
|
+
const against = prop.initializer.properties.filter(isPropertyAssignment).find((prop2) => prop2.name.getText() === "against");
|
|
491
563
|
if (!against) {
|
|
492
564
|
console.warn(
|
|
493
565
|
`\u26A0 No against found in ${name}
|
|
@@ -495,21 +567,46 @@ function toSelectors(props) {
|
|
|
495
567
|
);
|
|
496
568
|
continue;
|
|
497
569
|
}
|
|
498
|
-
const
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
570
|
+
const selector = toSelector(
|
|
571
|
+
select.initializer,
|
|
572
|
+
against.initializer.getText()
|
|
573
|
+
);
|
|
574
|
+
if (!selector) {
|
|
575
|
+
console.warn(
|
|
576
|
+
`\u26A0 Unsupported select in ${name}: ${select.initializer.getText()}. Select payload.body or one value, such as payload.params.id or payload.headers['x-id'].
|
|
577
|
+
at ${nodeLocation(prop) ?? "unknown"}`
|
|
578
|
+
);
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
581
|
+
selectors.push(selector);
|
|
504
582
|
}
|
|
505
583
|
return selectors;
|
|
506
584
|
}
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
585
|
+
function toSelector(select, against) {
|
|
586
|
+
if (isPropertyAccessExpression(select) && isIdentifier(select.expression)) {
|
|
587
|
+
return select.name.text === "body" ? { kind: "body", against } : void 0;
|
|
588
|
+
}
|
|
589
|
+
if (!isPropertyAccessExpression(select) && !isElementAccessExpression(select)) {
|
|
590
|
+
return void 0;
|
|
591
|
+
}
|
|
592
|
+
const name = memberName(select);
|
|
593
|
+
const owner = select.expression;
|
|
594
|
+
if (name === void 0 || !isPropertyAccessExpression(owner) || !isIdentifier(owner.expression) || !isSemanticSource(owner.name.text)) {
|
|
595
|
+
return void 0;
|
|
596
|
+
}
|
|
597
|
+
return { kind: "field", source: owner.name.text, name, against };
|
|
598
|
+
}
|
|
599
|
+
function memberName(node) {
|
|
600
|
+
if (isPropertyAccessExpression(node)) {
|
|
601
|
+
return node.name.text;
|
|
602
|
+
}
|
|
603
|
+
if (isElementAccessExpression(node) && isStringLiteralLikeNode(node.argumentExpression)) {
|
|
604
|
+
return node.argumentExpression.text;
|
|
605
|
+
}
|
|
606
|
+
return void 0;
|
|
607
|
+
}
|
|
608
|
+
async function analyze(project, config) {
|
|
609
|
+
const typeChecker = project.checker;
|
|
513
610
|
const typeDeriver = new TypeDeriver(typeChecker, config.typesMap);
|
|
514
611
|
const paths = new Paths({
|
|
515
612
|
imports: config.imports ?? [],
|
|
@@ -519,29 +616,33 @@ async function analyze(tsconfigPath, config) {
|
|
|
519
616
|
rules: config.middlewareSecurity,
|
|
520
617
|
matched: /* @__PURE__ */ new Set()
|
|
521
618
|
};
|
|
522
|
-
for (const sourceFile of program
|
|
523
|
-
logger(`
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
(
|
|
529
|
-
const
|
|
530
|
-
if (
|
|
531
|
-
const naunce = responseAnalyzer2[token] || responseAnalyzer2["default"];
|
|
532
|
-
if (!naunce) {
|
|
533
|
-
throw new Error(`No response analyzer for token ${token}`);
|
|
534
|
-
}
|
|
619
|
+
for (const sourceFile of sourceFiles(project.program)) {
|
|
620
|
+
logger(`Visiting ${sourceFile.fileName}`);
|
|
621
|
+
visit(
|
|
622
|
+
sourceFile,
|
|
623
|
+
(handler, token, node) => {
|
|
624
|
+
const responseAnalyzer2 = config.responseAnalyzer;
|
|
625
|
+
if (typeof responseAnalyzer2 !== "function") {
|
|
626
|
+
const naunce = responseAnalyzer2[token];
|
|
627
|
+
if (naunce) {
|
|
535
628
|
return naunce(handler, typeDeriver, node);
|
|
536
629
|
}
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
630
|
+
if (token.startsWith("throw.")) {
|
|
631
|
+
return [];
|
|
632
|
+
}
|
|
633
|
+
const fallback = responseAnalyzer2["default"];
|
|
634
|
+
if (!fallback) {
|
|
635
|
+
throw new Error(`No response analyzer for token ${token}`);
|
|
636
|
+
}
|
|
637
|
+
return fallback(handler, typeDeriver, node);
|
|
638
|
+
}
|
|
639
|
+
return responseAnalyzer2(handler, typeDeriver);
|
|
640
|
+
},
|
|
641
|
+
paths,
|
|
642
|
+
typeChecker,
|
|
643
|
+
typeDeriver,
|
|
644
|
+
security
|
|
645
|
+
);
|
|
545
646
|
}
|
|
546
647
|
for (const rule of security?.rules ?? []) {
|
|
547
648
|
if (!security?.matched.has(rule)) {
|
|
@@ -551,6 +652,7 @@ async function analyze(tsconfigPath, config) {
|
|
|
551
652
|
);
|
|
552
653
|
}
|
|
553
654
|
}
|
|
655
|
+
const pathsObject = await paths.getPaths();
|
|
554
656
|
const components = {
|
|
555
657
|
schemas: {
|
|
556
658
|
...paths.getSharedSchemas(),
|
|
@@ -562,7 +664,7 @@ async function analyze(tsconfigPath, config) {
|
|
|
562
664
|
securitySchemes: config.securitySchemes
|
|
563
665
|
};
|
|
564
666
|
return {
|
|
565
|
-
paths:
|
|
667
|
+
paths: pathsObject,
|
|
566
668
|
tags: paths.getTags(),
|
|
567
669
|
components
|
|
568
670
|
};
|
|
@@ -571,55 +673,50 @@ function isFunctionWithBody(node) {
|
|
|
571
673
|
if (!node) {
|
|
572
674
|
return false;
|
|
573
675
|
}
|
|
574
|
-
return (
|
|
676
|
+
return (isFunctionDeclaration(node) || isFunctionExpression(node) || isArrowFunction(node) || isMethodDeclaration(node) || isConstructorDeclaration(node) || isGetAccessorDeclaration(node) || isSetAccessorDeclaration(node)) && !!node.body;
|
|
575
677
|
}
|
|
576
678
|
|
|
577
679
|
// packages/generic/src/lib/response-analyzer.ts
|
|
578
|
-
import
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
if (callerMethod === "attachment") {
|
|
589
|
-
contentType = "application/octet-stream";
|
|
590
|
-
}
|
|
591
|
-
if (!body) {
|
|
592
|
-
contentType = "empty";
|
|
593
|
-
}
|
|
594
|
-
callback(body, statusCode, headers, contentType);
|
|
595
|
-
}
|
|
596
|
-
}
|
|
597
|
-
}
|
|
598
|
-
return ts2.forEachChild(node, handlerVisitor(callback));
|
|
599
|
-
};
|
|
600
|
-
};
|
|
601
|
-
function toResponses(handler, deriver) {
|
|
602
|
-
const responsesList = [];
|
|
603
|
-
const visit2 = handlerVisitor((node, statusCode, headers, contentType) => {
|
|
604
|
-
responsesList.push({
|
|
605
|
-
headers: headers ? Object.keys(deriver.serializeNode(headers)) : [],
|
|
606
|
-
contentType,
|
|
607
|
-
statusCode: statusCode ? resolveStatusCode(statusCode) : "200",
|
|
608
|
-
response: node ? deriver.serializeNode(node) : void 0
|
|
609
|
-
});
|
|
610
|
-
});
|
|
611
|
-
visit2(handler.body);
|
|
612
|
-
return responsesList;
|
|
613
|
-
}
|
|
680
|
+
import {
|
|
681
|
+
isCallExpression as isCallExpression2,
|
|
682
|
+
isIdentifier as isIdentifier2,
|
|
683
|
+
isLiteralExpression,
|
|
684
|
+
isNewExpression as isNewExpression2,
|
|
685
|
+
isNumericLiteral,
|
|
686
|
+
isObjectLiteralExpression as isObjectLiteralExpression2,
|
|
687
|
+
isPropertyAccessExpression as isPropertyAccessExpression2,
|
|
688
|
+
isPropertyAssignment as isPropertyAssignment2
|
|
689
|
+
} from "@typescript/native/ast/is";
|
|
614
690
|
function resolveStatusCode(node) {
|
|
615
|
-
if (
|
|
691
|
+
if (isNumericLiteral(node)) {
|
|
616
692
|
return node.text;
|
|
617
693
|
}
|
|
618
694
|
throw new Error(`Could not resolve status code`);
|
|
619
695
|
}
|
|
620
|
-
function defaultResponseAnalyzer(handler, deriver) {
|
|
696
|
+
function defaultResponseAnalyzer(handler, deriver, returned) {
|
|
697
|
+
if (!isCallExpression2(returned) || !isPropertyAccessExpression2(returned.expression)) {
|
|
698
|
+
return [];
|
|
699
|
+
}
|
|
700
|
+
const method = returned.expression;
|
|
701
|
+
if (!isIdentifier2(method.expression) || method.expression.text !== "output") {
|
|
702
|
+
return [];
|
|
703
|
+
}
|
|
704
|
+
const [body, statusCode, headers] = returned.arguments;
|
|
705
|
+
let contentType = "application/json";
|
|
706
|
+
if (!body) {
|
|
707
|
+
contentType = "empty";
|
|
708
|
+
} else if (method.name.text === "attachment") {
|
|
709
|
+
contentType = "application/octet-stream";
|
|
710
|
+
}
|
|
621
711
|
try {
|
|
622
|
-
return
|
|
712
|
+
return [
|
|
713
|
+
{
|
|
714
|
+
headers: headers ? deriver.checker.getPropertiesOfType(deriver.checker.getTypeAtLocation(headers)).map((prop) => prop.name) : [],
|
|
715
|
+
contentType,
|
|
716
|
+
statusCode: statusCode ? resolveStatusCode(statusCode) : "200",
|
|
717
|
+
response: body ? deriver.serializeNode(body) : void 0
|
|
718
|
+
}
|
|
719
|
+
];
|
|
623
720
|
} catch (error) {
|
|
624
721
|
console.error("Error analyzing response\n", handler.getText());
|
|
625
722
|
throw error;
|
|
@@ -627,16 +724,16 @@ function defaultResponseAnalyzer(handler, deriver) {
|
|
|
627
724
|
}
|
|
628
725
|
var responseAnalyzer = {
|
|
629
726
|
"throw.new.ProblemDetailsException": (handler, deriver, node) => {
|
|
630
|
-
if (
|
|
727
|
+
if (isNewExpression2(node)) {
|
|
631
728
|
const [problem] = node.arguments ?? [];
|
|
632
|
-
if (!
|
|
729
|
+
if (!isObjectLiteralExpression2(problem)) {
|
|
633
730
|
return [];
|
|
634
731
|
}
|
|
635
732
|
const properties = problem.properties.reduce(
|
|
636
733
|
(acc, prop) => {
|
|
637
|
-
if (
|
|
734
|
+
if (isPropertyAssignment2(prop)) {
|
|
638
735
|
const key = prop.name.getText();
|
|
639
|
-
if (
|
|
736
|
+
if (isLiteralExpression(prop.initializer)) {
|
|
640
737
|
acc[key] = prop.initializer.text;
|
|
641
738
|
} else {
|
|
642
739
|
acc[key] = prop.initializer.getText();
|
|
@@ -662,7 +759,6 @@ var responseAnalyzer = {
|
|
|
662
759
|
export {
|
|
663
760
|
analyze,
|
|
664
761
|
defaultResponseAnalyzer,
|
|
665
|
-
responseAnalyzer
|
|
666
|
-
returnTokens
|
|
762
|
+
responseAnalyzer
|
|
667
763
|
};
|
|
668
764
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/lib/generic.ts", "../src/lib/response-analyzer.ts"],
|
|
4
|
-
"sourcesContent": ["import debug from 'debug';\nimport { realpathSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport type { SecurityRequirementObject } from 'openapi3-ts/oas31';\nimport { camelcase } from 'stringcase';\nimport ts from 'typescript';\n\nimport {\n type InjectImport,\n type NaunceResponseAnalyzer,\n type OnOperation,\n type OpenAPIComponentsObject,\n type OpenAPISecuritySchemeObject,\n Paths,\n type ResponseAnalyzerFn,\n type ResponseItem,\n type Selector,\n type SemanticSource,\n TypeDeriver,\n getProgram,\n isCallExpression,\n isHttpMethod,\n nodeLocation,\n toSchema,\n} from '@sdk-it/core';\n\n/**\n * Gets the file path from a symbol's first declaration\n */\nfunction symbolFile(symbol: ts.Symbol | undefined): string | undefined {\n if (!symbol) {\n return undefined;\n }\n\n const declarations = symbol.declarations ?? [];\n if (declarations.length === 0) {\n return undefined;\n }\n\n const sourceFile = declarations[0].getSourceFile();\n return sourceFile?.fileName;\n}\n\n/**\n * Determines if a symbol is from an external library (node_modules)\n */\nfunction isExternalFunction(symbol: ts.Symbol | undefined): boolean {\n const fileName = symbolFile(symbol);\n return fileName ? fileName.includes('node_modules') : false;\n}\n\n/**\n * Determines if a symbol refers to a local function (not from node_modules)\n */\nfunction isLocalFunction(symbol: ts.Symbol | undefined): boolean {\n if (!symbol) {\n return false;\n }\n\n return !isExternalFunction(symbol);\n}\n\nexport interface MiddlewareSecurityRule {\n middleware: {\n import: string;\n from: string;\n };\n security: SecurityRequirementObject[];\n values?: {\n scheme: string;\n argument: number;\n mode: 'any' | 'all';\n };\n}\n\nfunction resolvedSymbol(\n expression: ts.LeftHandSideExpression,\n typeChecker: ts.TypeChecker,\n) {\n const location = ts.isPropertyAccessExpression(expression)\n ? expression.name\n : expression;\n const symbol = typeChecker.getSymbolAtLocation(location);\n return symbol && symbol.flags & ts.SymbolFlags.Alias\n ? typeChecker.getAliasedSymbol(symbol)\n : symbol;\n}\n\n/**\n * Symlinked working directories (macOS `/tmp` -> `/private/tmp`) and Windows\n * drive-letter casing make two spellings of the same file compare unequal.\n */\nfunction realPath(path: string) {\n const resolved = resolve(path);\n try {\n return realpathSync.native(resolved);\n } catch {\n return resolved;\n }\n}\n\nfunction matchesMiddleware(\n symbol: ts.Symbol | undefined,\n middleware: MiddlewareSecurityRule['middleware'],\n) {\n if (symbol?.name !== middleware.import) {\n return false;\n }\n const from = realPath(middleware.from);\n return (symbol.declarations ?? []).some(\n (declaration) => realPath(declaration.getSourceFile().fileName) === from,\n );\n}\n\ninterface SecurityAnalysis {\n rules: readonly MiddlewareSecurityRule[];\n matched: Set<MiddlewareSecurityRule>;\n}\n\nfunction middlewareSecurity(\n args: readonly ts.Expression[],\n security: SecurityAnalysis,\n typeChecker: ts.TypeChecker,\n): SecurityRequirementObject[] {\n let requirements: SecurityRequirementObject[] | undefined;\n for (const arg of args) {\n const call = ts.isCallExpression(arg) ? arg : undefined;\n const reference = call ? call.expression : arg;\n if (\n !ts.isIdentifier(reference) &&\n !ts.isPropertyAccessExpression(reference)\n ) {\n continue;\n }\n const symbol = resolvedSymbol(reference, typeChecker);\n const rule = security.rules.find(({ middleware }) =>\n matchesMiddleware(symbol, middleware),\n );\n if (!rule) {\n continue;\n }\n security.matched.add(rule);\n if (rule.values && !call) {\n throw new TypeError(\n `Security middleware ${rule.middleware.import} must be called so argument ${rule.values.argument} can be read\\n at ${nodeLocation(arg) ?? 'unknown'}`,\n );\n }\n const requirement =\n rule.values && call\n ? securityWithValues(call, rule, rule.values, typeChecker)\n : structuredClone(rule.security);\n requirements = requirements\n ? andSecurity(requirements, requirement)\n : requirement;\n }\n return requirements ?? [];\n}\n\nfunction securityWithValues(\n call: ts.CallExpression,\n rule: MiddlewareSecurityRule,\n valuesConfig: NonNullable<MiddlewareSecurityRule['values']>,\n typeChecker: ts.TypeChecker,\n) {\n const expression = call.arguments[valuesConfig.argument];\n if (!expression) {\n throw new TypeError(\n `Security middleware ${rule.middleware.import} requires argument ${valuesConfig.argument}`,\n );\n }\n const resolved = constantStrings(expression, typeChecker);\n if (!resolved) {\n throw new TypeError(\n `Could not statically resolve security values at ${nodeLocation(expression) ?? 'unknown'}`,\n );\n }\n if (resolved.length === 0) {\n return structuredClone(rule.security);\n }\n const values = [...new Set(resolved)];\n return rule.security.flatMap((requirement) => {\n const existing = requirement[valuesConfig.scheme];\n if (!existing) {\n throw new TypeError(\n `Security scheme ${valuesConfig.scheme} is not present in the middleware requirement`,\n );\n }\n if (valuesConfig.mode === 'all') {\n return [\n {\n ...structuredClone(requirement),\n [valuesConfig.scheme]: [...new Set([...existing, ...values])],\n },\n ];\n }\n return values.map((value) => ({\n ...structuredClone(requirement),\n [valuesConfig.scheme]: [...new Set([...existing, value])],\n }));\n });\n}\n\nfunction constantStrings(\n expression: ts.Expression,\n typeChecker: ts.TypeChecker,\n visited = new Set<ts.Declaration>(),\n): string[] | undefined {\n while (\n ts.isParenthesizedExpression(expression) ||\n ts.isAsExpression(expression) ||\n ts.isTypeAssertionExpression(expression) ||\n ts.isSatisfiesExpression(expression) ||\n ts.isNonNullExpression(expression)\n ) {\n expression = expression.expression;\n }\n if (ts.isStringLiteralLike(expression)) {\n return [expression.text];\n }\n if (ts.isArrayLiteralExpression(expression)) {\n const result: string[] = [];\n for (const element of expression.elements) {\n if (ts.isOmittedExpression(element)) {\n continue;\n }\n const values = constantStrings(\n ts.isSpreadElement(element) ? element.expression : element,\n typeChecker,\n visited,\n );\n if (!values) {\n return undefined;\n }\n result.push(...values);\n }\n return result;\n }\n if (ts.isPropertyAccessExpression(expression)) {\n const value = typeChecker.getConstantValue(expression);\n if (typeof value === 'string') {\n return [value];\n }\n }\n if (\n ts.isIdentifier(expression) ||\n ts.isPropertyAccessExpression(expression)\n ) {\n const symbol = resolvedSymbol(expression, typeChecker);\n for (const declaration of symbol?.declarations ?? []) {\n // `visited` tracks the current recursion path, not everything ever seen,\n // so the same constant can be referenced more than once in one expression.\n if (visited.has(declaration)) {\n continue;\n }\n visited.add(declaration);\n try {\n if (\n (ts.isVariableDeclaration(declaration) ||\n ts.isEnumMember(declaration)) &&\n declaration.initializer\n ) {\n const values = constantStrings(\n declaration.initializer,\n typeChecker,\n visited,\n );\n if (values) {\n return values;\n }\n }\n } finally {\n visited.delete(declaration);\n }\n }\n }\n return undefined;\n}\n\nfunction andSecurity(\n left: SecurityRequirementObject[],\n right: SecurityRequirementObject[],\n) {\n const combined = left.flatMap((leftRequirement) =>\n right.map((rightRequirement) => {\n const requirement = structuredClone(leftRequirement);\n for (const [scheme, values] of Object.entries(rightRequirement)) {\n requirement[scheme] = [\n ...new Set([...(requirement[scheme] ?? []), ...values]),\n ];\n }\n return requirement;\n }),\n );\n return [\n ...new Map(\n combined.map((requirement) => [requirementKey(requirement), requirement]),\n ).values(),\n ];\n}\n\n/**\n * Scheme and value order carry no meaning in a security requirement, so the\n * identity key has to ignore both.\n */\nfunction requirementKey(requirement: SecurityRequirementObject) {\n return JSON.stringify(\n Object.keys(requirement)\n .sort()\n .map((scheme) => [scheme, [...requirement[scheme]].sort()]),\n );\n}\n\nexport const returnTokens = (\n node: ts.Node,\n typeChecker?: ts.TypeChecker,\n options?: { consider3rdParty?: boolean; maxDepth?: number },\n) => {\n const tokens: { token: string; node: ts.Expression }[] = [];\n const consider3rdParty = options?.consider3rdParty ?? false;\n const maxDepth = options?.maxDepth ?? 5;\n // Track visited function declarations to prevent infinite recursion\n const visitedFunctions = new Set<ts.Declaration>();\n\n const visitor = (node: ts.Node, depth: number): void => {\n // Skip if we've exceeded max depth\n if (depth > maxDepth) {\n return;\n }\n\n if (ts.isThrowStatement(node)) {\n let expression = node.expression;\n const visited = new Set<ts.Declaration>();\n while (true) {\n if (\n ts.isParenthesizedExpression(expression) ||\n ts.isAsExpression(expression) ||\n ts.isTypeAssertionExpression(expression) ||\n ts.isSatisfiesExpression(expression) ||\n ts.isNonNullExpression(expression)\n ) {\n expression = expression.expression;\n continue;\n }\n if (\n !typeChecker ||\n (!ts.isIdentifier(expression) &&\n !ts.isPropertyAccessExpression(expression))\n )\n break;\n // Structural property types can point at another object's declaration.\n // Only module namespace imports guarantee the referenced export binding.\n if (\n ts.isPropertyAccessExpression(expression) &&\n !typeChecker\n .getSymbolAtLocation(expression.expression)\n ?.declarations?.some(ts.isNamespaceImport)\n )\n break;\n const declaration = resolvedSymbol(\n expression,\n typeChecker,\n )?.valueDeclaration;\n if (\n !declaration ||\n visited.has(declaration) ||\n !ts.isVariableDeclaration(declaration) ||\n !ts.isVariableDeclarationList(declaration.parent) ||\n !(declaration.parent.flags & ts.NodeFlags.Const) ||\n !declaration.initializer\n )\n break;\n visited.add(declaration);\n expression = declaration.initializer;\n }\n if (ts.isNewExpression(expression)) {\n tokens.push({\n token: `throw.new.${expression.expression.getText()}`,\n node: expression,\n });\n }\n }\n\n if (ts.isReturnStatement(node) && node.expression) {\n if (ts.isCallExpression(node.expression)) {\n tokens.push({\n token: node.expression.expression.getText(),\n node: node.expression,\n });\n }\n if (ts.isNewExpression(node.expression)) {\n tokens.push({\n token: `new.${node.expression.expression.getText()}`,\n node: node.expression,\n });\n }\n // Continue traversing into the returned expression (e.g., arrow functions)\n // This handles: return async (c, next) => { throw ... }\n ts.forEachChild(node.expression, (child) => visitor(child, depth));\n return;\n }\n\n // If we encounter a call expression and have a type checker, follow it\n if (ts.isCallExpression(node) && typeChecker && depth < maxDepth) {\n const callExpression = node;\n\n // Try to resolve the function being called\n let symbol: ts.Symbol | undefined;\n\n if (ts.isIdentifier(callExpression.expression)) {\n symbol = typeChecker.getSymbolAtLocation(callExpression.expression);\n } else if (ts.isPropertyAccessExpression(callExpression.expression)) {\n symbol = typeChecker.getSymbolAtLocation(\n callExpression.expression.name,\n );\n }\n\n // Resolve aliases\n if (symbol && symbol.flags & ts.SymbolFlags.Alias) {\n symbol = typeChecker.getAliasedSymbol(symbol);\n }\n\n // Check if we should follow this function\n const shouldFollow = consider3rdParty || isLocalFunction(symbol);\n\n if (shouldFollow && symbol) {\n const declarations = symbol?.declarations ?? [];\n\n for (const declaration of declarations) {\n // Skip if we've already visited this function (prevent infinite recursion)\n if (visitedFunctions.has(declaration)) {\n continue;\n }\n\n if (isFunctionWithBody(declaration) && declaration.body) {\n visitedFunctions.add(declaration);\n // Recursively visit the function body with incremented depth\n visitor(declaration.body, depth + 1);\n }\n }\n }\n }\n\n ts.forEachChild(node, (child) => visitor(child, depth));\n };\n\n visitor(node, 0);\n return tokens;\n};\n\nconst logger = debug('@sdk-it/generic');\n\nconst jsDocsTags = [\n 'openapi',\n 'tags',\n 'description',\n 'summary',\n 'access',\n 'tool',\n 'toolDescription',\n] as const;\ntype JSDocsTags = (typeof jsDocsTags)[number];\n\nfunction parseJSDocComment(node: ts.Node) {\n let tags: string[] = [];\n let name = '';\n let description = '';\n let summary = '';\n let access = '';\n let tool = '';\n let toolDescription = '';\n\n for (const tag of ts.getAllJSDocTags(node, (tag): tag is ts.JSDocTag =>\n jsDocsTags.includes(tag.tagName.text as JSDocsTags),\n )) {\n if (typeof tag.comment !== 'string') {\n continue;\n }\n switch (tag.tagName.text as JSDocsTags) {\n case 'openapi':\n name = tag.comment;\n break;\n case 'tags':\n tags = tag.comment.split(',').map((tag) => tag.trim());\n break;\n case 'description':\n description = tag.comment;\n break;\n case 'summary':\n summary = tag.comment;\n break;\n case 'access':\n access = tag.comment.trim().toLowerCase();\n break;\n case 'tool':\n tool = tag.comment.trim();\n break;\n case 'toolDescription':\n toolDescription = tag.comment.trim();\n break;\n }\n }\n return {\n name,\n tags,\n description,\n access,\n tool,\n toolDescription,\n summary,\n };\n}\n\nfunction visit(\n node: ts.Node,\n responseAnalyzer: (\n handler: ts.ArrowFunction | ts.FunctionExpression,\n token: string,\n node: ts.Node,\n ) => ResponseItem[],\n paths: Paths,\n typeChecker: ts.TypeChecker,\n typeDeriver: TypeDeriver,\n security?: SecurityAnalysis,\n) {\n if (!ts.isCallExpression(node) || node.arguments.length < 2) {\n return moveOn();\n }\n if (\n !ts.isPropertyAccessExpression(node.expression) ||\n !ts.isIdentifier(node.expression.name) ||\n !isHttpMethod(node.expression.name.text)\n ) {\n return moveOn();\n }\n\n const [pathNode] = node.arguments;\n if (!ts.isStringLiteral(pathNode)) {\n return moveOn();\n }\n const method = node.expression.name.text;\n const path = pathNode.text;\n const validate = node.arguments.find((arg) =>\n isCallExpression(arg, 'validate'),\n );\n if (!validate) {\n return moveOn();\n }\n const handler = node.arguments.at(-1);\n if (!handler || !ts.isArrowFunction(handler)) {\n return moveOn();\n }\n const metadata = parseJSDocComment(node.parent);\n // Skip endpoints marked as private access\n if (metadata.access === 'private') {\n return moveOn();\n }\n const operationName =\n metadata.name ||\n camelcase(`${method} ${path.replace(/[^a-zA-Z0-9]/g, '')}`);\n if (!validate.arguments.length) {\n return moveOn();\n }\n\n let selector: ts.Expression | undefined;\n let contentType: ts.Expression | undefined;\n if (validate.arguments.length === 2) {\n contentType = validate.arguments[0];\n selector = validate.arguments[1];\n } else {\n selector = validate.arguments[0];\n }\n if (!ts.isArrowFunction(selector)) {\n return moveOn();\n }\n if (\n !selector ||\n !ts.isParenthesizedExpression(selector.body) ||\n !ts.isObjectLiteralExpression(selector.body.expression)\n ) {\n return moveOn();\n }\n\n // Collect all middleware declarations for analysis\n const middlewareDeclarations: { node: ts.Node; name?: string }[] = [];\n\n // slice(1, -1) to skip first (path) and last (handler) arguments\n // and skip the validate middleware - it's handled separately\n for (const arg of node.arguments.slice(1, -1)) {\n if (ts.isCallExpression(arg)) {\n // Try to resolve the factory function declaration\n if (ts.isIdentifier(arg.expression)) {\n const middlewareFnName = arg.expression.text;\n let symbol = typeChecker.getSymbolAtLocation(arg.expression);\n\n // If symbol has alias, resolve to the actual symbol\n if (symbol && symbol.flags & ts.SymbolFlags.Alias) {\n symbol = typeChecker.getAliasedSymbol(symbol);\n }\n\n const allDeclarations = [\n symbol?.valueDeclaration,\n ...(symbol?.declarations ?? []),\n ].filter((it) => !!it);\n\n let declaration = allDeclarations.find(isFunctionWithBody);\n\n // If not found, check for variable declarations with function initializers\n if (!declaration) {\n for (const decl of allDeclarations) {\n if (ts.isVariableDeclaration(decl) && decl.initializer) {\n if (isFunctionWithBody(decl.initializer)) {\n declaration = decl.initializer;\n break;\n }\n }\n }\n }\n\n if (declaration) {\n middlewareDeclarations.push({\n node: declaration,\n name: middlewareFnName,\n });\n }\n }\n\n // Also check if the call expression argument itself is an arrow function\n // e.g., middleware((ctx) => {...})\n // But skip if the function name is 'validate'\n if (\n ts.isIdentifier(arg.expression) &&\n arg.expression.text === 'validate'\n ) {\n continue;\n }\n const firstArg = arg.arguments[0];\n if (isFunctionWithBody(firstArg)) {\n middlewareDeclarations.push({ node: firstArg });\n }\n }\n }\n\n const props = selector.body.expression.properties.filter(\n ts.isPropertyAssignment,\n );\n\n const sourceFile = node.getSourceFile();\n\n typeDeriver.setTrace({\n file: sourceFile.fileName,\n operation: `${method.toUpperCase()} ${path}`,\n });\n\n const responses: ResponseItem[] = [];\n\n // Analyze all middlewares for potential responses\n for (const middleware of middlewareDeclarations) {\n for (const { token, node } of returnTokens(middleware.node, typeChecker)) {\n const items = responseAnalyzer(middleware.node as any, token, node);\n if (middleware.name) {\n for (const item of items) {\n item.middlewareName = middleware.name;\n }\n }\n responses.push(...items);\n }\n }\n\n // Analyze the main handler for responses\n for (const { token, node } of returnTokens(handler, typeChecker)) {\n responses.push(...responseAnalyzer(handler, token, node));\n }\n\n paths.addPath(\n operationName,\n path,\n method,\n contentType\n ? ts.isStringLiteral(contentType)\n ? contentType.text\n : undefined\n : undefined,\n toSelectors(props),\n responses,\n sourceFile.fileName,\n {\n ...metadata,\n security: security\n ? middlewareSecurity(node.arguments.slice(1, -1), security, typeChecker)\n : undefined,\n },\n );\n\n function moveOn() {\n ts.forEachChild(node, (node) =>\n visit(node, responseAnalyzer, paths, typeChecker, typeDeriver, security),\n );\n }\n}\n\nfunction toSelectors(props: ts.PropertyAssignment[]) {\n const selectors: Selector[] = [];\n for (const prop of props) {\n if (!ts.isObjectLiteralExpression(prop.initializer)) {\n continue;\n }\n const name = prop.name.getText();\n const select = prop.initializer.properties\n .filter(ts.isPropertyAssignment)\n .find((prop) => prop.name.getText() === 'select');\n if (!select) {\n console.warn(\n `\\u26a0 No select found in ${name}\\n at ${nodeLocation(prop) ?? 'unknown'}`,\n );\n continue;\n }\n const against = prop.initializer.properties\n .filter(ts.isPropertyAssignment)\n .find((prop) => prop.name.getText() === 'against');\n if (!against) {\n console.warn(\n `\\u26a0 No against found in ${name}\\n at ${nodeLocation(prop) ?? 'unknown'}`,\n );\n continue;\n }\n const [, source, selectText] = select.initializer.getText().split('.');\n selectors.push({\n name: selectText,\n against: against.initializer.getText(),\n source: source as SemanticSource,\n });\n }\n return selectors;\n}\n\nexport async function analyze(\n tsconfigPath: string,\n config: {\n /**\n * Additional code to inject before resolving zod schemas\n */\n imports?: InjectImport[];\n typesMap?: Record<string, string>;\n responseAnalyzer: ResponseAnalyzerFn | NaunceResponseAnalyzer;\n onOperation?: OnOperation;\n securitySchemes?: Record<string, OpenAPISecuritySchemeObject>;\n middlewareSecurity?: readonly MiddlewareSecurityRule[];\n },\n) {\n logger(`Parsing tsconfig`);\n const program = getProgram(tsconfigPath);\n logger(`Program created`);\n const typeChecker = program.getTypeChecker();\n\n logger(`Type checker created`);\n const typeDeriver = new TypeDeriver(typeChecker, config.typesMap);\n const paths = new Paths({\n imports: config.imports ?? [],\n onOperation: config.onOperation,\n });\n const security: SecurityAnalysis | undefined = config.middlewareSecurity && {\n rules: config.middlewareSecurity,\n matched: new Set(),\n };\n\n for (const sourceFile of program.getSourceFiles()) {\n logger(`Analyzing ${sourceFile.fileName}`);\n if (!sourceFile.isDeclarationFile) {\n logger(`Visiting ${sourceFile.fileName}`);\n visit(\n sourceFile,\n (handler, token, node) => {\n const responseAnalyzer = config.responseAnalyzer;\n if (typeof responseAnalyzer !== 'function') {\n const naunce =\n responseAnalyzer[token] || responseAnalyzer['default'];\n if (!naunce) {\n throw new Error(`No response analyzer for token ${token}`);\n }\n return naunce(handler, typeDeriver, node);\n }\n return responseAnalyzer(handler, typeDeriver);\n },\n paths,\n typeChecker,\n typeDeriver,\n security,\n );\n }\n }\n\n for (const rule of security?.rules ?? []) {\n if (!security?.matched.has(rule)) {\n console.warn(\n `\u26A0 Security middleware ${rule.middleware.import} from ${rule.middleware.from} matched no route\\n routes it protects are documented as public`,\n );\n }\n }\n\n const components: OpenAPIComponentsObject = {\n schemas: {\n ...paths.getSharedSchemas(),\n ...Object.entries(typeDeriver.collector).reduce(\n (acc, [key, value]) => ({ ...acc, [key]: toSchema(value) }),\n {},\n ),\n },\n securitySchemes: config.securitySchemes,\n };\n\n return {\n paths: await paths.getPaths(),\n tags: paths.getTags(),\n components,\n };\n}\n\nexport type Serialized = ReturnType<typeof analyze>;\n\nfunction isFunctionWithBody(\n node: ts.Node | ts.Declaration | undefined,\n): node is ts.FunctionLikeDeclaration & { body: ts.Block | ts.Expression } {\n if (!node) {\n return false;\n }\n return (\n (ts.isFunctionDeclaration(node) ||\n ts.isFunctionExpression(node) ||\n ts.isArrowFunction(node) ||\n ts.isMethodDeclaration(node) ||\n ts.isConstructorDeclaration(node) ||\n ts.isGetAccessor(node) ||\n ts.isSetAccessor(node)) &&\n !!node.body\n );\n}\n", "import ts from 'typescript';\n\nimport type {\n NaunceResponseAnalyzer,\n ResponseItem,\n TypeDeriver,\n} from '@sdk-it/core';\n\nconst handlerVisitor: (\n on: (\n node: ts.Node | undefined,\n statusCode: ts.Node | undefined,\n headers: ts.Node | undefined,\n contentType: string,\n ) => void,\n) => ts.Visitor = (callback) => {\n return (node: ts.Node) => {\n if (ts.isReturnStatement(node) && node.expression) {\n if (\n ts.isCallExpression(node.expression) &&\n ts.isPropertyAccessExpression(node.expression.expression)\n ) {\n const propAccess = node.expression.expression;\n if (\n ts.isIdentifier(propAccess.expression) &&\n propAccess.expression.text === 'output'\n ) {\n let contentType = 'application/json';\n const callerMethod = propAccess.name.text;\n const [body, statusCode, headers] = node.expression.arguments;\n if (callerMethod === 'attachment') {\n contentType = 'application/octet-stream';\n }\n if (!body) {\n contentType = 'empty';\n }\n callback(body, statusCode, headers, contentType);\n }\n }\n }\n return ts.forEachChild(node, handlerVisitor(callback));\n };\n};\n\nfunction toResponses(\n handler: ts.ArrowFunction | ts.FunctionExpression,\n deriver: TypeDeriver,\n) {\n const responsesList: ResponseItem[] = [];\n const visit = handlerVisitor((node, statusCode, headers, contentType) => {\n responsesList.push({\n headers: headers ? Object.keys(deriver.serializeNode(headers)) : [],\n contentType,\n statusCode: statusCode ? resolveStatusCode(statusCode) : '200',\n response: node ? deriver.serializeNode(node) : undefined,\n });\n });\n visit(handler.body);\n return responsesList;\n}\n\nfunction resolveStatusCode(node: ts.Node) {\n if (ts.isNumericLiteral(node)) {\n return node.text;\n }\n throw new Error(`Could not resolve status code`);\n}\n\nexport function defaultResponseAnalyzer(\n handler: ts.ArrowFunction | ts.FunctionExpression,\n deriver: TypeDeriver,\n) {\n try {\n return toResponses(handler, deriver);\n } catch (error) {\n console.error('Error analyzing response\\n', handler.getText());\n throw error;\n }\n}\n\nexport const responseAnalyzer: NaunceResponseAnalyzer = {\n 'throw.new.ProblemDetailsException': (handler, deriver, node) => {\n if (ts.isNewExpression(node)) {\n const [problem] = node.arguments ?? [];\n if (!ts.isObjectLiteralExpression(problem)) {\n return [];\n }\n const properties = problem.properties.reduce<Record<string, string>>(\n (acc, prop) => {\n if (ts.isPropertyAssignment(prop)) {\n const key = prop.name.getText();\n if (ts.isLiteralExpression(prop.initializer)) {\n acc[key] = prop.initializer.text;\n } else {\n acc[key] = prop.initializer.getText();\n }\n }\n return acc;\n },\n {},\n );\n return [\n {\n contentType: 'application/problem+json',\n headers: [],\n statusCode: properties.status,\n response: deriver.serializeNode(problem),\n },\n ];\n }\n return [];\n },\n default: defaultResponseAnal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CAAC;AAAA,EACV;AAAA,EACA,SAAS;AACX;",
|
|
6
|
-
"names": ["node", "tag", "responseAnalyzer", "prop", "
|
|
4
|
+
"sourcesContent": ["import {\n type CallExpression,\n type Expression,\n type LeftHandSideExpression,\n type Node,\n NodeFlags,\n type PropertyAssignment,\n getJSDocTags,\n getTextOfJSDocComment,\n} from '@typescript/native/ast';\nimport {\n isArrayLiteralExpression,\n isArrowFunction,\n isAsExpression,\n isAwaitExpression,\n isBlock,\n isCallExpression as isCall,\n isConditionalExpression,\n isConstructorDeclaration,\n isElementAccessExpression,\n isEnumMember,\n isFunctionDeclaration,\n isFunctionExpression,\n isGetAccessorDeclaration,\n isIdentifier,\n isMethodDeclaration,\n isNamespaceImport,\n isNewExpression,\n isNonNullExpression,\n isObjectLiteralExpression,\n isOmittedExpression,\n isParenthesizedExpression,\n isPropertyAccessExpression,\n isPropertyAssignment,\n isReturnStatement,\n isSatisfiesExpression,\n isSetAccessorDeclaration,\n isSpreadElement,\n isStringLiteral,\n isStringLiteralLikeNode,\n isThrowStatement,\n isTypeAssertion,\n isVariableDeclaration,\n isVariableDeclarationList,\n} from '@typescript/native/ast/is';\nimport {\n type Checker,\n SymbolFlags,\n type Symbol as TsSymbol,\n} from '@typescript/native/sync';\nimport { realpathSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { debuglog } from 'node:util';\nimport type { SecurityRequirementObject } from 'openapi3-ts/oas31';\nimport { camelcase } from 'stringcase';\n\nimport {\n type FunctionWithBody,\n type InjectImport,\n type NaunceResponseAnalyzer,\n type OnOperation,\n type OpenAPIComponentsObject,\n type OpenAPISecuritySchemeObject,\n Paths,\n type ResponseAnalyzerFn,\n type ResponseItem,\n type Selector,\n isHttpMethod,\n isSemanticSource,\n toSchema,\n} from '@sdk-it/core';\nimport { TypeDeriver, nodeLocation } from '@sdk-it/core/deriver.js';\nimport {\n type AnalysisProject,\n isCallExpression,\n sourceFiles,\n} from '@sdk-it/core/program.js';\n\nexport interface MiddlewareSecurityRule {\n middleware: {\n import: string;\n from: string;\n };\n security: SecurityRequirementObject[];\n values?: {\n scheme: string;\n argument: number;\n mode: 'any' | 'all';\n };\n}\n\nfunction resolvedSymbol(\n expression: LeftHandSideExpression,\n typeChecker: Checker,\n) {\n const location = isPropertyAccessExpression(expression)\n ? expression.name\n : expression;\n const symbol = typeChecker.getSymbolAtLocation(location);\n return symbol && symbol.flags & SymbolFlags.Alias\n ? typeChecker.getAliasedSymbol(symbol)\n : symbol;\n}\n\n/**\n * Symlinked working directories (macOS `/tmp` -> `/private/tmp`) and Windows\n * drive-letter casing make two spellings of the same file compare unequal.\n */\nfunction realPath(path: string) {\n const resolved = resolve(path);\n try {\n return realpathSync.native(resolved);\n } catch {\n return resolved;\n }\n}\n\nfunction matchesMiddleware(\n symbol: TsSymbol | undefined,\n middleware: MiddlewareSecurityRule['middleware'],\n) {\n if (symbol?.name !== middleware.import) {\n return false;\n }\n const from = realPath(middleware.from);\n return symbol.declarations.some((handle) => {\n const fileName = handle.resolve()?.getSourceFile().fileName;\n return fileName !== undefined && realPath(fileName) === from;\n });\n}\n\ninterface SecurityAnalysis {\n rules: readonly MiddlewareSecurityRule[];\n matched: Set<MiddlewareSecurityRule>;\n}\n\nfunction middlewareSecurity(\n args: readonly Expression[],\n security: SecurityAnalysis,\n typeChecker: Checker,\n): SecurityRequirementObject[] {\n let requirements: SecurityRequirementObject[] | undefined;\n for (const arg of args) {\n const call = isCall(arg) ? arg : undefined;\n const reference = call ? call.expression : arg;\n if (!isIdentifier(reference) && !isPropertyAccessExpression(reference)) {\n continue;\n }\n const symbol = resolvedSymbol(reference, typeChecker);\n const rule = security.rules.find(({ middleware }) =>\n matchesMiddleware(symbol, middleware),\n );\n if (!rule) {\n continue;\n }\n security.matched.add(rule);\n if (rule.values && !call) {\n throw new TypeError(\n `Security middleware ${rule.middleware.import} must be called so argument ${rule.values.argument} can be read\\n at ${nodeLocation(arg) ?? 'unknown'}`,\n );\n }\n const requirement =\n rule.values && call\n ? securityWithValues(call, rule, rule.values, typeChecker)\n : structuredClone(rule.security);\n requirements = requirements\n ? andSecurity(requirements, requirement)\n : requirement;\n }\n return requirements ?? [];\n}\n\nfunction securityWithValues(\n call: CallExpression,\n rule: MiddlewareSecurityRule,\n valuesConfig: NonNullable<MiddlewareSecurityRule['values']>,\n typeChecker: Checker,\n) {\n const expression = call.arguments[valuesConfig.argument];\n if (!expression) {\n throw new TypeError(\n `Security middleware ${rule.middleware.import} requires argument ${valuesConfig.argument}`,\n );\n }\n const resolved = constantStrings(expression, typeChecker);\n if (!resolved) {\n throw new TypeError(\n `Could not statically resolve security values at ${nodeLocation(expression) ?? 'unknown'}`,\n );\n }\n if (resolved.length === 0) {\n return structuredClone(rule.security);\n }\n const values = [...new Set(resolved)];\n return rule.security.flatMap((requirement) => {\n const existing = requirement[valuesConfig.scheme];\n if (!existing) {\n throw new TypeError(\n `Security scheme ${valuesConfig.scheme} is not present in the middleware requirement`,\n );\n }\n if (valuesConfig.mode === 'all') {\n return [\n {\n ...structuredClone(requirement),\n [valuesConfig.scheme]: [...new Set([...existing, ...values])],\n },\n ];\n }\n return values.map((value) => ({\n ...structuredClone(requirement),\n [valuesConfig.scheme]: [...new Set([...existing, value])],\n }));\n });\n}\n\nfunction constantStrings(\n expression: Expression,\n typeChecker: Checker,\n visited = new Set<Node>(),\n): string[] | undefined {\n while (\n isParenthesizedExpression(expression) ||\n isAsExpression(expression) ||\n isTypeAssertion(expression) ||\n isSatisfiesExpression(expression) ||\n isNonNullExpression(expression)\n ) {\n expression = expression.expression;\n }\n if (isStringLiteralLikeNode(expression)) {\n return [expression.text];\n }\n if (isArrayLiteralExpression(expression)) {\n const result: string[] = [];\n for (const element of expression.elements) {\n if (isOmittedExpression(element)) {\n continue;\n }\n const values = constantStrings(\n isSpreadElement(element) ? element.expression : element,\n typeChecker,\n visited,\n );\n if (!values) {\n return undefined;\n }\n result.push(...values);\n }\n return result;\n }\n if (isPropertyAccessExpression(expression)) {\n const value = typeChecker.getConstantValue(expression);\n if (typeof value === 'string') {\n return [value];\n }\n }\n if (isIdentifier(expression) || isPropertyAccessExpression(expression)) {\n const symbol = resolvedSymbol(expression, typeChecker);\n for (const handle of symbol?.declarations ?? []) {\n const declaration = handle.resolve();\n // `visited` tracks the current recursion path, not everything ever seen,\n // so the same constant can be referenced more than once in one expression.\n if (!declaration || visited.has(declaration)) {\n continue;\n }\n visited.add(declaration);\n try {\n if (\n (isVariableDeclaration(declaration) || isEnumMember(declaration)) &&\n declaration.initializer\n ) {\n const values = constantStrings(\n declaration.initializer,\n typeChecker,\n visited,\n );\n if (values) {\n return values;\n }\n }\n } finally {\n visited.delete(declaration);\n }\n }\n }\n return undefined;\n}\n\nfunction andSecurity(\n left: SecurityRequirementObject[],\n right: SecurityRequirementObject[],\n) {\n const combined = left.flatMap((leftRequirement) =>\n right.map((rightRequirement) => {\n const requirement = structuredClone(leftRequirement);\n for (const [scheme, values] of Object.entries(rightRequirement)) {\n requirement[scheme] = [\n ...new Set([...(requirement[scheme] ?? []), ...values]),\n ];\n }\n return requirement;\n }),\n );\n return [\n ...new Map(\n combined.map((requirement) => [requirementKey(requirement), requirement]),\n ).values(),\n ];\n}\n\n/**\n * Scheme and value order carry no meaning in a security requirement, so the\n * identity key has to ignore both.\n */\nfunction requirementKey(requirement: SecurityRequirementObject) {\n return JSON.stringify(\n Object.keys(requirement)\n .sort()\n .map((scheme) => [scheme, requirement[scheme].toSorted()]),\n );\n}\n\n/**\n * The calls whose value a returned expression passes on as the response:\n * through await, parentheses, type assertions, satisfies and non-null, and\n * both branches of a conditional.\n */\nfunction returnedCalls(expression: Expression): CallExpression[] {\n if (\n isAwaitExpression(expression) ||\n isParenthesizedExpression(expression) ||\n isAsExpression(expression) ||\n isTypeAssertion(expression) ||\n isSatisfiesExpression(expression) ||\n isNonNullExpression(expression)\n ) {\n return returnedCalls(expression.expression);\n }\n if (isConditionalExpression(expression)) {\n return [\n ...returnedCalls(expression.whenTrue),\n ...returnedCalls(expression.whenFalse),\n ];\n }\n return isCall(expression) ? [expression] : [];\n}\n\n/**\n * Collects the tokens that become a handler's responses. In returned mode a\n * return statement is a response; in discarded mode only throws are, because\n * the caller drops the value. A call is followed in returned mode only when\n * its value is returned, so a helper that the handler calls for its side\n * effects adds its throws but never its returns.\n */\nfunction returnTokens(node: Node, typeChecker: Checker) {\n const tokens: { token: string; node: Expression }[] = [];\n const maxDepth = 5;\n // A function is read once per mode: a discarded visit skips its returns,\n // so a later returned call to it must read it again.\n const visitedFunctions = {\n returned: new Set<Node>(),\n discarded: new Set<Node>(),\n };\n\n const follow = (\n callExpression: CallExpression,\n depth: number,\n returned: boolean,\n ): void => {\n if (depth >= maxDepth) {\n return;\n }\n\n let symbol: TsSymbol | undefined;\n if (isIdentifier(callExpression.expression)) {\n symbol = typeChecker.getSymbolAtLocation(callExpression.expression);\n } else if (isPropertyAccessExpression(callExpression.expression)) {\n symbol = typeChecker.getSymbolAtLocation(callExpression.expression.name);\n }\n if (symbol && symbol.flags & SymbolFlags.Alias) {\n symbol = typeChecker.getAliasedSymbol(symbol);\n }\n\n // Only source the program reads has a body to follow: a package that\n // ships declarations does not, one read through @sdk-it/source does.\n if (!symbol) {\n return;\n }\n const visited = returned\n ? visitedFunctions.returned\n : visitedFunctions.discarded;\n for (const handle of symbol.declarations) {\n const declaration = handle.resolve();\n if (!declaration || visited.has(declaration)) {\n continue;\n }\n if (isFunctionWithBody(declaration) && declaration.body) {\n visited.add(declaration);\n visitor(declaration.body, depth + 1, returned);\n }\n }\n };\n\n const visitor = (node: Node, depth: number, returned: boolean): void => {\n // Skip if we've exceeded max depth\n if (depth > maxDepth) {\n return;\n }\n\n if (isThrowStatement(node)) {\n let expression = node.expression;\n const visited = new Set<Node>();\n while (true) {\n if (\n isParenthesizedExpression(expression) ||\n isAsExpression(expression) ||\n isTypeAssertion(expression) ||\n isSatisfiesExpression(expression) ||\n isNonNullExpression(expression)\n ) {\n expression = expression.expression;\n continue;\n }\n if (\n !isIdentifier(expression) &&\n !isPropertyAccessExpression(expression)\n )\n break;\n // Structural property types can point at another object's declaration.\n // Only module namespace imports guarantee the referenced export binding.\n if (\n isPropertyAccessExpression(expression) &&\n !typeChecker\n .getSymbolAtLocation(expression.expression)\n ?.declarations.some(isNamespaceImport.Handle)\n )\n break;\n const declaration = resolvedSymbol(\n expression,\n typeChecker,\n )?.valueDeclaration?.resolve();\n if (\n !declaration ||\n visited.has(declaration) ||\n !isVariableDeclaration(declaration) ||\n !isVariableDeclarationList(declaration.parent) ||\n !(declaration.parent.flags & NodeFlags.Const) ||\n !declaration.initializer\n )\n break;\n visited.add(declaration);\n expression = declaration.initializer;\n }\n if (isNewExpression(expression)) {\n tokens.push({\n token: `throw.new.${expression.expression.getText()}`,\n node: expression,\n });\n } else if (isCall(expression)) {\n // A factory call (e.g. an error catalog entry) is keyed by the type it returns.\n const thrown = typeChecker\n .getTypeAtLocation(expression)\n .getSymbol()?.name;\n if (thrown) {\n tokens.push({ token: `throw.call.${thrown}`, node: expression });\n }\n }\n }\n\n if (isReturnStatement(node) && node.expression) {\n visitReturned(node.expression, depth, returned);\n return;\n }\n\n // A concise arrow body is the function's return value: () => (c) => { ... }\n if (isArrowFunction(node) && !isBlock(node.body)) {\n for (const parameter of node.parameters) {\n visitor(parameter, depth, false);\n }\n visitReturned(node.body, depth, returned);\n return;\n }\n\n if (isCall(node)) {\n follow(node, depth, false);\n }\n\n // A nested function's returns answer its own caller, not this one.\n node.forEachChild((child) =>\n visitor(child, depth, returned && !isFunctionWithBody(child)),\n );\n };\n\n const visitReturned = (\n expression: Expression,\n depth: number,\n returned: boolean,\n ): void => {\n // A parenthesized value is the value itself: (c) => (c.json(x))\n if (isParenthesizedExpression(expression)) {\n visitReturned(expression.expression, depth, returned);\n return;\n }\n if (returned) {\n if (isCall(expression)) {\n tokens.push({\n token: expression.expression.getText(),\n node: expression,\n });\n }\n if (isNewExpression(expression)) {\n tokens.push({\n token: `new.${expression.expression.getText()}`,\n node: expression,\n });\n }\n }\n for (const call of returnedCalls(expression)) {\n follow(call, depth, returned);\n }\n // A returned function keeps the mode: return async (c, next) => { ... }\n if (isFunctionWithBody(expression)) {\n visitor(expression, depth, returned);\n } else {\n expression.forEachChild((child) => visitor(child, depth, returned));\n }\n };\n\n visitor(node, 0, true);\n return tokens;\n}\n\nconst logger = debuglog('@sdk-it/generic');\n\nconst jsDocsTags = [\n 'openapi',\n 'tags',\n 'description',\n 'summary',\n 'access',\n 'tool',\n 'toolDescription',\n] as const;\n\nfunction parseJSDocComment(node: Node) {\n let tags: string[] = [];\n let name = '';\n let description = '';\n let summary = '';\n let access = '';\n let tool = '';\n let toolDescription = '';\n\n for (const tag of getJSDocTags(node)) {\n const tagName = jsDocsTags.find((name) => name === tag.tagName.text);\n if (tagName === undefined) {\n continue;\n }\n const comment = getTextOfJSDocComment(tag.comment);\n if (comment === undefined) {\n continue;\n }\n switch (tagName) {\n case 'openapi':\n name = comment;\n break;\n case 'tags':\n tags = comment.split(',').map((tag) => tag.trim());\n break;\n case 'description':\n description = comment;\n break;\n case 'summary':\n summary = comment;\n break;\n case 'access':\n access = comment.trim().toLowerCase();\n break;\n case 'tool':\n tool = comment.trim();\n break;\n case 'toolDescription':\n toolDescription = comment.trim();\n break;\n }\n }\n return {\n name,\n tags,\n description,\n access,\n tool,\n toolDescription,\n summary,\n };\n}\n\nfunction visit(\n node: Node,\n responseAnalyzer: (\n handler: FunctionWithBody,\n token: string,\n node: Node,\n ) => ResponseItem[],\n paths: Paths,\n typeChecker: Checker,\n typeDeriver: TypeDeriver,\n security?: SecurityAnalysis,\n) {\n if (!isCall(node) || node.arguments.length < 2) {\n return moveOn();\n }\n if (\n !isPropertyAccessExpression(node.expression) ||\n !isIdentifier(node.expression.name) ||\n !isHttpMethod(node.expression.name.text)\n ) {\n return moveOn();\n }\n\n const [pathNode] = node.arguments;\n if (!isStringLiteral(pathNode)) {\n return moveOn();\n }\n const method = node.expression.name.text;\n const path = pathNode.text;\n const validate = node.arguments.find((arg) =>\n isCallExpression(arg, 'validate'),\n );\n if (!validate) {\n return moveOn();\n }\n const handler = node.arguments.at(-1);\n if (!handler || !isArrowFunction(handler)) {\n return moveOn();\n }\n const metadata = parseJSDocComment(node.parent);\n // Skip endpoints marked as private access\n if (metadata.access === 'private') {\n return moveOn();\n }\n const operationName =\n metadata.name ||\n camelcase(`${method} ${path.replace(/[^a-zA-Z0-9]/g, '')}`);\n if (!validate.arguments.length) {\n return moveOn();\n }\n\n let selector: Expression | undefined;\n let contentType: Expression | undefined;\n if (validate.arguments.length === 2) {\n contentType = validate.arguments[0];\n selector = validate.arguments[1];\n } else {\n selector = validate.arguments[0];\n }\n if (!isArrowFunction(selector)) {\n return moveOn();\n }\n if (\n !selector ||\n !isParenthesizedExpression(selector.body) ||\n !isObjectLiteralExpression(selector.body.expression)\n ) {\n return moveOn();\n }\n\n // Collect all middleware declarations for analysis\n const middlewareDeclarations: { node: FunctionWithBody; name?: string }[] =\n [];\n\n // slice(1, -1) to skip first (path) and last (handler) arguments\n // and skip the validate middleware - it's handled separately\n for (const arg of node.arguments.slice(1, -1)) {\n if (isCall(arg)) {\n // Try to resolve the factory function declaration\n if (isIdentifier(arg.expression)) {\n const middlewareFnName = arg.expression.text;\n let symbol = typeChecker.getSymbolAtLocation(arg.expression);\n\n // If symbol has alias, resolve to the actual symbol\n if (symbol && symbol.flags & SymbolFlags.Alias) {\n symbol = typeChecker.getAliasedSymbol(symbol);\n }\n\n const allDeclarations = [\n symbol?.valueDeclaration,\n ...(symbol?.declarations ?? []),\n ]\n .map((handle) => handle?.resolve())\n .filter((declaration) => declaration !== undefined);\n\n let declaration = allDeclarations.find(isFunctionWithBody);\n\n // If not found, check for variable declarations with function initializers\n if (!declaration) {\n for (const decl of allDeclarations) {\n if (isVariableDeclaration(decl) && decl.initializer) {\n if (isFunctionWithBody(decl.initializer)) {\n declaration = decl.initializer;\n break;\n }\n }\n }\n }\n\n if (declaration) {\n middlewareDeclarations.push({\n node: declaration,\n name: middlewareFnName,\n });\n }\n }\n\n // Also check if the call expression argument itself is an arrow function\n // e.g., middleware((ctx) => {...})\n // But skip if the function name is 'validate'\n if (isIdentifier(arg.expression) && arg.expression.text === 'validate') {\n continue;\n }\n const firstArg = arg.arguments[0];\n if (isFunctionWithBody(firstArg)) {\n middlewareDeclarations.push({ node: firstArg });\n }\n }\n }\n\n const props =\n selector.body.expression.properties.filter(isPropertyAssignment);\n\n const sourceFile = node.getSourceFile();\n\n typeDeriver.setTrace({\n file: sourceFile.fileName,\n operation: `${method.toUpperCase()} ${path}`,\n });\n\n const responses: ResponseItem[] = [];\n\n // Analyze all middlewares for potential responses\n for (const middleware of middlewareDeclarations) {\n for (const { token, node } of returnTokens(middleware.node, typeChecker)) {\n const items = responseAnalyzer(middleware.node, token, node);\n if (middleware.name) {\n for (const item of items) {\n item.middlewareName = middleware.name;\n }\n }\n responses.push(...items);\n }\n }\n\n // Analyze the main handler for responses\n for (const { token, node } of returnTokens(handler, typeChecker)) {\n responses.push(...responseAnalyzer(handler, token, node));\n }\n\n paths.addPath(\n operationName,\n path,\n method,\n contentType\n ? isStringLiteral(contentType)\n ? contentType.text\n : undefined\n : undefined,\n toSelectors(props),\n responses,\n sourceFile.fileName,\n {\n ...metadata,\n security: security\n ? middlewareSecurity(node.arguments.slice(1, -1), security, typeChecker)\n : undefined,\n },\n );\n\n function moveOn() {\n node.forEachChild((node) =>\n visit(node, responseAnalyzer, paths, typeChecker, typeDeriver, security),\n );\n }\n}\n\nfunction toSelectors(props: PropertyAssignment[]) {\n const selectors: Selector[] = [];\n for (const prop of props) {\n if (!isObjectLiteralExpression(prop.initializer)) {\n continue;\n }\n const name = prop.name.getText();\n const select = prop.initializer.properties\n .filter(isPropertyAssignment)\n .find((prop) => prop.name.getText() === 'select');\n if (!select) {\n console.warn(\n `\\u26a0 No select found in ${name}\\n at ${nodeLocation(prop) ?? 'unknown'}`,\n );\n continue;\n }\n const against = prop.initializer.properties\n .filter(isPropertyAssignment)\n .find((prop) => prop.name.getText() === 'against');\n if (!against) {\n console.warn(\n `\\u26a0 No against found in ${name}\\n at ${nodeLocation(prop) ?? 'unknown'}`,\n );\n continue;\n }\n const selector = toSelector(\n select.initializer,\n against.initializer.getText(),\n );\n if (!selector) {\n console.warn(\n `\u26A0 Unsupported select in ${name}: ${select.initializer.getText()}. Select payload.body or one value, such as payload.params.id or payload.headers['x-id'].\\n at ${nodeLocation(prop) ?? 'unknown'}`,\n );\n continue;\n }\n selectors.push(selector);\n }\n return selectors;\n}\n\n/**\n * `payload.body` selects the whole body; `payload.<source>.<name>` and\n * `payload.<source>['<name>']` select one value.\n */\nfunction toSelector(select: Expression, against: string): Selector | undefined {\n if (isPropertyAccessExpression(select) && isIdentifier(select.expression)) {\n return select.name.text === 'body' ? { kind: 'body', against } : undefined;\n }\n if (\n !isPropertyAccessExpression(select) &&\n !isElementAccessExpression(select)\n ) {\n return undefined;\n }\n const name = memberName(select);\n const owner = select.expression;\n if (\n name === undefined ||\n !isPropertyAccessExpression(owner) ||\n !isIdentifier(owner.expression) ||\n !isSemanticSource(owner.name.text)\n ) {\n return undefined;\n }\n return { kind: 'field', source: owner.name.text, name, against };\n}\n\nfunction memberName(node: Expression): string | undefined {\n if (isPropertyAccessExpression(node)) {\n return node.name.text;\n }\n if (\n isElementAccessExpression(node) &&\n isStringLiteralLikeNode(node.argumentExpression)\n ) {\n return node.argumentExpression.text;\n }\n return undefined;\n}\n\nexport async function analyze(\n project: AnalysisProject,\n config: {\n /**\n * Additional code to inject before resolving zod schemas\n */\n imports?: InjectImport[];\n typesMap?: Record<string, string>;\n responseAnalyzer: ResponseAnalyzerFn | NaunceResponseAnalyzer;\n onOperation?: OnOperation;\n securitySchemes?: Record<string, OpenAPISecuritySchemeObject>;\n middlewareSecurity?: readonly MiddlewareSecurityRule[];\n },\n) {\n const typeChecker = project.checker;\n const typeDeriver = new TypeDeriver(typeChecker, config.typesMap);\n const paths = new Paths({\n imports: config.imports ?? [],\n onOperation: config.onOperation,\n });\n const security: SecurityAnalysis | undefined = config.middlewareSecurity && {\n rules: config.middlewareSecurity,\n matched: new Set(),\n };\n\n for (const sourceFile of sourceFiles(project.program)) {\n logger(`Visiting ${sourceFile.fileName}`);\n visit(\n sourceFile,\n (handler, token, node) => {\n const responseAnalyzer = config.responseAnalyzer;\n if (typeof responseAnalyzer !== 'function') {\n const naunce = responseAnalyzer[token];\n if (naunce) {\n return naunce(handler, typeDeriver, node);\n }\n // A thrown value that no analyzer claims is not a documented response.\n if (token.startsWith('throw.')) {\n return [];\n }\n const fallback = responseAnalyzer['default'];\n if (!fallback) {\n throw new Error(`No response analyzer for token ${token}`);\n }\n return fallback(handler, typeDeriver, node);\n }\n return responseAnalyzer(handler, typeDeriver);\n },\n paths,\n typeChecker,\n typeDeriver,\n security,\n );\n }\n\n for (const rule of security?.rules ?? []) {\n if (!security?.matched.has(rule)) {\n console.warn(\n `\u26A0 Security middleware ${rule.middleware.import} from ${rule.middleware.from} matched no route\\n routes it protects are documented as public`,\n );\n }\n }\n\n const pathsObject = await paths.getPaths();\n const components: OpenAPIComponentsObject = {\n schemas: {\n ...paths.getSharedSchemas(),\n ...Object.entries(typeDeriver.collector).reduce(\n (acc, [key, value]) => ({ ...acc, [key]: toSchema(value) }),\n {},\n ),\n },\n securitySchemes: config.securitySchemes,\n };\n\n return {\n paths: pathsObject,\n tags: paths.getTags(),\n components,\n };\n}\n\nexport type Serialized = ReturnType<typeof analyze>;\n\nfunction isFunctionWithBody(node: Node | undefined): node is FunctionWithBody {\n if (!node) {\n return false;\n }\n return (\n (isFunctionDeclaration(node) ||\n isFunctionExpression(node) ||\n isArrowFunction(node) ||\n isMethodDeclaration(node) ||\n isConstructorDeclaration(node) ||\n isGetAccessorDeclaration(node) ||\n isSetAccessorDeclaration(node)) &&\n !!node.body\n );\n}\n", "import type { Node } from '@typescript/native/ast';\nimport {\n isCallExpression,\n isIdentifier,\n isLiteralExpression,\n isNewExpression,\n isNumericLiteral,\n isObjectLiteralExpression,\n isPropertyAccessExpression,\n isPropertyAssignment,\n} from '@typescript/native/ast/is';\n\nimport type {\n FunctionWithBody,\n NaunceResponseAnalyzer,\n ResponseItem,\n} from '@sdk-it/core';\nimport type { TypeDeriver } from '@sdk-it/core/deriver.js';\n\nfunction resolveStatusCode(node: Node) {\n if (isNumericLiteral(node)) {\n return node.text;\n }\n throw new Error(`Could not resolve status code`);\n}\n\n/** The response `returned`, a value the handler returns, sends when it is an `output` call, such as `output.json(body, 201)`. */\nexport function defaultResponseAnalyzer(\n handler: FunctionWithBody,\n deriver: TypeDeriver,\n returned: Node,\n): ResponseItem[] {\n if (\n !isCallExpression(returned) ||\n !isPropertyAccessExpression(returned.expression)\n ) {\n return [];\n }\n const method = returned.expression;\n if (!isIdentifier(method.expression) || method.expression.text !== 'output') {\n return [];\n }\n const [body, statusCode, headers] = returned.arguments;\n let contentType = 'application/json';\n if (!body) {\n contentType = 'empty';\n } else if (method.name.text === 'attachment') {\n contentType = 'application/octet-stream';\n }\n try {\n return [\n {\n headers: headers\n ? deriver.checker\n .getPropertiesOfType(deriver.checker.getTypeAtLocation(headers))\n .map((prop) => prop.name)\n : [],\n contentType,\n statusCode: statusCode ? resolveStatusCode(statusCode) : '200',\n response: body ? deriver.serializeNode(body) : undefined,\n },\n ];\n } catch (error) {\n console.error('Error analyzing response\\n', handler.getText());\n throw error;\n }\n}\n\nexport const responseAnalyzer: NaunceResponseAnalyzer = {\n 'throw.new.ProblemDetailsException': (handler, deriver, node) => {\n if (isNewExpression(node)) {\n const [problem] = node.arguments ?? [];\n if (!isObjectLiteralExpression(problem)) {\n return [];\n }\n const properties = problem.properties.reduce<Record<string, string>>(\n (acc, prop) => {\n if (isPropertyAssignment(prop)) {\n const key = prop.name.getText();\n if (isLiteralExpression(prop.initializer)) {\n acc[key] = prop.initializer.text;\n } else {\n acc[key] = prop.initializer.getText();\n }\n }\n return acc;\n },\n {},\n );\n return [\n {\n contentType: 'application/problem+json',\n headers: [],\n statusCode: properties.status,\n response: deriver.serializeNode(problem),\n },\n ];\n }\n return [];\n },\n default: defaultResponseAnalyzer,\n};\n\nexport default responseAnalyzer;\n"],
|
|
5
|
+
"mappings": ";AAAA;AAAA,EAKE;AAAA,EAEA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,oBAAoB;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EAEE;AAAA,OAEK;AACP,SAAS,oBAAoB;AAC7B,SAAS,eAAe;AACxB,SAAS,gBAAgB;AAEzB,SAAS,iBAAiB;AAE1B;AAAA,EAOE;AAAA,EAIA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa,oBAAoB;AAC1C;AAAA,EAEE;AAAA,EACA;AAAA,OACK;AAeP,SAAS,eACP,YACA,aACA;AACA,QAAM,WAAW,2BAA2B,UAAU,IAClD,WAAW,OACX;AACJ,QAAM,SAAS,YAAY,oBAAoB,QAAQ;AACvD,SAAO,UAAU,OAAO,QAAQ,YAAY,QACxC,YAAY,iBAAiB,MAAM,IACnC;AACN;AAMA,SAAS,SAAS,MAAc;AAC9B,QAAM,WAAW,QAAQ,IAAI;AAC7B,MAAI;AACF,WAAO,aAAa,OAAO,QAAQ;AAAA,EACrC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,kBACP,QACA,YACA;AACA,MAAI,QAAQ,SAAS,WAAW,QAAQ;AACtC,WAAO;AAAA,EACT;AACA,QAAM,OAAO,SAAS,WAAW,IAAI;AACrC,SAA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zC,kBAAI,GAAG,IAAI,KAAK,YAAY;AAAA,YAC9B,OAAO;AACL,kBAAI,GAAG,IAAI,KAAK,YAAY,QAAQ;AAAA,YACtC;AAAA,UACF;AACA,iBAAO;AAAA,QACT;AAAA,QACA,CAAC;AAAA,MACH;AACA,aAAO;AAAA,QACL;AAAA,UACE,aAAa;AAAA,UACb,SAAS,CAAC;AAAA,UACV,YAAY,WAAW;AAAA,UACvB,UAAU,QAAQ,cAAc,OAAO;AAAA,QACzC;AAAA,MACF;AAAA,IACF;AACA,WAAO,CAAC;AAAA,EACV;AAAA,EACA,SAAS;AACX;",
|
|
6
|
+
"names": ["node", "name", "tag", "responseAnalyzer", "declaration", "prop", "isCallExpression", "isIdentifier", "isNewExpression", "isObjectLiteralExpression", "isPropertyAccessExpression", "isPropertyAssignment"]
|
|
7
7
|
}
|
package/dist/lib/generic.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { SecurityRequirementObject } from 'openapi3-ts/oas31';
|
|
2
|
-
import ts from 'typescript';
|
|
3
2
|
import { type InjectImport, type NaunceResponseAnalyzer, type OnOperation, type OpenAPIComponentsObject, type OpenAPISecuritySchemeObject, type ResponseAnalyzerFn } from '@sdk-it/core';
|
|
3
|
+
import { type AnalysisProject } from '@sdk-it/core/program.js';
|
|
4
4
|
export interface MiddlewareSecurityRule {
|
|
5
5
|
middleware: {
|
|
6
6
|
import: string;
|
|
@@ -13,14 +13,7 @@ export interface MiddlewareSecurityRule {
|
|
|
13
13
|
mode: 'any' | 'all';
|
|
14
14
|
};
|
|
15
15
|
}
|
|
16
|
-
export declare
|
|
17
|
-
consider3rdParty?: boolean;
|
|
18
|
-
maxDepth?: number;
|
|
19
|
-
}) => {
|
|
20
|
-
token: string;
|
|
21
|
-
node: ts.Expression;
|
|
22
|
-
}[];
|
|
23
|
-
export declare function analyze(tsconfigPath: string, config: {
|
|
16
|
+
export declare function analyze(project: AnalysisProject, config: {
|
|
24
17
|
/**
|
|
25
18
|
* Additional code to inject before resolving zod schemas
|
|
26
19
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generic.d.ts","
|
|
1
|
+
{"version":3,"file":"generic.d.ts","sources":["../../src/lib/generic.ts"],"names":[],"mappings":"AAqDA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAGnE,OAAO,EAEL,KAAK,YAAY,EACjB,KAAK,sBAAsB,EAC3B,KAAK,WAAW,EAChB,KAAK,uBAAuB,EAC5B,KAAK,2BAA2B,EAEhC,KAAK,kBAAkB,EAMxB,MAAM,cAAc,CAAC;AAEtB,OAAO,EACL,KAAK,eAAe,EAGrB,MAAM,yBAAyB,CAAC;AAEjC,MAAM,WAAW,sBAAsB;IACrC,UAAU,EAAE;QACV,MAAM,EAAE,MAAM,CAAC;QACf,IAAI,EAAE,MAAM,CAAC;KACd,CAAC;IACF,QAAQ,EAAE,yBAAyB,EAAE,CAAC;IACtC,MAAM,CAAC,EAAE;QACP,MAAM,EAAE,MAAM,CAAC;QACf,QAAQ,EAAE,MAAM,CAAC;QACjB,IAAI,EAAE,KAAK,GAAG,KAAK,CAAC;KACrB,CAAC;CACH;AAwwBD,wBAAsB,OAAO,CAC3B,OAAO,EAAE,eAAe,EACxB,MAAM,EAAE;IACN;;OAEG;IACH,OAAO,CAAC,EAAE,YAAY,EAAE,CAAC;IACzB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAClC,gBAAgB,EAAE,kBAAkB,GAAG,sBAAsB,CAAC;IAC9D,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,2BAA2B,CAAC,CAAC;IAC9D,kBAAkB,CAAC,EAAE,SAAS,sBAAsB,EAAE,CAAC;CACxD;;;;GAoEF;AAED,MAAM,MAAM,UAAU,GAAG,UAAU,CAAC,OAAO,OAAO,CAAC,CAAC"}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import
|
|
2
|
-
import type { NaunceResponseAnalyzer, ResponseItem
|
|
3
|
-
|
|
1
|
+
import type { Node } from '@typescript/native/ast';
|
|
2
|
+
import type { FunctionWithBody, NaunceResponseAnalyzer, ResponseItem } from '@sdk-it/core';
|
|
3
|
+
import type { TypeDeriver } from '@sdk-it/core/deriver.js';
|
|
4
|
+
/** The response `returned`, a value the handler returns, sends when it is an `output` call, such as `output.json(body, 201)`. */
|
|
5
|
+
export declare function defaultResponseAnalyzer(handler: FunctionWithBody, deriver: TypeDeriver, returned: Node): ResponseItem[];
|
|
4
6
|
export declare const responseAnalyzer: NaunceResponseAnalyzer;
|
|
5
7
|
export default responseAnalyzer;
|
|
6
8
|
//# sourceMappingURL=response-analyzer.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"response-analyzer.d.ts","
|
|
1
|
+
{"version":3,"file":"response-analyzer.d.ts","sources":["../../src/lib/response-analyzer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAYnD,OAAO,KAAK,EACV,gBAAgB,EAChB,sBAAsB,EACtB,YAAY,EACb,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAS3D,iIAAiI;AACjI,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,gBAAgB,EACzB,OAAO,EAAE,WAAW,EACpB,QAAQ,EAAE,IAAI,GACb,YAAY,EAAE,CAmChB;AAED,eAAO,MAAM,gBAAgB,EAAE,sBAiC9B,CAAC;AAEF,eAAe,gBAAgB,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sdk-it/generic",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.47.0",
|
|
4
|
+
"repository": {
|
|
5
|
+
"type": "git",
|
|
6
|
+
"url": "https://github.com/JanuaryLabs/sdk-it",
|
|
7
|
+
"directory": "packages/generic"
|
|
8
|
+
},
|
|
9
|
+
"bugs": {
|
|
10
|
+
"url": "https://github.com/JanuaryLabs/sdk-it/issues"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/JanuaryLabs/sdk-it/tree/main/packages/generic#readme",
|
|
4
13
|
"type": "module",
|
|
5
14
|
"main": "./dist/index.js",
|
|
6
15
|
"module": "./dist/index.js",
|
|
@@ -22,12 +31,16 @@
|
|
|
22
31
|
"!**/*.test.*"
|
|
23
32
|
],
|
|
24
33
|
"dependencies": {
|
|
25
|
-
"@
|
|
34
|
+
"@typescript/native": "npm:typescript@7.1.0-beta",
|
|
35
|
+
"@sdk-it/core": "0.47.0",
|
|
26
36
|
"stringcase": "^4.3.1",
|
|
27
|
-
"
|
|
28
|
-
"openapi3-ts": "^4.4.0"
|
|
37
|
+
"openapi3-ts": "^4.6.2"
|
|
29
38
|
},
|
|
30
|
-
"
|
|
31
|
-
"
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@sdk-it/hono": "0.47.0",
|
|
41
|
+
"@sdk-it/spec": "0.47.0",
|
|
42
|
+
"@sdk-it/testing": "*",
|
|
43
|
+
"@sdk-it/typescript": "0.47.0",
|
|
44
|
+
"@zukhruf/fs": "^0.8.22"
|
|
32
45
|
}
|
|
33
46
|
}
|