@sumrco/cli 0.3.9 → 0.4.2

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.
Files changed (41) hide show
  1. package/ARTIFACT-MANIFEST.json +18 -0
  2. package/README.md +12 -0
  3. package/THIRD_PARTY_NOTICES.md +1119 -0
  4. package/ai/modules/kontract/resources/api-generation-standards.rf.md +18 -5
  5. package/ai/modules/kontract/resources/authoring/configuration.rf.md +568 -12
  6. package/ai/modules/kontract/resources/authoring/schema-reuse.rf.md +25 -4
  7. package/ai/modules/kontract/resources/authoring/scope-and-splitting.rf.md +8 -6
  8. package/ai/modules/kontract/resources/authoring/spec-layout.rf.md +4 -0
  9. package/ai/modules/kontract/resources/generated-output.rf.md +712 -44
  10. package/ai/modules/kontract/resources/nestjs-eslint.rf.md +153 -0
  11. package/ai/modules/kontract/resources/openapi-sdk-generator-research.rf.md +177 -0
  12. package/ai/modules/kontract/resources/overview.md +70 -8
  13. package/ai/modules/kontract/resources/performance.rf.md +11 -2
  14. package/ai/modules/kontract/sumr.module.yaml +15 -14
  15. package/ai/modules/mission/resources/flow-config.rf.md +2 -2
  16. package/ai/modules/mission/resources/overview.md +42 -35
  17. package/ai/modules/mission/resources/stage-closeout.rf.md +5 -5
  18. package/ai/modules/mission/resources/stage-delivery.rf.md +5 -5
  19. package/ai/modules/mission/resources/stage-intake.rf.md +2 -2
  20. package/ai/modules/mission/resources/stage-planning.rf.md +43 -4
  21. package/ai/modules/mission/resources/stage-pull-request.rf.md +2 -2
  22. package/ai/modules/mission/resources/stage-quality.rf.md +8 -8
  23. package/ai/modules/mission/resources/team-members/planner.tm.md +17 -5
  24. package/ai/modules/mission/resources/workflows/daily-triage.cmd.md +5 -1
  25. package/ai/modules/mission/resources/workflows/mission-cycle.cmd.md +7 -5
  26. package/ai/modules/mission/resources/workflows/planning-only.cmd.md +8 -3
  27. package/ai/modules/mission/sumr.module.yaml +20 -16
  28. package/ai/modules/playbook/resources/authoring/extraction.rf.md +28 -1
  29. package/ai/modules/playbook/resources/authoring/frontmatter.rf.md +7 -0
  30. package/ai/modules/playbook/resources/authoring/overview.md +33 -2
  31. package/ai/modules/playbook/resources/authoring/patterns.rf.md +21 -0
  32. package/ai/modules/playbook/resources/team-members/technical-writer.tm.md +5 -1
  33. package/ai/modules/playbook/sumr.module.yaml +13 -12
  34. package/ai/registry.json +3 -3
  35. package/bin/sumr +18 -3
  36. package/eslint/index.mjs +2 -0
  37. package/eslint/kontract/index.mjs +22 -0
  38. package/eslint/kontract/rules/typescript-nestjs/operation-contract.mjs +656 -0
  39. package/index.js +3060 -462
  40. package/package.json +26 -23
  41. package/sbom.cdx.json +5111 -0
