@nifrajs/cli 5.2.0 → 5.3.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.
Files changed (95) hide show
  1. package/CHANGELOG.md +102 -0
  2. package/dist/assure-hydration.d.ts.map +1 -1
  3. package/dist/assure-hydration.js +6 -2
  4. package/dist/assure-hydration.js.map +1 -1
  5. package/dist/check-diagnostics.d.ts.map +1 -1
  6. package/dist/check-diagnostics.js +2 -0
  7. package/dist/check-diagnostics.js.map +1 -1
  8. package/dist/check-scan.d.ts +9 -3
  9. package/dist/check-scan.d.ts.map +1 -1
  10. package/dist/check-scan.js +61 -24
  11. package/dist/check-scan.js.map +1 -1
  12. package/dist/check.d.ts.map +1 -1
  13. package/dist/check.js +3 -3
  14. package/dist/check.js.map +1 -1
  15. package/dist/cli.d.ts.map +1 -1
  16. package/dist/cli.js +22 -14
  17. package/dist/cli.js.map +1 -1
  18. package/dist/db-tool.d.ts.map +1 -1
  19. package/dist/db-tool.js +2 -1
  20. package/dist/db-tool.js.map +1 -1
  21. package/dist/env-file.d.ts.map +1 -1
  22. package/dist/env-file.js +41 -8
  23. package/dist/env-file.js.map +1 -1
  24. package/dist/internal/source-facts.d.ts +20 -4
  25. package/dist/internal/source-facts.d.ts.map +1 -1
  26. package/dist/internal/source-facts.js +248 -32
  27. package/dist/internal/source-facts.js.map +1 -1
  28. package/dist/mcp-exec.d.ts +1 -0
  29. package/dist/mcp-exec.d.ts.map +1 -1
  30. package/dist/mcp-exec.js +11 -3
  31. package/dist/mcp-exec.js.map +1 -1
  32. package/dist/mcp-http.js +1 -1
  33. package/dist/mcp-io.d.ts +23 -3
  34. package/dist/mcp-io.d.ts.map +1 -1
  35. package/dist/mcp-io.js +59 -12
  36. package/dist/mcp-io.js.map +1 -1
  37. package/dist/mcp-isolate.d.ts.map +1 -1
  38. package/dist/mcp-isolate.js +2 -1
  39. package/dist/mcp-isolate.js.map +1 -1
  40. package/dist/migrate-layout.d.ts.map +1 -1
  41. package/dist/migrate-layout.js +1 -0
  42. package/dist/migrate-layout.js.map +1 -1
  43. package/dist/recipes/5.3.0.d.ts +11 -0
  44. package/dist/recipes/5.3.0.d.ts.map +1 -0
  45. package/dist/recipes/5.3.0.js +35 -0
  46. package/dist/recipes/5.3.0.js.map +1 -0
  47. package/dist/recipes/index.d.ts.map +1 -1
  48. package/dist/recipes/index.js +2 -0
  49. package/dist/recipes/index.js.map +1 -1
  50. package/dist/review.d.ts.map +1 -1
  51. package/dist/review.js +2 -0
  52. package/dist/review.js.map +1 -1
  53. package/dist/rules/codes.d.ts +2 -0
  54. package/dist/rules/codes.d.ts.map +1 -1
  55. package/dist/rules/codes.js +2 -0
  56. package/dist/rules/codes.js.map +1 -1
  57. package/dist/rules/explanations.d.ts.map +1 -1
  58. package/dist/rules/explanations.js +12 -2
  59. package/dist/rules/explanations.js.map +1 -1
  60. package/dist/rules/pages.d.ts +25 -1
  61. package/dist/rules/pages.d.ts.map +1 -1
  62. package/dist/rules/pages.js +149 -33
  63. package/dist/rules/pages.js.map +1 -1
  64. package/dist/rules/route-statement.d.ts +10 -0
  65. package/dist/rules/route-statement.d.ts.map +1 -0
  66. package/dist/rules/route-statement.js +150 -0
  67. package/dist/rules/route-statement.js.map +1 -0
  68. package/dist/upgrade.d.ts +43 -10
  69. package/dist/upgrade.d.ts.map +1 -1
  70. package/dist/upgrade.js +161 -45
  71. package/dist/upgrade.js.map +1 -1
  72. package/docs/llms-full.txt +96 -13
  73. package/docs/types.json +124 -28
  74. package/package.json +11 -11
  75. package/src/assure-hydration.ts +7 -1
  76. package/src/check-diagnostics.ts +2 -0
  77. package/src/check-scan.ts +64 -25
  78. package/src/check.ts +8 -3
  79. package/src/cli.ts +22 -14
  80. package/src/db-tool.ts +2 -0
  81. package/src/env-file.ts +42 -7
  82. package/src/internal/source-facts.ts +312 -39
  83. package/src/mcp-exec.ts +13 -2
  84. package/src/mcp-http.ts +1 -1
  85. package/src/mcp-io.ts +72 -12
  86. package/src/mcp-isolate.ts +2 -0
  87. package/src/migrate-layout.ts +1 -0
  88. package/src/recipes/5.3.0.ts +36 -0
  89. package/src/recipes/index.ts +2 -0
  90. package/src/review.ts +2 -0
  91. package/src/rules/codes.ts +2 -0
  92. package/src/rules/explanations.ts +12 -2
  93. package/src/rules/pages.ts +193 -33
  94. package/src/rules/route-statement.ts +170 -0
  95. package/src/upgrade.ts +202 -47