@@ -0,0 +1,656 @@
1
+ import { readFileSync, statSync } from 'node:fs';
2
+ import { dirname, extname, isAbsolute, join, normalize, resolve } from 'node:path';
3
+
4
+ const STANDARD_ROUTES = new Map([
5
+ ['Delete', 'DELETE'],
6
+ ['Get', 'GET'],
7
+ ['Head', 'HEAD'],
8
+ ['Options', 'OPTIONS'],
9
+ ['Patch', 'PATCH'],
10
+ ['Post', 'POST'],
11
+ ['Put', 'PUT'],
12
+ ['Sse', 'GET'],
13
+ ]);
14
+ const BOUNDARY_DECORATORS = new Set(['Body', 'Cookie', 'HeaderParam', 'Headers', 'MultipartFiles', 'Param', 'Query', 'Res', 'UploadedFile', 'UploadedFiles']);
15
+ const UNSAFE_RESPONSE_DECORATOR = 'Res';
16
+ const BODY_DECORATOR = 'Body';
17
+ const COOKIE_DECORATOR = 'Cookie';
18
+ const HEADER_DECORATOR = 'Headers';
19
+ const HEADER_PARAMETER_DECORATOR = 'HeaderParam';
20
+ const PATH_PARAMETER_DECORATOR = 'Param';
21
+ const MULTIPART_FILE_DECORATORS = new Set(['MultipartFiles', 'UploadedFile', 'UploadedFiles']);
22
+ const HANDLER_RETURN_SYMBOL = 'symbol';
23
+ const HANDLER_RETURN_TYPE = 'type';
24
+ const PASSTHROUGH_RESPONSE_MODE = 'passthrough';
25
+ const VERSION_SELECTION_ABSENT = 'absent';
26
+ const VERSION_SELECTION_VALUES = 'versions';
27
+ const CONTRACT_MARKER = /\/\*\* @kontract-operation (\{[^\n]*\}) \*\/[\s\S]*?export const ([A-Za-z_$][\w$]*)\s*=/gu;
28
+
29
+ function decorators(node) {
30
+ return Array.isArray(node?.decorators) ? node.decorators : [];
31
+ }
32
+
33
+ function decoratorCall(decorator) {
34
+ const expression = decorator?.expression;
35
+ return expression?.type === 'CallExpression' ? expression : undefined;
36
+ }
37
+
38
+ function calleeName(call) {
39
+ const callee = call?.callee;
40
+ if (callee?.type === 'Identifier') return callee.name;
41
+ if (callee?.type === 'MemberExpression' && !callee.computed && callee.property.type === 'Identifier') return callee.property.name;
42
+ return undefined;
43
+ }
44
+
45
+ function literalString(node) {
46
+ if (node?.type === 'Literal' && typeof node.value === 'string') return node.value;
47
+ if (node?.type === 'TemplateLiteral' && node.expressions.length === 0) return node.quasis[0]?.value.cooked;
48
+ return undefined;
49
+ }
50
+
51
+ function literalStrings(node) {
52
+ if (node?.type === 'ArrayExpression') return node.elements.flatMap((element) => literalStrings(element));
53
+ const value = literalString(node);
54
+ return value === undefined ? [] : [value];
55
+ }
56
+
57
+ function objectPropertyValue(node, name) {
58
+ if (node?.type !== 'ObjectExpression') return undefined;
59
+ const property = node.properties.find(
60
+ (candidate) => candidate?.type === 'Property' && !candidate.computed && ((candidate.key.type === 'Identifier' && candidate.key.name === name) || (candidate.key.type === 'Literal' && candidate.key.value === name)),
61
+ );
62
+ return property?.type === 'Property' ? property.value : undefined;
63
+ }
64
+
65
+ function importsForProgram(program) {
66
+ const bindings = new Map();
67
+ for (const statement of program.body ?? []) {
68
+ if (statement.type !== 'ImportDeclaration' || typeof statement.source?.value !== 'string') continue;
69
+ for (const specifier of statement.specifiers ?? []) {
70
+ if (specifier.type === 'ImportSpecifier') {
71
+ bindings.set(specifier.local.name, {
72
+ imported: specifier.imported.type === 'Identifier' ? specifier.imported.name : String(specifier.imported.value),
73
+ source: statement.source.value,
74
+ });
75
+ } else if (specifier.type === 'ImportNamespaceSpecifier') bindings.set(specifier.local.name, { namespace: true, source: statement.source.value });
76
+ }
77
+ }
78
+ return bindings;
79
+ }
80
+
81
+ function resolveExpressionImport(node, bindings) {
82
+ if (node?.type === 'Identifier') {
83
+ const binding = bindings.get(node.name);
84
+ return binding && !binding.namespace ? binding : undefined;
85
+ }
86
+ if (node?.type === 'MemberExpression' && !node.computed && node.object.type === 'Identifier' && node.property.type === 'Identifier') {
87
+ const binding = bindings.get(node.object.name);
88
+ if (binding?.namespace) return { imported: node.property.name, source: binding.source };
89
+ }
90
+ return undefined;
91
+ }
92
+
93
+ function resolveTypeImport(node, bindings) {
94
+ let current = node;
95
+ while (current?.type === 'TSParenthesizedType') current = current.typeAnnotation;
96
+ if (current?.type === 'TSUnionType') {
97
+ const defined = current.types.filter((entry) => entry.type !== 'TSUndefinedKeyword');
98
+ return defined.length === 1 ? resolveTypeImport(defined[0], bindings) : undefined;
99
+ }
100
+ if (current?.type === 'TSArrayType') return resolveTypeImport(current.elementType, bindings);
101
+ if (current?.type === 'TSTypeReference') {
102
+ const typeName = current.typeName;
103
+ if (typeName.type === 'Identifier' && (typeName.name === 'Promise' || typeName.name === 'Observable')) {
104
+ const argument = (current.typeArguments ?? current.typeParameters)?.params?.[0];
105
+ return resolveTypeImport(argument, bindings);
106
+ }
107
+ if (typeName.type === 'Identifier') return bindings.get(typeName.name);
108
+ if (typeName.type === 'TSQualifiedName' && typeName.left.type === 'Identifier' && typeName.right.type === 'Identifier') {
109
+ const binding = bindings.get(typeName.left.name);
110
+ if (binding?.namespace) return { imported: typeName.right.name, source: binding.source };
111
+ }
112
+ }
113
+ return undefined;
114
+ }
115
+
116
+ function typeText(node, sourceCode) {
117
+ return node ? sourceCode.getText(node).replace(/\s+/gu, '') : undefined;
118
+ }
119
+
120
+ function unwrapParameter(parameter) {
121
+ const inner = parameter?.type === 'TSParameterProperty' ? parameter.parameter : parameter;
122
+ return inner?.type === 'AssignmentPattern' ? inner.left : inner;
123
+ }
124
+
125
+ function parameterType(parameter) {
126
+ return unwrapParameter(parameter)?.typeAnnotation?.typeAnnotation;
127
+ }
128
+
129
+ function keepsNestResponseHandling(boundary) {
130
+ const options = boundary?.arguments?.[0];
131
+ if (options?.type !== 'ObjectExpression') return false;
132
+ return options.properties.some(
133
+ (property) =>
134
+ property?.type === 'Property' &&
135
+ !property.computed &&
136
+ ((property.key.type === 'Identifier' && property.key.name === 'passthrough') || (property.key.type === 'Literal' && property.key.value === 'passthrough')) &&
137
+ property.value?.type === 'Literal' &&
138
+ property.value.value === true,
139
+ );
140
+ }
141
+
142
+ function aliasesFromOptions(options, cwd) {
143
+ const aliases = Array.isArray(options?.aliases) ? options.aliases : [];
144
+ return aliases.flatMap((entry) =>
145
+ entry && typeof entry.prefix === 'string' && typeof entry.path === 'string'
146
+ ? [
147
+ {
148
+ path: isAbsolute(entry.path) ? entry.path : resolve(cwd, entry.path),
149
+ prefix: entry.prefix.replace(/\/\*$/u, ''),
150
+ },
151
+ ]
152
+ : [],
153
+ );
154
+ }
155
+
156
+ function importBase(source, filename, aliases) {
157
+ if (source.startsWith('.')) return resolve(dirname(filename), source);
158
+ for (const alias of aliases) {
159
+ if (source === alias.prefix || source.startsWith(`${alias.prefix}/`)) return join(alias.path, source.slice(alias.prefix.length));
160
+ }
161
+ return undefined;
162
+ }
163
+
164
+ function isFile(path) {
165
+ try {
166
+ return statSync(path).isFile();
167
+ } catch {
168
+ return false;
169
+ }
170
+ }
171
+
172
+ function sourceText(file) {
173
+ try {
174
+ return readFileSync(file, 'utf8');
175
+ } catch {
176
+ return undefined;
177
+ }
178
+ }
179
+
180
+ function resolveSourceFile(source, filename, aliases) {
181
+ const base = importBase(source, filename, aliases);
182
+ if (!base) return undefined;
183
+ const candidates = ['.ts', '.mts', '.js', '.mjs'].includes(extname(base)) ? [base] : [`${base}.ts`, `${base}.mts`, `${base}.js`, `${base}.mjs`, join(base, 'index.ts'), join(base, 'index.mts'), join(base, 'index.js'), join(base, 'index.mjs')];
184
+ return candidates.find(isFile);
185
+ }
186
+
187
+ function reexportSources(source) {
188
+ return [...source.matchAll(/export\s+\*\s+from\s+['"]([^'"]+)['"]/gu)].map((match) => match[1]);
189
+ }
190
+
191
+ function reexportsFile(file, target, visited = new Set()) {
192
+ if (normalize(file) === normalize(target)) return true;
193
+ if (visited.has(file)) return false;
194
+ visited.add(file);
195
+ const source = sourceText(file);
196
+ if (source === undefined) return false;
197
+ return reexportSources(source).some((reexport) => {
198
+ const child = resolveSourceFile(reexport, file, []);
199
+ return child !== undefined && reexportsFile(child, target, visited);
200
+ });
201
+ }
202
+
203
+ function operationMetadata(file, exportName, visited = new Set()) {
204
+ if (!file || visited.has(file)) return undefined;
205
+ visited.add(file);
206
+ const source = sourceText(file);
207
+ if (source === undefined) return undefined;
208
+ CONTRACT_MARKER.lastIndex = 0;
209
+ for (const match of source.matchAll(CONTRACT_MARKER)) {
210
+ if (match[2] !== exportName) continue;
211
+ try {
212
+ return { file, metadata: JSON.parse(match[1]) };
213
+ } catch {
214
+ return undefined;
215
+ }
216
+ }
217
+ for (const reexport of reexportSources(source)) {
218
+ const child = resolveSourceFile(reexport, file, []);
219
+ const found = operationMetadata(child, exportName, visited);
220
+ if (found) return found;
221
+ }
222
+ return undefined;
223
+ }
224
+
225
+ function sameResolvedImport(actual, expected, controllerFile, operationFile, aliases) {
226
+ if (!actual || !expected) return false;
227
+ if (actual.imported !== expected.symbol) return false;
228
+ const actualFile = resolveSourceFile(actual.source, controllerFile, aliases);
229
+ const expectedFile = resolveSourceFile(expected.source, operationFile, []);
230
+ if (!actualFile && !expectedFile) return actual.source === expected.source;
231
+ return actualFile !== undefined && expectedFile !== undefined && reexportsFile(actualFile, expectedFile);
232
+ }
233
+
234
+ function pathSegments(value) {
235
+ return value
236
+ .split('/')
237
+ .filter(Boolean)
238
+ .map((segment) =>
239
+ segment
240
+ .replace(/^:([^?]+)\??$/u, '{$1}')
241
+ .replace(/^\*([^?]+)\??$/u, '{$1}')
242
+ .replace(/^\{([^}]+)\}$/u, '{$1}'),
243
+ );
244
+ }
245
+
246
+ function controllerCall(classNode) {
247
+ return decorators(classNode)
248
+ .map(decoratorCall)
249
+ .find((call) => calleeName(call) === 'Controller');
250
+ }
251
+
252
+ function combinedRoutePaths(classNode, routeCall) {
253
+ const controller = controllerCall(classNode);
254
+ const controllerArgument = controller?.arguments?.[0];
255
+ const bases = literalStrings(controllerArgument?.type === 'ObjectExpression' ? objectPropertyValue(controllerArgument, 'path') : controllerArgument);
256
+ const routes = literalStrings(routeCall?.arguments?.[0]);
257
+ const effectiveBases = bases.length > 0 ? bases : [''];
258
+ const effectiveRoutes = routes.length > 0 ? routes : [''];
259
+ return effectiveBases.flatMap((base) => effectiveRoutes.map((route) => `/${[...pathSegments(base), ...pathSegments(route)].join('/')}`));
260
+ }
261
+
262
+ function importedVersionNeutral(node, bindings) {
263
+ const imported = resolveExpressionImport(node, bindings);
264
+ return imported?.source === '@nestjs/common' && imported.imported === 'VERSION_NEUTRAL';
265
+ }
266
+
267
+ function versionSelection(node, bindings) {
268
+ if (!node) return { kind: VERSION_SELECTION_ABSENT, versions: [] };
269
+ if (importedVersionNeutral(node, bindings)) return { kind: 'neutral', versions: [] };
270
+ const versions = literalStrings(node);
271
+ return versions.length > 0 ? { kind: VERSION_SELECTION_VALUES, versions } : { kind: VERSION_SELECTION_ABSENT, versions: [] };
272
+ }
273
+
274
+ function controllerVersionSelection(classNode, bindings) {
275
+ const argument = controllerCall(classNode)?.arguments?.[0];
276
+ return versionSelection(objectPropertyValue(argument, 'version'), bindings);
277
+ }
278
+
279
+ function methodVersionSelection(node, bindings) {
280
+ const versionCall = decorators(node)
281
+ .map(decoratorCall)
282
+ .find((call) => calleeName(call) === 'Version');
283
+ return versionSelection(versionCall?.arguments?.[0], bindings);
284
+ }
285
+
286
+ function uriVersionedRoutePaths(classNode, node, paths, metadata, bindings) {
287
+ if (metadata.versioning && metadata.versioning !== 'uri') return paths;
288
+ const methodSelection = methodVersionSelection(node, bindings);
289
+ const controllerSelection = controllerVersionSelection(classNode, bindings);
290
+ const selection =
291
+ methodSelection.kind !== VERSION_SELECTION_ABSENT
292
+ ? methodSelection
293
+ : controllerSelection.kind !== VERSION_SELECTION_ABSENT
294
+ ? controllerSelection
295
+ : metadata.versioning === 'uri' && typeof metadata.version === 'string'
296
+ ? { kind: VERSION_SELECTION_VALUES, versions: [metadata.version] }
297
+ : { kind: VERSION_SELECTION_ABSENT, versions: [] };
298
+ if (selection.kind !== VERSION_SELECTION_VALUES) return paths;
299
+ return selection.versions.flatMap((version) => paths.map((path) => `/v${version}${path === '/' ? '' : path}`));
300
+ }
301
+
302
+ function owningClass(method, sourceCode) {
303
+ return sourceCode.getAncestors(method).find((ancestor) => ancestor.type === 'ClassDeclaration' || ancestor.type === 'ClassExpression');
304
+ }
305
+
306
+ function contractCalls(node, bindings) {
307
+ return decorators(node)
308
+ .map(decoratorCall)
309
+ .filter((call) => resolveExpressionImport(call.callee, bindings)?.imported === 'Operation');
310
+ }
311
+
312
+ function reportBodyParameter(context, typeNode, metadata, bindings, filename, operationFile, aliases) {
313
+ if (metadata.requestBody && sameResolvedImport(resolveTypeImport(typeNode, bindings), metadata.requestBody, filename, operationFile, aliases)) return;
314
+ context.report({ data: { operationId: metadata.operationId }, messageId: 'wrongRequest', node: typeNode });
315
+ }
316
+
317
+ function reportNamedParameter(context, kind, boundary, typeNode, metadata, expected, seen, sourceCode, bindings, filename, operationFile, aliases) {
318
+ const name = literalString(boundary.arguments?.[0]);
319
+ if (!name) {
320
+ context.report({ data: { decorator: kind, operationId: metadata.operationId }, messageId: 'namedBoundaryRequired', node: boundary });
321
+ return;
322
+ }
323
+ seen[kind].add(name);
324
+ const parameterContract = expected[kind].find((entry) => entry.name === name);
325
+ const matches =
326
+ parameterContract &&
327
+ (parameterContract.typeRef ? sameResolvedImport(resolveTypeImport(typeNode, bindings), parameterContract.typeRef, filename, operationFile, aliases) : typeText(typeNode, sourceCode) === parameterContract.type.replace(/\s+/gu, ''));
328
+ if (!matches) context.report({ data: { decorator: kind, name, operationId: metadata.operationId }, messageId: 'wrongParameter', node: typeNode });
329
+ }
330
+
331
+ function operationOwnedRequestPipe(boundary, bindings, operationImport) {
332
+ const pipe = boundary.arguments?.[0];
333
+ if (pipe?.type !== 'NewExpression') return false;
334
+ const pipeImport = resolveExpressionImport(pipe.callee, bindings);
335
+ const contract = pipe.arguments?.[0];
336
+ if (pipeImport?.source === 'nestjs-zod' && pipeImport.imported === 'ZodValidationPipe')
337
+ return (
338
+ contract?.type === 'MemberExpression' &&
339
+ !contract.computed &&
340
+ contract.property.type === 'Identifier' &&
341
+ contract.property.name === 'requestBodyDto' &&
342
+ resolveExpressionImport(contract.object, bindings)?.imported === operationImport.imported
343
+ );
344
+ if (pipeImport?.imported !== 'MultipartBodyPipe') return false;
345
+ const multipartOperation = resolveExpressionImport(contract, bindings);
346
+ return multipartOperation?.imported === operationImport.imported && multipartOperation.source === operationImport.source;
347
+ }
348
+
349
+ function operationOwnedParameterPipe(boundary, bindings, operationImport, parameterName) {
350
+ return (boundary.arguments ?? []).some((argument) => {
351
+ if (argument?.type !== 'CallExpression') return false;
352
+ const pipeImport = resolveExpressionImport(argument.callee, bindings);
353
+ if (pipeImport?.imported !== 'operationParameterPipe') return false;
354
+ const root = resolveExpressionImport(argument.arguments?.[0], bindings);
355
+ if (root?.imported !== operationImport.imported || root.source !== operationImport.source) return false;
356
+ const named = argument.arguments?.[1];
357
+ return named?.type === 'Literal' && named.value === parameterName;
358
+ });
359
+ }
360
+
361
+ function operationOwnedParameterBagPipe(boundary, bindings, operationImport, group) {
362
+ return (boundary.arguments ?? []).some((argument) => {
363
+ if (argument?.type !== 'NewExpression') return false;
364
+ const pipeImport = resolveExpressionImport(argument.callee, bindings);
365
+ if (pipeImport?.imported !== 'OperationParameterBagPipe') return false;
366
+ const root = resolveExpressionImport(argument.arguments?.[0], bindings);
367
+ return root?.imported === operationImport.imported && root.source === operationImport.source && literalString(argument.arguments?.[1]) === group;
368
+ });
369
+ }
370
+
371
+ function operationOwnedMultipartFilesPipe(boundary, bindings, operationImport) {
372
+ return (boundary.arguments ?? []).some((argument) => {
373
+ if (argument?.type !== 'NewExpression') return false;
374
+ const pipeImport = resolveExpressionImport(argument.callee, bindings);
375
+ if (pipeImport?.imported !== 'MultipartFilesPipe') return false;
376
+ const root = resolveExpressionImport(argument.arguments?.[0], bindings);
377
+ return root?.imported === operationImport.imported && root.source === operationImport.source;
378
+ });
379
+ }
380
+
381
+ function hasOperationOwnedMultipartInterceptor(node, bindings, operationImport) {
382
+ return decorators(node)
383
+ .map(decoratorCall)
384
+ .filter((call) => calleeName(call) === 'UseInterceptors')
385
+ .some((call) =>
386
+ (call.arguments ?? []).some((argument) => {
387
+ if (argument?.type !== 'NewExpression') return false;
388
+ const interceptorImport = resolveExpressionImport(argument.callee, bindings);
389
+ if (interceptorImport?.imported !== 'MultipartContentTypeInterceptor') return false;
390
+ const root = resolveExpressionImport(argument.arguments?.[0], bindings);
391
+ return root?.imported === operationImport.imported && root.source === operationImport.source;
392
+ }),
393
+ );
394
+ }
395
+
396
+ function reportBodyBoundary(context, boundary, typeNode, metadata, bindings, filename, operationFile, aliases, operationImport, seen) {
397
+ seen.Body.add('body');
398
+ if (!metadata.requestBody && operationOwnedRequestPipe(boundary, bindings, operationImport)) return;
399
+ reportBodyParameter(context, typeNode, metadata, bindings, filename, operationFile, aliases);
400
+ if (!operationOwnedRequestPipe(boundary, bindings, operationImport)) context.report({ data: { operationId: metadata.operationId }, messageId: 'wrongRequestPipe', node: boundary });
401
+ }
402
+
403
+ function reportMultipartBoundary(context, boundary, metadata, bindings, operationImport, seen) {
404
+ seen.MultipartFiles = true;
405
+ if (!metadata.multipart?.files?.length || !operationOwnedMultipartFilesPipe(boundary, bindings, operationImport)) context.report({ data: { operationId: metadata.operationId }, messageId: 'wrongMultipartFiles', node: boundary });
406
+ }
407
+
408
+ function parameterGroup(kind) {
409
+ if (kind === COOKIE_DECORATOR) return 'cookie';
410
+ if (kind === HEADER_DECORATOR || kind === HEADER_PARAMETER_DECORATOR) return 'header';
411
+ if (kind === PATH_PARAMETER_DECORATOR) return 'path';
412
+ return 'query';
413
+ }
414
+
415
+ function reportAggregateBoundary(context, boundary, kind, typeNode, metadata, bindings, expected, seen, operationImport, filename, operationFile, aliases) {
416
+ const aggregate = metadata.parameterBags?.[kind];
417
+ if (!aggregate) {
418
+ context.report({ data: { decorator: kind, operationId: metadata.operationId }, messageId: 'namedBoundaryRequired', node: boundary });
419
+ return;
420
+ }
421
+ if (!sameResolvedImport(resolveTypeImport(typeNode, bindings), aggregate, filename, operationFile, aliases)) context.report({ data: { decorator: kind, operationId: metadata.operationId }, messageId: 'wrongParameterBag', node: typeNode });
422
+ const group = parameterGroup(kind);
423
+ if (!operationOwnedParameterBagPipe(boundary, bindings, operationImport, group)) context.report({ data: { decorator: kind, group, operationId: metadata.operationId }, messageId: 'wrongParameterBagPipe', node: boundary });
424
+ for (const entry of expected[kind]) seen[kind].add(entry.name);
425
+ }
426
+
427
+ function reportNamedBoundary(context, boundary, decoratorKind, kind, typeNode, metadata, bindings, expected, seen, sourceCode, operationImport, filename, operationFile, aliases) {
428
+ if (MULTIPART_FILE_DECORATORS.has(decoratorKind)) {
429
+ reportMultipartBoundary(context, boundary, metadata, bindings, operationImport, seen);
430
+ return;
431
+ }
432
+ if (literalString(boundary.arguments?.[0]) === undefined) {
433
+ reportAggregateBoundary(context, boundary, kind, typeNode, metadata, bindings, expected, seen, operationImport, filename, operationFile, aliases);
434
+ return;
435
+ }
436
+ reportNamedParameter(context, kind, boundary, typeNode, metadata, expected, seen, sourceCode, bindings, filename, operationFile, aliases);
437
+ const parameterIndex = expected[kind].findIndex((entry) => entry.name === literalString(boundary.arguments?.[0]));
438
+ if (parameterIndex >= 0 && !operationOwnedParameterPipe(boundary, bindings, operationImport, expected[kind][parameterIndex].name))
439
+ context.report({ data: { decorator: kind, name: expected[kind][parameterIndex].name, operationId: metadata.operationId }, messageId: 'wrongParameterPipe', node: boundary });
440
+ }
441
+
442
+ function reportMissingBoundaries(context, node, metadata, bindings, expected, seen, operationImport) {
443
+ if ((metadata.requestBody || metadata.multipart) && !seen.Body.has('body')) context.report({ data: { operationId: metadata.operationId }, messageId: 'missingRequest', node });
444
+ if (metadata.multipart?.files?.length && !seen.MultipartFiles) context.report({ data: { operationId: metadata.operationId }, messageId: 'missingMultipartFiles', node });
445
+ if (metadata.multipart && !hasOperationOwnedMultipartInterceptor(node, bindings, operationImport)) context.report({ data: { operationId: metadata.operationId }, messageId: 'missingMultipartInterceptor', node });
446
+ for (const kind of ['Cookie', 'Headers', 'Param', 'Query']) {
447
+ for (const entry of expected[kind]) {
448
+ if (!seen[kind].has(entry.name)) context.report({ data: { decorator: kind, name: entry.name, operationId: metadata.operationId }, messageId: 'missingParameter', node });
449
+ }
450
+ }
451
+ }
452
+
453
+ function reportBoundaryParameters(context, node, metadata, bindings, sourceCode, filename, operationFile, aliases, operationImport) {
454
+ const expected = {
455
+ Body: metadata.requestBody ? [metadata.requestBody] : [],
456
+ Cookie: metadata.cookies ?? [],
457
+ Headers: metadata.headers ?? [],
458
+ Param: metadata.params ?? [],
459
+ Query: metadata.query ?? [],
460
+ };
461
+ const seen = { Body: new Set(), Cookie: new Set(), Headers: new Set(), MultipartFiles: false, Param: new Set(), Query: new Set() };
462
+
463
+ for (const parameter of node.value.params ?? []) {
464
+ const boundary = decorators(parameter)
465
+ .map(decoratorCall)
466
+ .find((call) => BOUNDARY_DECORATORS.has(calleeName(call)));
467
+ const decoratorKind = calleeName(boundary);
468
+ if (!decoratorKind) continue;
469
+ if (decoratorKind === UNSAFE_RESPONSE_DECORATOR) {
470
+ if (!keepsNestResponseHandling(boundary)) context.report({ data: { operationId: metadata.operationId }, messageId: 'unsafeResponse', node: boundary });
471
+ continue;
472
+ }
473
+ const kind = decoratorKind === HEADER_PARAMETER_DECORATOR ? HEADER_DECORATOR : decoratorKind;
474
+ const typeNode = parameterType(parameter);
475
+ if (!typeNode) {
476
+ context.report({ data: { decorator: kind }, messageId: 'missingBoundaryType', node: parameter });
477
+ continue;
478
+ }
479
+ if (kind === BODY_DECORATOR) reportBodyBoundary(context, boundary, typeNode, metadata, bindings, filename, operationFile, aliases, operationImport, seen);
480
+ else reportNamedBoundary(context, boundary, decoratorKind, kind, typeNode, metadata, bindings, expected, seen, sourceCode, operationImport, filename, operationFile, aliases);
481
+ }
482
+ reportMissingBoundaries(context, node, metadata, bindings, expected, seen, operationImport);
483
+ }
484
+
485
+ function reportResponse(context, node, metadata, bindings, filename, operationFile, aliases) {
486
+ const serializers = decorators(node)
487
+ .map(decoratorCall)
488
+ .filter((call) => calleeName(call) === 'ZodResponse' || calleeName(call) === 'ZodSerializerDto');
489
+ for (const serializer of serializers) context.report({ data: { operationId: metadata.operationId }, messageId: 'redundantSerializer', node: serializer });
490
+ if (metadata.responseMode === PASSTHROUGH_RESPONSE_MODE) return;
491
+ const returnType = node.value.returnType?.typeAnnotation;
492
+ if (!returnType) {
493
+ context.report({ data: { operationId: metadata.operationId }, messageId: 'missingReturn', node });
494
+ return;
495
+ }
496
+ const candidates = returnType.type === 'TSUnionType' ? returnType.types : [returnType];
497
+ const baseTypes = candidates.map((candidate) => {
498
+ if (candidate.type !== 'TSTypeReference' || candidate.typeName.type !== 'Identifier' || candidate.typeName.name !== 'Promise') return candidate;
499
+ return (candidate.typeArguments ?? candidate.typeParameters)?.params?.[0];
500
+ });
501
+ const matches =
502
+ baseTypes.length > 0 &&
503
+ baseTypes.every((candidate) => {
504
+ if (!candidate) return false;
505
+ if (metadata.handlerReturn?.kind === HANDLER_RETURN_SYMBOL) return sameResolvedImport(resolveTypeImport(candidate, bindings), metadata.handlerReturn.value, filename, operationFile, aliases);
506
+ return metadata.handlerReturn?.kind === HANDLER_RETURN_TYPE && typeText(candidate, context.sourceCode) === metadata.handlerReturn.value.replace(/\s+/gu, '');
507
+ });
508
+ if (!matches) context.report({ data: { operationId: metadata.operationId }, messageId: 'wrongResponse', node: returnType });
509
+ }
510
+
511
+ function reportOperationBoundary(context, node, metadata, bindings, sourceCode, filename, operationFile, aliases, operationImport) {
512
+ if (metadata.responseMode !== PASSTHROUGH_RESPONSE_MODE) reportBoundaryParameters(context, node, metadata, bindings, sourceCode, filename, operationFile, aliases, operationImport);
513
+ reportResponse(context, node, metadata, bindings, filename, operationFile, aliases);
514
+ }
515
+
516
+ function isControllerClass(node) {
517
+ return Boolean(
518
+ node &&
519
+ decorators(node)
520
+ .map(decoratorCall)
521
+ .some((call) => calleeName(call) === 'Controller'),
522
+ );
523
+ }
524
+
525
+ export const nestjsOperationContractRule = {
526
+ create(context) {
527
+ const sourceCode = context.sourceCode;
528
+ const filename = context.physicalFilename ?? context.filename;
529
+ const cwd = typeof context.cwd === 'string' ? context.cwd : process.cwd();
530
+ const aliases = aliasesFromOptions(context.options[0], cwd);
531
+ const exemptDecorators = new Set(context.options[0]?.exemptDecorators ?? []);
532
+ let bindings = new Map();
533
+
534
+ return {
535
+ MethodDefinition(node) {
536
+ const classNode = owningClass(node, sourceCode);
537
+ if (!isControllerClass(classNode)) return;
538
+
539
+ const route = decorators(node)
540
+ .map(decoratorCall)
541
+ .find((call) => STANDARD_ROUTES.has(calleeName(call)));
542
+ if (!route) {
543
+ const nonStandard = decorators(node)
544
+ .map(decoratorCall)
545
+ .find((call) => calleeName(call) === 'All');
546
+ const name = calleeName(nonStandard);
547
+ if (name && !exemptDecorators.has(name)) context.report({ data: { decorator: name }, messageId: 'exemptNonStandard', node: nonStandard });
548
+ return;
549
+ }
550
+
551
+ const contracts = contractCalls(node, bindings);
552
+ if (contracts.length !== 1) {
553
+ context.report({ data: { count: String(contracts.length) }, messageId: 'contractCount', node });
554
+ return;
555
+ }
556
+ const contract = contracts[0];
557
+ const operationImport = resolveExpressionImport(contract.arguments?.[0], bindings);
558
+ const decoratorImport = resolveExpressionImport(contract.callee, bindings);
559
+ if (!operationImport || !decoratorImport || operationImport.source !== decoratorImport.source) {
560
+ context.report({ messageId: 'wrongOperation', node: contract });
561
+ return;
562
+ }
563
+ const operationFile = resolveSourceFile(operationImport.source, filename, aliases);
564
+ const resolved = operationMetadata(operationFile, operationImport.imported);
565
+ if (!resolved) {
566
+ context.report({ data: { source: operationImport.source, symbol: operationImport.imported }, messageId: 'staleContract', node: contract });
567
+ return;
568
+ }
569
+
570
+ const metadata = resolved.metadata;
571
+ const actualMethod = STANDARD_ROUTES.get(calleeName(route));
572
+ const routePaths = uriVersionedRoutePaths(classNode, node, combinedRoutePaths(classNode, route), metadata, bindings);
573
+ const actualPath = routePaths[0] ?? '/';
574
+ if (actualMethod !== metadata.method || !routePaths.includes(metadata.path)) {
575
+ context.report({
576
+ data: {
577
+ actualMethod,
578
+ actualPath,
579
+ expectedMethod: metadata.method,
580
+ expectedPath: metadata.path,
581
+ operationId: metadata.operationId,
582
+ },
583
+ messageId: 'routeMismatch',
584
+ node: route,
585
+ });
586
+ }
587
+
588
+ const httpCode = decorators(node)
589
+ .map(decoratorCall)
590
+ .find((call) => calleeName(call) === 'HttpCode');
591
+ const explicitStatus = httpCode?.arguments?.[0]?.type === 'Literal' && typeof httpCode.arguments[0].value === 'number' ? httpCode.arguments[0].value : undefined;
592
+ if (explicitStatus !== undefined && metadata.status !== undefined && explicitStatus !== metadata.status)
593
+ context.report({ data: { actual: String(explicitStatus), expected: String(metadata.status), operationId: metadata.operationId }, messageId: 'statusConflict', node: httpCode });
594
+
595
+ reportOperationBoundary(context, node, metadata, bindings, sourceCode, filename, resolved.file, aliases, operationImport);
596
+ },
597
+ Program(node) {
598
+ bindings = importsForProgram(node);
599
+ },
600
+ };
601
+ },
602
+ meta: {
603
+ docs: {
604
+ description: 'Bind each NestJS JSON route to its exact generated Kontract operation.',
605
+ },
606
+ messages: {
607
+ contractCount: 'Standard NestJS route must have exactly one generated @Operation(OP); found {{count}}.',
608
+ exemptNonStandard: 'Non-standard route @{{decorator}} requires an explicit rule exemption.',
609
+ missingBoundaryType: '@{{decorator}} parameter must have an explicit generated-contract type.',
610
+ missingMultipartFiles: 'Multipart operation {{operationId}} requires its generated file boundary.',
611
+ missingMultipartInterceptor: 'Multipart operation {{operationId}} requires new MultipartContentTypeInterceptor(OP).',
612
+ missingParameter: 'Operation {{operationId}} requires @{{decorator}}({{name}}).',
613
+ missingRequest: 'Operation {{operationId}} requires its generated @Body request DTO.',
614
+ missingReturn: 'JSON operation {{operationId}} requires an explicit generated handler response type.',
615
+ namedBoundaryRequired: 'Operation {{operationId}} requires a named @{{decorator}} boundary because this generated metadata has no aggregate parameter contract.',
616
+ redundantSerializer: 'Operation {{operationId}} already installs its exact native Zod response binding through @Operation; remove the redundant response decorator.',
617
+ routeMismatch: 'Route {{actualMethod}} {{actualPath}} does not match generated operation {{operationId}} ({{expectedMethod}} {{expectedPath}}).',
618
+ staleContract: 'Cannot resolve generated operation metadata for {{symbol}} from {{source}}. Regenerate Kontract output or configure an import alias.',
619
+ statusConflict: '@HttpCode({{actual}}) conflicts with generated operation {{operationId}} status {{expected}}.',
620
+ unsafeResponse: 'Managed operation {{operationId}} cannot use library-mode @Res(); use @Res({ passthrough: true }) or declare x-response-mode: passthrough for an application-owned response transport.',
621
+ wrongMultipartFiles: 'Multipart files for operation {{operationId}} must use new MultipartFilesPipe(OP).',
622
+ wrongOperation: '@Operation must receive a generated operation imported from the same generated operations module.',
623
+ wrongParameter: '@{{decorator}}({{name}}) does not match operation {{operationId}}.',
624
+ wrongParameterBag: 'Aggregate @{{decorator}} type does not match the generated parameter bag owned by operation {{operationId}}.',
625
+ wrongParameterBagPipe: "Aggregate @{{decorator}} for operation {{operationId}} must use new OperationParameterBagPipe(OP, '{{group}}').",
626
+ wrongParameterPipe: "@{{decorator}}({{name}}) must include operationParameterPipe(OP, '<parameter name>') for operation {{operationId}}.",
627
+ wrongRequest: '@Body type does not match the generated request DTO owned by operation {{operationId}}.',
628
+ wrongRequestPipe: '@Body for operation {{operationId}} must use new ZodValidationPipe(OP.requestBodyDto) so runtime validation uses the exact operation-owned schema.',
629
+ wrongResponse: 'Handler return type does not match the generated response type owned by operation {{operationId}}.',
630
+ },
631
+ schema: [
632
+ {
633
+ additionalProperties: false,
634
+ properties: {
635
+ aliases: {
636
+ items: {
637
+ additionalProperties: false,
638
+ properties: {
639
+ path: { type: 'string' },
640
+ prefix: { type: 'string' },
641
+ },
642
+ required: ['prefix', 'path'],
643
+ type: 'object',
644
+ },
645
+ type: 'array',
646
+ },
647
+ exemptDecorators: { items: { type: 'string' }, type: 'array' },
648
+ },
649
+ type: 'object',
650
+ },
651
+ ],
652
+ type: 'problem',
653
+ },
654
+ };
655
+
656
+ export default nestjsOperationContractRule;