@@ -7,6 +7,18 @@ import type { TypeScriptApi } from "./typescript-import.ts"
7
7
  * Program: a rule asks for a file only after its lexical fast path found a candidate. That keeps
8
8
  * cold checks and projects without a TypeScript install on the existing conservative path.
9
9
  */
10
+ /** What {@link SourceFacts.untypedResponseRoutes} finds in one file. */
11
+ export interface UntypedResponseRoutes {
12
+ /** Whether `position` lies in one of those handlers. */
13
+ isUntypedAt(position: number): boolean
14
+ /**
15
+ * Positions of their returned raw `Response` values that the lexical pattern cannot see: a local
16
+ * `const` holding one, the context's `json()`/`text()` from a registered handler, or a call to an
17
+ * imported function `importReturnsResponse` answers for.
18
+ */
19
+ readonly indirectReturns: readonly number[]
20
+ }
21
+
10
22
  export interface SourceFacts {
11
23
  parse(file: string, content: string): TSApi.SourceFile | undefined
12
24
  isValueImportAt(
@@ -37,11 +49,19 @@ export interface SourceFacts {
37
49
  ): boolean | undefined
38
50
  isResponseSyntaxAt(source: TSApi.SourceFile, position: number): boolean | undefined
39
51
  /**
40
- * Whether `position` lies in a route handler: a function passed to `.get("/path", …)` and the
41
- * other method registrations, a function value of an `implement(contract, {...})` map, a local
42
- * function either one names, or a local function a handler returns a call to (one hop).
52
+ * The route handlers of `source` that return no plain value, so a raw `Response` they return leaves
53
+ * the typed client nothing to infer. A route handler is a function passed to `.get("/path", …)` and
54
+ * the other method registrations, a function value of an `implement(contract, {...})` map, a local
55
+ * function either one names, or a local function a handler returns a call to (one hop). A handler
56
+ * that also returns a plain value keeps the route typed (the client drops a bare `Response` from the
57
+ * union), and so does a registration that declares `{ response: … }`.
43
58
  */
44
- isRouteHandlerAt(source: TSApi.SourceFile, position: number): boolean
59
+ untypedResponseRoutes(
60
+ source: TSApi.SourceFile,
61
+ importReturnsResponse?: (specifier: string, name: string) => boolean,
62
+ ): UntypedResponseRoutes
63
+ /** Whether the function `source` exports as `name` returns a raw `Response` on some path. */
64
+ exportReturnsResponse(source: TSApi.SourceFile, name: string): boolean
45
65
  /** Whether the `import` keyword at `position` starts a runtime `import(specifier)` call (true) or a
46
66
  * type-position `import("…")` such as `typeof import("x")` (false); undefined when neither. */
47
67
  isDynamicImportAt(
@@ -117,11 +137,15 @@ type FunctionNode =
117
137
  | TSApi.FunctionDeclaration
118
138
  | TSApi.MethodDeclaration
119
139
 
120
- /** Every route handler of `source`, by the rules {@link SourceFacts.isRouteHandlerAt} states. */
121
- function routeHandlers(ts: TypeScriptApi, source: TSApi.SourceFile): ReadonlySet<TSApi.Node> {
122
- const isFunctionValue = (node: TSApi.Node): node is FunctionNode =>
123
- ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isMethodDeclaration(node)
124
- // Local functions by name; a name declared twice keeps both, which only ever adds findings.
140
+ function isFunctionValue(ts: TypeScriptApi, node: TSApi.Node): node is FunctionNode {
141
+ return ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isMethodDeclaration(node)
142
+ }
143
+
144
+ /** Local functions by name; a name declared twice keeps both, which only ever adds findings. */
145
+ function localFunctions(
146
+ ts: TypeScriptApi,
147
+ source: TSApi.SourceFile,
148
+ ): ReadonlyMap<string, readonly FunctionNode[]> {
125
149
  const locals = new Map<string, FunctionNode[]>()
126
150
  const declare = (name: string, fn: FunctionNode): void => {
127
151
  locals.set(name, [...(locals.get(name) ?? []), fn])
@@ -130,16 +154,158 @@ function routeHandlers(ts: TypeScriptApi, source: TSApi.SourceFile): ReadonlySet
130
154
  if (ts.isFunctionDeclaration(node) && node.name !== undefined) declare(node.name.text, node)
131
155
  else if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer) {
132
156
  const value = unwrapExpression(ts, node.initializer)
133
- if (isFunctionValue(value)) declare(node.name.text, value)
157
+ if (isFunctionValue(ts, value)) declare(node.name.text, value)
134
158
  }
135
159
  ts.forEachChild(node, collect)
136
160
  }
137
161
  collect(source)
162
+ return locals
163
+ }
164
+
165
+ /** The values `fn` itself returns: a concise arrow body, or each `return` outside nested functions. */
166
+ function returnedValues(ts: TypeScriptApi, fn: FunctionNode): readonly TSApi.Expression[] {
167
+ const body = fn.body
168
+ if (body === undefined) return []
169
+ if (!ts.isBlock(body)) return [body]
170
+ const values: TSApi.Expression[] = []
171
+ // The facade over TypeScript 7 guarantees `isFunctionLike`; a class method is function-like too.
172
+ const visit = (node: TSApi.Node): void => {
173
+ if (ts.isFunctionLike(node)) return
174
+ if (ts.isReturnStatement(node) && node.expression !== undefined) values.push(node.expression)
175
+ ts.forEachChild(node, visit)
176
+ }
177
+ ts.forEachChild(body, visit)
178
+ return values
179
+ }
180
+
181
+ /** Local variables of `fn` (outside nested functions) initialised with a raw `Response`. */
182
+ function responseBindings(ts: TypeScriptApi, fn: FunctionNode): ReadonlySet<string> {
183
+ const names = new Set<string>()
184
+ const visit = (node: TSApi.Node): void => {
185
+ if (ts.isFunctionLike(node)) return
186
+ if (
187
+ ts.isVariableDeclaration(node) &&
188
+ ts.isIdentifier(node.name) &&
189
+ node.initializer !== undefined &&
190
+ rawResponseExpression(ts, unwrapExpression(ts, node.initializer))
191
+ )
192
+ names.add(node.name.text)
193
+ ts.forEachChild(node, visit)
194
+ }
195
+ if (fn.body !== undefined) ts.forEachChild(fn.body, visit)
196
+ return names
197
+ }
198
+
199
+ /** Whether a value `fn` returns is a raw `Response`, written there or held in a local variable. */
200
+ function returnsRawResponse(ts: TypeScriptApi, fn: FunctionNode): boolean {
201
+ const bindings = responseBindings(ts, fn)
202
+ return returnedValues(ts, fn).some((value) => {
203
+ const unwrapped = unwrapExpression(ts, value)
204
+ return (
205
+ rawResponseExpression(ts, unwrapped) ||
206
+ (ts.isIdentifier(unwrapped) && bindings.has(unwrapped.text))
207
+ )
208
+ })
209
+ }
210
+
211
+ /** Value imports from relative modules, by local name: `import { json as reply } from "./http"`. */
212
+ function relativeImports(
213
+ ts: TypeScriptApi,
214
+ source: TSApi.SourceFile,
215
+ ): ReadonlyMap<string, { readonly specifier: string; readonly name: string }> {
216
+ const imports = new Map<string, { readonly specifier: string; readonly name: string }>()
217
+ for (const statement of source.statements) {
218
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))
219
+ continue
220
+ const specifier = statement.moduleSpecifier.text
221
+ const clause = statement.importClause
222
+ if (!specifier.startsWith(".") || clause === undefined || clause.isTypeOnly) continue
223
+ const named = clause.namedBindings
224
+ if (named === undefined || !ts.isNamedImports(named)) continue
225
+ for (const element of named.elements) {
226
+ if (element.isTypeOnly) continue
227
+ const name = (element.propertyName ?? element.name).text
228
+ imports.set(element.name.text, { specifier, name })
229
+ }
230
+ }
231
+ return imports
232
+ }
138
233
 
139
- const handlers = new Set<TSApi.Node>()
234
+ /** The local name `source` exports as `name`: an exported declaration, or `export { local as name }`. */
235
+ function exportedLocal(
236
+ ts: TypeScriptApi,
237
+ source: TSApi.SourceFile,
238
+ name: string,
239
+ ): string | undefined {
240
+ const exported = (modifiers: readonly TSApi.ModifierLike[] | undefined): boolean =>
241
+ modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) === true
242
+ for (const statement of source.statements) {
243
+ if (ts.isFunctionDeclaration(statement)) {
244
+ if (statement.name?.text === name && exported(statement.modifiers)) return name
245
+ } else if (ts.isVariableStatement(statement)) {
246
+ const declarations = statement.declarationList.declarations
247
+ if (
248
+ exported(statement.modifiers) &&
249
+ declarations.some((d) => ts.isIdentifier(d.name) && d.name.text === name)
250
+ )
251
+ return name
252
+ } else if (
253
+ ts.isExportDeclaration(statement) &&
254
+ statement.moduleSpecifier === undefined &&
255
+ !statement.isTypeOnly &&
256
+ statement.exportClause !== undefined &&
257
+ ts.isNamedExports(statement.exportClause)
258
+ ) {
259
+ for (const element of statement.exportClause.elements)
260
+ if (element.name.text === name && !element.isTypeOnly)
261
+ return (element.propertyName ?? element.name).text
262
+ }
263
+ }
264
+ return undefined
265
+ }
266
+
267
+ interface RouteHandlerSets {
268
+ /** Functions a route registration or an `implement()` map passes: their first parameter is the context. */
269
+ readonly direct: ReadonlySet<FunctionNode>
270
+ /** The direct handlers registered at least once without a `{ response: … }` declaration. */
271
+ readonly undeclared: ReadonlySet<FunctionNode>
272
+ /** Local functions a direct handler returns a call to (one hop), with the handlers that do. */
273
+ readonly returned: ReadonlyMap<FunctionNode, ReadonlySet<FunctionNode>>
274
+ }
275
+
276
+ /** What a handler's returned value is, as far as one file shows: a raw `Response` reached some way,
277
+ * a plain value the client types, or neither for sure. */
278
+ type ReturnKind = "raw" | "held" | "context" | "imported" | "helper" | "plain" | "unknown"
279
+ const RESPONSE_KINDS: ReadonlySet<ReturnKind> = new Set([
280
+ "raw",
281
+ "held",
282
+ "context",
283
+ "imported",
284
+ "helper",
285
+ ])
286
+ const INDIRECT_KINDS: ReadonlySet<ReturnKind> = new Set(["held", "context", "imported"])
287
+
288
+ /** An options object literal with a `response` property: the route's output is declared. */
289
+ function declaresResponse(ts: TypeScriptApi, argument: TSApi.Expression): boolean {
290
+ return (
291
+ ts.isObjectLiteralExpression(argument) &&
292
+ argument.properties.some(
293
+ (property) =>
294
+ (ts.isPropertyAssignment(property) || ts.isShorthandPropertyAssignment(property)) &&
295
+ ts.isIdentifier(property.name) &&
296
+ property.name.text === "response",
297
+ )
298
+ )
299
+ }
300
+
301
+ /** Every route handler of `source`, by the rules {@link SourceFacts.isRouteHandlerAt} states. */
302
+ function routeHandlers(ts: TypeScriptApi, source: TSApi.SourceFile): RouteHandlerSets {
303
+ const locals = localFunctions(ts, source)
304
+ const handlers = new Set<FunctionNode>()
305
+ const undeclared = new Set<FunctionNode>()
140
306
  const named = (expression: TSApi.Node): readonly FunctionNode[] => {
141
307
  if (ts.isIdentifier(expression)) return locals.get(expression.text) ?? []
142
- return isFunctionValue(expression) ? [expression] : []
308
+ return isFunctionValue(ts, expression) ? [expression] : []
143
309
  }
144
310
  const find = (node: TSApi.Node): void => {
145
311
  if (ts.isCallExpression(node)) {
@@ -152,20 +318,29 @@ function routeHandlers(ts: TypeScriptApi, source: TSApi.SourceFile): ReadonlySet
152
318
  first !== undefined &&
153
319
  (ts.isStringLiteralLike(first) || ts.isTemplateExpression(first))
154
320
  ) {
155
- for (const argument of rest)
156
- for (const fn of named(unwrapExpression(ts, argument))) handlers.add(fn)
321
+ const arguments_ = rest.map((argument) => unwrapExpression(ts, argument))
322
+ const declared = arguments_.some((argument) => declaresResponse(ts, argument))
323
+ for (const argument of arguments_)
324
+ for (const fn of named(argument)) {
325
+ handlers.add(fn)
326
+ if (!declared) undeclared.add(fn)
327
+ }
157
328
  }
158
329
  const implement =
159
330
  (ts.isIdentifier(callee) && callee.text === "implement") || method === "implement"
160
331
  const map =
161
332
  node.arguments[1] === undefined ? undefined : unwrapExpression(ts, node.arguments[1])
162
333
  if (implement && map !== undefined && ts.isObjectLiteralExpression(map)) {
334
+ const add = (fn: FunctionNode): void => {
335
+ handlers.add(fn)
336
+ undeclared.add(fn)
337
+ }
163
338
  for (const property of map.properties) {
164
- if (ts.isMethodDeclaration(property)) handlers.add(property)
339
+ if (ts.isMethodDeclaration(property)) add(property)
165
340
  else if (ts.isPropertyAssignment(property))
166
- for (const fn of named(unwrapExpression(ts, property.initializer))) handlers.add(fn)
341
+ for (const fn of named(unwrapExpression(ts, property.initializer))) add(fn)
167
342
  else if (ts.isShorthandPropertyAssignment(property))
168
- for (const fn of locals.get(property.name.text) ?? []) handlers.add(fn)
343
+ for (const fn of locals.get(property.name.text) ?? []) add(fn)
169
344
  }
170
345
  }
171
346
  }
@@ -174,22 +349,45 @@ function routeHandlers(ts: TypeScriptApi, source: TSApi.SourceFile): ReadonlySet
174
349
  find(source)
175
350
 
176
351
  // One hop: a local function a handler returns a call to answers for that handler.
177
- const returned = new Set<TSApi.Node>()
178
- const follow = (node: TSApi.Node): void => {
179
- const value =
180
- ts.isReturnStatement(node) && node.expression !== undefined
181
- ? node.expression
182
- : ts.isArrowFunction(node) && !ts.isBlock(node.body)
183
- ? node.body
184
- : undefined
185
- const call = value === undefined ? undefined : unwrapExpression(ts, value)
186
- if (call !== undefined && ts.isCallExpression(call))
187
- for (const fn of named(call.expression)) returned.add(fn)
188
- ts.forEachChild(node, follow)
352
+ const returned = new Map<FunctionNode, Set<FunctionNode>>()
353
+ for (const handler of handlers) {
354
+ const follow = (node: TSApi.Node): void => {
355
+ const value =
356
+ ts.isReturnStatement(node) && node.expression !== undefined
357
+ ? node.expression
358
+ : ts.isArrowFunction(node) && !ts.isBlock(node.body)
359
+ ? node.body
360
+ : undefined
361
+ const call = value === undefined ? undefined : unwrapExpression(ts, value)
362
+ if (call !== undefined && ts.isCallExpression(call))
363
+ for (const fn of named(call.expression)) {
364
+ const callers = returned.get(fn) ?? new Set<FunctionNode>()
365
+ callers.add(handler)
366
+ returned.set(fn, callers)
367
+ }
368
+ ts.forEachChild(node, follow)
369
+ }
370
+ follow(handler)
189
371
  }
190
- for (const handler of handlers) follow(handler)
191
- for (const fn of returned) handlers.add(fn)
192
- return handlers
372
+ return { direct: handlers, undeclared, returned }
373
+ }
374
+
375
+ /** `c.json(…)`/`c.text(…)` on the handler's own context parameter: both build a plain `Response`. */
376
+ function contextResponseCall(
377
+ ts: TypeScriptApi,
378
+ handler: FunctionNode,
379
+ value: TSApi.Expression,
380
+ ): boolean {
381
+ const context = handler.parameters[0]?.name
382
+ if (context === undefined || !ts.isIdentifier(context)) return false
383
+ if (!ts.isCallExpression(value) || !ts.isPropertyAccessExpression(value.expression)) return false
384
+ const target = value.expression.expression
385
+ const method = value.expression.name.text
386
+ return (
387
+ ts.isIdentifier(target) &&
388
+ target.text === context.text &&
389
+ (method === "json" || method === "text")
390
+ )
193
391
  }
194
392
 
195
393
  export interface SourceFactsOptions {
@@ -325,17 +523,91 @@ export function createSourceFacts(
325
523
  return false
326
524
  }
327
525
 
328
- const handlersBySource = new WeakMap<TSApi.SourceFile, ReadonlySet<TSApi.Node>>()
329
- const isRouteHandlerAt = (source: TSApi.SourceFile, position: number): boolean => {
526
+ const handlersBySource = new WeakMap<TSApi.SourceFile, RouteHandlerSets>()
527
+ const handlersOf = (source: TSApi.SourceFile): RouteHandlerSets => {
330
528
  let handlers = handlersBySource.get(source)
331
529
  if (handlers === undefined) {
332
530
  handlers = routeHandlers(ts, source)
333
531
  handlersBySource.set(source, handlers)
334
532
  }
335
- return (
336
- ancestorAt(ts, source, position, (node): node is TSApi.Node => handlers.has(node)) !==
337
- undefined
338
- )
533
+ return handlers
534
+ }
535
+ const untypedResponseRoutes = (
536
+ source: TSApi.SourceFile,
537
+ importReturnsResponse?: (specifier: string, name: string) => boolean,
538
+ ): UntypedResponseRoutes => {
539
+ const { direct, undeclared, returned } = handlersOf(source)
540
+ const locals = localFunctions(ts, source)
541
+ const imports = importReturnsResponse === undefined ? undefined : relativeImports(ts, source)
542
+ // A call this file cannot see into, or a conditional, may or may not be a Response: it neither
543
+ // marks a handler untyped nor keeps it typed.
544
+ const kindOf = (fn: FunctionNode, isDirect: boolean, value: TSApi.Expression): ReturnKind => {
545
+ if (rawResponseExpression(ts, value)) return "raw"
546
+ if (ts.isConditionalExpression(value) || ts.isNewExpression(value)) return "unknown"
547
+ if (!ts.isCallExpression(value)) return "plain"
548
+ if (isDirect && contextResponseCall(ts, fn, value)) return "context"
549
+ if (!ts.isIdentifier(value.expression)) return "unknown"
550
+ const imported = imports?.get(value.expression.text)
551
+ if (imported !== undefined)
552
+ return importReturnsResponse?.(imported.specifier, imported.name) === true
553
+ ? "imported"
554
+ : "unknown"
555
+ // From a direct handler, a call to a local helper answers as the helper does (one hop).
556
+ const helpers = isDirect
557
+ ? (locals.get(value.expression.text) ?? []).filter((helper) => returned.has(helper))
558
+ : []
559
+ if (helpers.length === 0) return "unknown"
560
+ const kinds = helpers.flatMap((helper) =>
561
+ returnKinds(helper, false).map((entry) => entry.kind),
562
+ )
563
+ if (kinds.some((kind) => kind === "plain")) return "plain"
564
+ return kinds.every((kind) => RESPONSE_KINDS.has(kind)) ? "helper" : "unknown"
565
+ }
566
+ const returnKinds = (fn: FunctionNode, isDirect: boolean) => {
567
+ const bindings = responseBindings(ts, fn)
568
+ return returnedValues(ts, fn).map((returnedValue) => {
569
+ const value = unwrapExpression(ts, returnedValue)
570
+ const kind: ReturnKind =
571
+ ts.isIdentifier(value) && bindings.has(value.text) ? "held" : kindOf(fn, isDirect, value)
572
+ return { value, kind }
573
+ })
574
+ }
575
+ // No plain return: a Response written anywhere in it (a `.then(() => new Response(…))` too)
576
+ // is what the route answers with.
577
+ const isUntyped = (fn: FunctionNode, isDirect: boolean): boolean =>
578
+ !returnKinds(fn, isDirect).some((entry) => entry.kind === "plain")
579
+
580
+ const untyped = new Map<FunctionNode, boolean>()
581
+ for (const handler of direct)
582
+ untyped.set(handler, undeclared.has(handler) && isUntyped(handler, true))
583
+ for (const [helper, callers] of returned) {
584
+ if (direct.has(helper)) continue
585
+ const reached = [...callers].some((caller) => untyped.get(caller) === true)
586
+ untyped.set(helper, reached && isUntyped(helper, false))
587
+ }
588
+ const indirectReturns: number[] = []
589
+ for (const [fn, untypedFn] of untyped) {
590
+ if (!untypedFn) continue
591
+ // A raw `new Response(` is the lexical pattern's to report, and a helper's at its own return.
592
+ for (const { value, kind } of returnKinds(fn, direct.has(fn)))
593
+ if (INDIRECT_KINDS.has(kind)) indirectReturns.push(value.getStart(source))
594
+ }
595
+ const byNode: ReadonlyMap<TSApi.Node, boolean> = untyped
596
+ return {
597
+ isUntypedAt: (position) => {
598
+ const handler = ancestorAt(ts, source, position, (node): node is TSApi.Node =>
599
+ byNode.has(node),
600
+ )
601
+ return handler !== undefined && byNode.get(handler) === true
602
+ },
603
+ indirectReturns,
604
+ }
605
+ }
606
+
607
+ const exportReturnsResponse = (source: TSApi.SourceFile, name: string): boolean => {
608
+ const local = exportedLocal(ts, source, name)
609
+ if (local === undefined) return false
610
+ return (localFunctions(ts, source).get(local) ?? []).some((fn) => returnsRawResponse(ts, fn))
339
611
  }
340
612
 
341
613
  const isDynamicImportAt = (
@@ -368,7 +640,8 @@ export function createSourceFacts(
368
640
  isRouteArgumentAt,
369
641
  isFunctionRouteCallAt,
370
642
  isResponseSyntaxAt,
371
- isRouteHandlerAt,
643
+ untypedResponseRoutes,
644
+ exportReturnsResponse,
372
645
  isDynamicImportAt,
373
646
  }
374
647
  }
package/src/mcp-exec.ts CHANGED
@@ -38,9 +38,12 @@ import {
38
38
  CHILD_TIMEOUT_MS,
39
39
  type EscalatingStop,
40
40
  escalatingStop,
41
+ forwardTerminalSignals,
41
42
  OWN_PROCESS_GROUP,
42
43
  readBoundedStream,
43
44
  signalProcessGroup,
45
+ stopGroupAndWait,
46
+ stopGroupOnExit,
44
47
  timeoutMessage,
45
48
  validateLocalPort,
46
49
  } from "./mcp-io.ts"
@@ -719,6 +722,7 @@ export async function spawnChild(
719
722
  stderr: "pipe",
720
723
  detached: OWN_PROCESS_GROUP,
721
724
  })
725
+ stopGroupOnExit(proc)
722
726
  const stopper = escalatingStop((name) => signalProcessGroup(proc, name))
723
727
  let killed = false
724
728
  const kill = (): void => {
@@ -846,6 +850,7 @@ export class WarmWorker {
846
850
  }
847
851
  >()
848
852
  private readonly stopper: EscalatingStop
853
+ private readonly releaseSignals: () => void
849
854
  private stdoutBuffer = ""
850
855
  private stdoutBufferBytes = 0
851
856
  private stderrBuffer = ""
@@ -865,14 +870,20 @@ export class WarmWorker {
865
870
  stdin: "pipe",
866
871
  stdout: "pipe",
867
872
  stderr: "pipe",
873
+ // Its own process group, stopped as a group: a process the app started dies with the worker.
874
+ detached: OWN_PROCESS_GROUP,
868
875
  }) as PipeSubprocess
869
- this.stopper = escalatingStop((name) => this.proc.kill(name))
876
+ this.stopper = escalatingStop((name) => signalProcessGroup(this.proc, name))
877
+ this.releaseSignals = forwardTerminalSignals(() => stopGroupAndWait(this.proc))
870
878
  liveWarmWorkers.add(this)
871
879
  void this.readStdout()
872
880
  void this.readStderr()
873
881
  void this.proc.exited.then((code) => {
874
882
  this.closed = true
875
- this.stopper.dispose()
883
+ this.releaseSignals()
884
+ // The worker is gone but the group may not be: whatever it started still gets SIGTERM, then
885
+ // SIGKILL after the grace period.
886
+ this.stopper.stop()
876
887
  liveWarmWorkers.delete(this)
877
888
  const err = new Error(
878
889
  `warm ${this.label} worker exited (${code})${this.stderrBuffer ? `:\n${this.stderrBuffer}` : ""}`,
package/src/mcp-http.ts CHANGED
@@ -29,7 +29,7 @@ export { docsTools } from "./mcp-docs-tools.ts"
29
29
  export type { TypeEntry } from "./types-search.ts"
30
30
 
31
31
  // Kept in lockstep with packages/cli/package.json by check:publish's version-consistency gate.
32
- const VERSION = "5.2.0"
32
+ const VERSION = "5.3.0"
33
33
  const SERVER_INFO = { name: "nifra-docs", version: VERSION }
34
34
  // Derive the GET/health tool list from the tools actually served, so the line can never drift from them.
35
35
  const docsHealth = (tools: McpTool[]): string =>
package/src/mcp-io.ts CHANGED
@@ -69,25 +69,85 @@ export function escalatingStop(
69
69
  }
70
70
  }
71
71
 
72
+ /**
73
+ * Once a child spawned with `detached: OWN_PROCESS_GROUP` exits, stop what is left of its group:
74
+ * SIGTERM, then SIGKILL after the grace period. A process the project's code started (a dev proxy, a
75
+ * watcher, an embedded database) outlives the child otherwise, and one that inherited the child's
76
+ * stdout or stderr keeps the caller's read, and the call, open until its deadline.
77
+ */
78
+ export function stopGroupOnExit(proc: {
79
+ readonly pid: number
80
+ readonly exited: Promise<unknown>
81
+ kill(signal?: NodeJS.Signals): void
82
+ }): void {
83
+ if (!OWN_PROCESS_GROUP) return
84
+ void proc.exited.then(() => escalatingStop((name) => signalProcessGroup(proc, name)).stop())
85
+ }
86
+
72
87
  const FORWARDED_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"] as const
73
88
 
89
+ /**
90
+ * SIGTERM to a child's group, then wait for the whole group to exit, SIGKILL whatever is left once
91
+ * `graceMs` passes. Resolves when the group is gone or killed.
92
+ */
93
+ export async function stopGroupAndWait(
94
+ proc: {
95
+ readonly pid: number
96
+ readonly exited: Promise<unknown>
97
+ kill(signal?: NodeJS.Signals): void
98
+ },
99
+ graceMs: number = KILL_GRACE_MS,
100
+ ): Promise<void> {
101
+ const deadline = Date.now() + graceMs
102
+ signalProcessGroup(proc, "SIGTERM")
103
+ await Promise.race([proc.exited, Bun.sleep(graceMs)])
104
+ // The leader is reaped once `exited` settles; a member that survived it keeps the group alive.
105
+ while (OWN_PROCESS_GROUP && Date.now() < deadline && groupAlive(proc.pid)) await Bun.sleep(25)
106
+ signalProcessGroup(proc, "SIGKILL")
107
+ // Reap the leader before this process takes the signal: a killed child it never waited for stays in
108
+ // the process table until its new parent gets to it.
109
+ await Promise.race([proc.exited, Bun.sleep(graceMs)])
110
+ }
111
+
112
+ function groupAlive(pid: number): boolean {
113
+ try {
114
+ process.kill(-pid, 0)
115
+ return true
116
+ } catch {
117
+ return false
118
+ }
119
+ }
120
+
121
+ // Every registered stop runs on one signal, together, and the signal is raised again only once all
122
+ // of them have finished: re-raising at once ended this process before a child that catches SIGTERM
123
+ // could be sent SIGKILL.
124
+ const terminalStops = new Set<{ readonly stop: () => void | Promise<void> }>()
125
+
126
+ function onTerminalSignal(signal: NodeJS.Signals): void {
127
+ const stops = [...terminalStops]
128
+ terminalStops.clear()
129
+ // A second Ctrl+C while the children stop ends this process at once.
130
+ for (const name of FORWARDED_SIGNALS) process.off(name, onTerminalSignal)
131
+ void Promise.allSettled(stops.map(async ({ stop }) => stop())).then(() =>
132
+ process.kill(process.pid, signal),
133
+ )
134
+ }
135
+
74
136
  /**
75
137
  * A child in its own group no longer gets the Ctrl+C the terminal sends its parent: on SIGINT,
76
- * SIGTERM or SIGHUP run `stop`, then let this process take the signal as it would have. Returns the
77
- * function that removes the listeners.
138
+ * SIGTERM or SIGHUP run `stop` (with every other registered one), wait for what it returns, then let
139
+ * this process take the signal as it would have. Returns the function that unregisters `stop`.
78
140
  */
79
- export function forwardTerminalSignals(stop: () => void): () => void {
141
+ export function forwardTerminalSignals(stop: () => void | Promise<void>): () => void {
80
142
  if (!OWN_PROCESS_GROUP) return () => {}
81
- const remove = (): void => {
82
- for (const name of FORWARDED_SIGNALS) process.off(name, forward)
83
- }
84
- const forward = (signal: NodeJS.Signals): void => {
85
- stop()
86
- remove()
87
- process.kill(process.pid, signal)
143
+ if (terminalStops.size === 0)
144
+ for (const name of FORWARDED_SIGNALS) process.on(name, onTerminalSignal)
145
+ const entry = { stop }
146
+ terminalStops.add(entry)
147
+ return () => {
148
+ if (!terminalStops.delete(entry) || terminalStops.size > 0) return
149
+ for (const name of FORWARDED_SIGNALS) process.off(name, onTerminalSignal)
88
150
  }
89
- for (const name of FORWARDED_SIGNALS) process.on(name, forward)
90
- return remove
91
151
  }
92
152
 
93
153
  /** Accept only a concrete TCP port. Port 0 (bind-any-free-port) is not a valid read target. */
@@ -19,6 +19,7 @@ import {
19
19
  readBoundedLines,
20
20
  readBoundedStream,
21
21
  signalProcessGroup,
22
+ stopGroupOnExit,
22
23
  } from "./mcp-io.ts"
23
24
  import type {
24
25
  AppSurface,
@@ -134,6 +135,7 @@ export async function askProjectChild(
134
135
  `cannot start a process in ${cwd}: ${error instanceof Error ? error.message : String(error)}`,
135
136
  )
136
137
  }
138
+ stopGroupOnExit(proc)
137
139
  let stopped: "timeout" | "cancel" | undefined
138
140
  const stop = (reason: "timeout" | "cancel"): void => {
139
141
  if (stopped !== undefined) return
@@ -1165,6 +1165,7 @@ function globCalls(ts: typeof TS, file: string, text: string): GlobCall[] {
1165
1165
  ts.isPropertyAccessExpression(node.expression) &&
1166
1166
  node.expression.name.text === "glob" &&
1167
1167
  ts.isMetaProperty(node.expression.expression) &&
1168
+ // nifra-expect NF-S002: keywordToken is a TypeScript SyntaxKind enum identifying import.meta, never a credential or request value.
1168
1169
  node.expression.expression.keywordToken === ts.SyntaxKind.ImportKeyword
1169
1170
  ) {
1170
1171
  const arg = node.arguments[0]
@@ -0,0 +1,36 @@
1
+ import type { UpgradeRecipe } from "./index.ts"
2
+
3
+ /**
4
+ * Upgrade recipe for Nifra 5.3.
5
+ *
6
+ * No import or dependency moves. The typed client reads two route return shapes differently,
7
+ * `nifra check` and `nifra upgrade` report more, and a build, a GraphQL endpoint, a session store and
8
+ * a few constructors refuse inputs they used to take; each note says what changes and what keeps the
9
+ * old answer.
10
+ */
11
+ export const recipe: UpgradeRecipe = {
12
+ version: "5.3.0",
13
+ pins: [
14
+ { match: "@nifrajs/", to: "5.3.0" },
15
+ { match: "create-nifra", to: "5.3.0" },
16
+ { match: "nifra", to: "5.3.0" },
17
+ ],
18
+ importMoves: [],
19
+ notes: [
20
+ "A route answering `status(code, body)` with a code typed as plain `number` types the client's `data` as that body, where it was `unknown`; a cast that recovered the type can go. A plain return beside `status(200, body)` types the 200 arm as either body, where the two were intersected, so client code that read a field only one of them has must narrow first.",
21
+ "`nifra check` adds NF-C045 (warning): a route added to a server as a statement of its own (`app.get(...)` with its result unused) when that server is exported or read by `typeof`. The route is served, but the typed client never sees it. Chain the registration onto the server's declaration, or declare the routes on their own `server()` and `merge()` it; `// nifra-expect NF-C045: <reason>` above the statement keeps a route off the type on purpose.",
22
+ "`nifra check` adds NF-C044 (warning): a `createWebApp` call that passes a `clientEntry` and no `copyChunks` in an app with copy tables (`@nifrajs/i18n/copy`), which fails in production on the first page that renders copy. Pass the `copyChunks` the generated server manifest exports; `// nifra-expect NF-C044: <reason>` on the call accepts a server that never serves those pages.",
23
+ "`nifra check`'s raw-`Response` advisory (NF-C007) also reads routes chained onto `createWebApp(...)`, a `Response` held in a local before it is returned, a handler's `c.json()`/`c.text()`, and a call to a function imported from a relative module that returns one, reported at each route that returns it. Return plain data to keep the route typed, or mark an intended `Response` with `// nifra-expect NF-C007: <reason>`.",
24
+ "`nifra upgrade` leaves a `peerDependencies` range alone when it already admits the target, and starts from the versions dependencies, devDependencies and overrides pin rather than from a peer floor, so a library workspace no longer replays older recipes. `nifra check` (NF-D002) and `nifra doctor` no longer count a peer floor as a second nifra version.",
25
+ "A build no longer copies hidden files from `public/` - any path segment starting with `.` other than `.well-known` - so `.env`, `.git/` or `.DS_Store` there is no longer deployed or served, matching development. A host marker a static deploy relies on, such as GitHub Pages' `.nojekyll`, now has to be written into the build output after the build.",
26
+ "`@nifrajs/graphql` refuses with a 400 before validation a document whose fragments, named and inline, expand past `maxFragmentExpansion` (default 20,000 selections summed over its selection sets), or whose fragment comparisons pass `maxFragmentComparisons` (default 100,000, which admits a binary tree of 255 fragments). Pass a higher limit to `respondGraphql`, `graphqlWebSocket` or `mountGraphql` if a legitimate client document is refused. A spread of an unknown fragment and a fragment cycle, which validation already refused, are refused before it too, with graphql-js's message and no `locations`.",
27
+ "A store-mode `@nifrajs/auth` session now writes a revocation marker under `<id>.revoked` on logout and rotation, and every load reads it beside the record. A custom `SessionStore` must accept that key like any other; one that validates keys against the session-id shape has to allow the suffix. `destroy(c, session)` also empties the session object it is passed, in both modes, so read anything you need from it before the call; committing it afterwards starts a new session holding only what was set since.",
28
+ "A raw request target holding a character a URL parser percent-encodes in a path (`\"`, `<`, `>`, `^`, `` ` ``, `{`, `}`, a space or non-ASCII) now routes as its encoded path on Node, Deno and Bun's native route table, as it already did on workerd and Bun's parsed URL: `GET /vault<tag>` reaches a route registered as `/vault%3Ctag%3E`, and `c.req.url` on Node and Deno carries the encoded form. Params are decoded as before.",
29
+ "`rangeResponse()` and `servePublicDir` ignore `Range` on a HEAD request (RFC 9110 section 14.2): HEAD answers 200 with the full `content-length`, where it used to answer 206 or 416.",
30
+ "Invalid numbers are refused where they used to disable a limit or strand work: `@nifrajs/edge` `server({ maxBodyBytes })` throws a `RangeError` for anything but a non-negative safe integer; `@nifrajs/jobs` `enqueue` throws for a `NaN` or infinite `delayMs` or `runAt`, `fixedBackoff`/`exponentialBackoff` throw for a non-finite or negative delay or a `jitter` outside [0, 1], and a backoff returning a non-finite delay dead-letters the job; `@nifrajs/mock` throws `UnsupportedMockSchemaError` for an `anyOf` whose every alternative contradicts the keywords beside it.",
31
+ "`RenderAdapter.renderToString` may return `undefined` for a render that suspended; the page is then streamed. A custom adapter keeps working unchanged; code that calls an adapter's `renderToString` itself has to handle `undefined`. Under `createCspPolicy`, a buffered page whose render writes a script of its own (a Solid `ErrorBoundary` that caught a server error) now carries a nonce and `cache-control: private, no-store`, like a deferred page.",
32
+ "A `@nifrajs/pi` turn whose provider refused Pi's sign-in or API key (an expired OAuth login, an incorrect key) now fails with code `PI_AUTH_REQUIRED` rather than `PI_MODEL_FAILED`, as `@nifrajs/acp` reports `ACP_AUTH_REQUIRED`. Code that matches `PI_MODEL_FAILED` to catch every failed model call has to match both.",
33
+ "A tool call through `executeTool` (`@nifrajs/core/tool-contract`) or an adapter built on it (the agent, MCP, WebMCP and HTTP tool adapters) whose executor throws or rejects keeps its idempotency key: a retry with the same key answers `idempotency_duplicate` rather than running the executor again, since the first attempt may have committed its effect. To retry a failure known to have committed nothing, call again with a new key.",
34
+ "`FileStorage` resolves the directory holding its root once and checks it before every operation: renaming an ancestor of the root now fails each operation with `StorageKeyError`, and a root reached through a symbolic link that is later repointed keeps the first tree until restart. Restart the process after moving a storage root.",
35
+ ],
36
+ }