@nifrajs/cli 5.10.0 → 5.12.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 (66) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/cli.d.ts.map +1 -1
  3. package/dist/cli.js +10 -13
  4. package/dist/cli.js.map +1 -1
  5. package/dist/doctor.js +2 -2
  6. package/dist/doctor.js.map +1 -1
  7. package/dist/load.d.ts +2 -2
  8. package/dist/load.d.ts.map +1 -1
  9. package/dist/load.js +1 -1
  10. package/dist/load.js.map +1 -1
  11. package/dist/mcp-delegate.d.ts +17 -3
  12. package/dist/mcp-delegate.d.ts.map +1 -1
  13. package/dist/mcp-delegate.js +24 -9
  14. package/dist/mcp-delegate.js.map +1 -1
  15. package/dist/mcp-http.js +1 -1
  16. package/dist/mcp-relay.d.ts +37 -0
  17. package/dist/mcp-relay.d.ts.map +1 -0
  18. package/dist/mcp-relay.js +129 -0
  19. package/dist/mcp-relay.js.map +1 -0
  20. package/dist/mcp.d.ts.map +1 -1
  21. package/dist/mcp.js +55 -1
  22. package/dist/mcp.js.map +1 -1
  23. package/dist/migrate-layout.d.ts.map +1 -1
  24. package/dist/migrate-layout.js +45 -33
  25. package/dist/migrate-layout.js.map +1 -1
  26. package/dist/recipes/5.10.0.d.ts +3 -2
  27. package/dist/recipes/5.10.0.d.ts.map +1 -1
  28. package/dist/recipes/5.10.0.js +5 -4
  29. package/dist/recipes/5.10.0.js.map +1 -1
  30. package/dist/recipes/5.11.0.d.ts +10 -0
  31. package/dist/recipes/5.11.0.d.ts.map +1 -0
  32. package/dist/recipes/5.11.0.js +50 -0
  33. package/dist/recipes/5.11.0.js.map +1 -0
  34. package/dist/recipes/5.12.0.d.ts +9 -0
  35. package/dist/recipes/5.12.0.d.ts.map +1 -0
  36. package/dist/recipes/5.12.0.js +34 -0
  37. package/dist/recipes/5.12.0.js.map +1 -0
  38. package/dist/recipes/index.d.ts.map +1 -1
  39. package/dist/recipes/index.js +4 -0
  40. package/dist/recipes/index.js.map +1 -1
  41. package/dist/source-rewrites.d.ts +0 -5
  42. package/dist/source-rewrites.d.ts.map +1 -1
  43. package/dist/source-rewrites.js +232 -7
  44. package/dist/source-rewrites.js.map +1 -1
  45. package/dist/upgrade.d.ts +19 -1
  46. package/dist/upgrade.d.ts.map +1 -1
  47. package/dist/upgrade.js +55 -2
  48. package/dist/upgrade.js.map +1 -1
  49. package/docs/examples.json +38 -2
  50. package/docs/llms-full.txt +610 -221
  51. package/docs/types.json +362 -32
  52. package/package.json +11 -11
  53. package/src/cli.ts +10 -13
  54. package/src/doctor.ts +2 -2
  55. package/src/load.ts +6 -3
  56. package/src/mcp-delegate.ts +37 -11
  57. package/src/mcp-http.ts +1 -1
  58. package/src/mcp-relay.ts +155 -0
  59. package/src/mcp.ts +51 -1
  60. package/src/migrate-layout.ts +61 -29
  61. package/src/recipes/5.10.0.ts +5 -4
  62. package/src/recipes/5.11.0.ts +51 -0
  63. package/src/recipes/5.12.0.ts +35 -0
  64. package/src/recipes/index.ts +4 -0
  65. package/src/source-rewrites.ts +250 -8
  66. package/src/upgrade.ts +71 -3
@@ -0,0 +1,35 @@
1
+ import type { UpgradeRecipe } from "./index.ts"
2
+
3
+ /**
4
+ * Upgrade recipe for Nifra 5.12.
5
+ *
6
+ * This release has no import or dependency moves. Its notes cover the opt-in static response lane,
7
+ * schema validation and coercion changes, shared body limits, and WebSocket topic adapters.
8
+ */
9
+ export const recipe: UpgradeRecipe = {
10
+ version: "5.12.0",
11
+ pins: [
12
+ { match: "@nifrajs/", to: "5.12.0" },
13
+ { match: "create-nifra", to: "5.12.0" },
14
+ { match: "nifra", to: "5.12.0" },
15
+ ],
16
+ importMoves: [],
17
+ affects: [
18
+ "@nifrajs/core",
19
+ "@nifrajs/deno",
20
+ "@nifrajs/edge",
21
+ "@nifrajs/node",
22
+ "@nifrajs/schema",
23
+ "@nifrajs/web",
24
+ ],
25
+ notes: [
26
+ "`staticResponse()` registers fixed, bodyless GET/HEAD routes. Eligible Bun listeners serve them directly from Bun's route table; existing routes are unchanged unless they opt in.",
27
+ "Capability IDs now allow `_` separators, so grants work for IDs derived from snake_case `defineTool` names. Names with empty segments still need an explicit valid capability.",
28
+ "Server apps can provide a WebSocket `TopicAdapter`. The Node and Deno adapters report topic cleanup failures without skipping close callbacks.",
29
+ "Core exports its default request-body cap for the edge kit, and the core and edge servers now use the same default.",
30
+ "Schema validation treats inherited `Object.prototype` members as absent unless the input has that own key. Optional keys such as `constructor` no longer cause false validation failures; coercing schemas validate and return a prototype-free copy without mutating a plain-object input.",
31
+ "`compileSchema()` output works with strict TypeScript, `noUnusedLocals`, `noUnusedParameters`, and Node's built-in type stripping. It also rejects schema text containing a type annotation Node cannot strip.",
32
+ "The schema coercion fast path now covers scalar arrays and primitive literal unions. Ordinary loader contexts also use shallow copies while specialized contexts retain lazy request accessors.",
33
+ "Common routes that combine validated HTTP inputs and lifecycle hooks now use the compiled fast path, preserving their route behavior.",
34
+ ],
35
+ }
@@ -22,6 +22,8 @@ import { recipe as v5_7_0 } from "./5.7.0.ts"
22
22
  import { recipe as v5_8_0 } from "./5.8.0.ts"
23
23
  import { recipe as v5_9_0 } from "./5.9.0.ts"
24
24
  import { recipe as v5_10_0 } from "./5.10.0.ts"
25
+ import { recipe as v5_11_0 } from "./5.11.0.ts"
26
+ import { recipe as v5_12_0 } from "./5.12.0.ts"
25
27
 
26
28
  /** A pin rule: every dependency whose name starts with `match` is set to version `to`. */
27
29
  export interface PinRule {
@@ -103,6 +105,8 @@ const RECIPES: Record<string, UpgradeRecipe> = {
103
105
  [v5_8_0.version]: v5_8_0,
104
106
  [v5_9_0.version]: v5_9_0,
105
107
  [v5_10_0.version]: v5_10_0,
108
+ [v5_11_0.version]: v5_11_0,
109
+ [v5_12_0.version]: v5_12_0,
106
110
  }
107
111
 
108
112
  export function getRecipe(version: string): UpgradeRecipe | undefined {
@@ -3,6 +3,7 @@
3
3
  * syntax tree with the project's own TypeScript. A rewrite changes only a shape it recognizes whole
4
4
  * and lists every other site for the user to edit by hand; it never guesses.
5
5
  */
6
+ import { isSameOriginPath } from "@nifrajs/core/pattern"
6
7
  import type * as TS from "typescript"
7
8
  import { codeUnitOrder } from "./internal/code-unit-order.ts"
8
9
  import { scriptKindOf } from "./internal/script-kind.ts"
@@ -48,7 +49,7 @@ const WEB = "@nifrajs/web"
48
49
  const NODE = "@nifrajs/node"
49
50
  const DENO = "@nifrajs/deno"
50
51
  const CORE_STATIC = "@nifrajs/core/serve-static"
51
- const DAY = '"public, max-age=86400"'
52
+ const DAY = "public, max-age=86400"
52
53
  const YEAR = "public, max-age=31536000, immutable"
53
54
  const PUBLIC_DIR_KEYS = new Set(["dir", "hashedPrefix", "hashedFiles", "cache", "files"])
54
55
  const PUBLIC_DIR_FORM =
@@ -81,8 +82,35 @@ function parseSource(ts: typeof TS, file: string, text: string) {
81
82
  return { tree, lineOf }
82
83
  }
83
84
 
85
+ /** Named-import order: by the imported name, a `type` modifier aside. */
86
+ const specifierOrder = (a: string, b: string): number =>
87
+ codeUnitOrder(a.replace(/^type /, ""), b.replace(/^type /, ""))
88
+
89
+ /** The quote most of the file's string literals use, apart from module specifiers and JSX attributes
90
+ * (double-quoted in files whose code is not); `fallback` on a tie. */
91
+ function quoteOf(ts: typeof TS, tree: TS.SourceFile, fallback: "'" | '"'): "'" | '"' {
92
+ let single = 0
93
+ let double = 0
94
+ const visit = (node: TS.Node): void => {
95
+ if (
96
+ ts.isStringLiteral(node) &&
97
+ !ts.isJsxAttribute(node.parent) &&
98
+ !ts.isImportDeclaration(node.parent) &&
99
+ !ts.isExportDeclaration(node.parent)
100
+ ) {
101
+ if (node.getText(tree).startsWith("'")) single++
102
+ else double++
103
+ }
104
+ ts.forEachChild(node, visit)
105
+ }
106
+ visit(tree)
107
+ return single === double ? fallback : single > double ? "'" : '"'
108
+ }
109
+
84
110
  function rewriteServeStatic(ts: typeof TS, file: string, text: string): RewriteResult {
85
111
  const { tree, lineOf } = parseSource(ts, file, text)
112
+ const importQuote = /from\s*'/.test(text) ? "'" : '"'
113
+ const quote = quoteOf(ts, tree, importQuote)
86
114
  const edits: Edit[] = []
87
115
  const manual: ManualSite[] = []
88
116
  let count = 0
@@ -244,12 +272,12 @@ function rewriteServeStatic(ts: typeof TS, file: string, text: string): RewriteR
244
272
  }
245
273
  if (cacheControl === undefined) {
246
274
  if (coreDay) dayUsed = true
247
- cacheControl = coreDay ? "ONE_DAY" : DAY
275
+ cacheControl = coreDay ? "ONE_DAY" : `${quote}${DAY}${quote}`
248
276
  }
249
277
  const prefixValue = values.get("hashedPrefix")
250
278
  // A shorthand `hashedPrefix` is a binding of that name.
251
279
  const hashedPrefix = !values.has("hashedPrefix")
252
- ? '"/assets/"'
280
+ ? `${quote}/assets/${quote}`
253
281
  : prefixValue === undefined
254
282
  ? "hashedPrefix"
255
283
  : source(prefixValue)
@@ -258,7 +286,7 @@ function rewriteServeStatic(ts: typeof TS, file: string, text: string): RewriteR
258
286
  : `hashedFiles: (path) => path.startsWith(${hashedPrefix})`
259
287
  const fields = [
260
288
  field("dir"),
261
- 'prefix: "/"',
289
+ `prefix: ${quote}/${quote}`,
262
290
  // A miss is the app's: servePublicDir answered `undefined` for every path it could not serve.
263
291
  "fallthrough: true",
264
292
  hashed,
@@ -402,9 +430,6 @@ function rewriteServeStatic(ts: typeof TS, file: string, text: string): RewriteR
402
430
  : `type HashedFiles as ${hashedFilesLocal}`,
403
431
  )
404
432
  }
405
- const quote = /from\s*'/.test(text) ? "'" : '"'
406
- const specifierOrder = (a: string, b: string): number =>
407
- codeUnitOrder(a.replace(/^type /, ""), b.replace(/^type /, ""))
408
433
  const target = imports.get(runtimeModule)
409
434
  let added: string | undefined
410
435
  if (names.length > 0) {
@@ -416,7 +441,7 @@ function rewriteServeStatic(ts: typeof TS, file: string, text: string): RewriteR
416
441
  text: `{ ${all.join(", ")} }`,
417
442
  })
418
443
  } else {
419
- added = `import { ${names.toSorted(specifierOrder).join(", ")} } from ${quote}${runtimeModule}${quote}`
444
+ added = `import { ${names.toSorted(specifierOrder).join(", ")} } from ${importQuote}${runtimeModule}${importQuote}`
420
445
  }
421
446
  }
422
447
  // The new import goes where the first web import that loses a name was, or after the imports.
@@ -565,6 +590,222 @@ function rewritePprOption(ts: typeof TS, file: string, text: string): RewriteRes
565
590
  }
566
591
  }
567
592
 
593
+ const HREF_RAW = "rawHref"
594
+ // Where `redirect`, `useNavigate` and React's `Link` come from; each also exports `rawHref`.
595
+ const HREF_PROVIDER = /^@nifrajs\/web(?:-(?:react|preact|vue|svelte|solid)\/router)?$/
596
+ const LINK_PROVIDER = "@nifrajs/web-react/router"
597
+ const LINK_TAGS = ["Link", "NavLink", "Navigate"]
598
+ const STRING_BUILT =
599
+ "the destination is built from a string: build it with href({ to, params, search }), or wrap a path built elsewhere in rawHref(path)"
600
+
601
+ /**
602
+ * 5.10: `navigate()`, `redirect()` and React's `Link`, `NavLink` and `Navigate` take an `Href`. A
603
+ * string path written whole at one of those sites becomes `rawHref(path)`, which sends the same
604
+ * request the string did. A destination built from a template or a concatenation, an object passed to
605
+ * `navigate`, and a path `rawHref` refuses are listed, since each needs a route and its params.
606
+ */
607
+ function rewriteHrefNavigation(ts: typeof TS, file: string, text: string): RewriteResult {
608
+ const { tree } = parseSource(ts, file, text)
609
+ const source = (node: TS.Node): string => node.getText(tree)
610
+ const bound = new Map<
611
+ string,
612
+ { readonly exported: string; readonly from: string; readonly named: TS.NamedImports }
613
+ >()
614
+ for (const statement of tree.statements) {
615
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))
616
+ continue
617
+ const from = statement.moduleSpecifier.text
618
+ const clause = statement.importClause
619
+ const bindings = clause?.namedBindings
620
+ if (!HREF_PROVIDER.test(from) || clause?.isTypeOnly === true) continue
621
+ if (bindings === undefined || !ts.isNamedImports(bindings)) continue
622
+ for (const element of bindings.elements) {
623
+ if (element.isTypeOnly) continue
624
+ bound.set(element.name.text, {
625
+ exported: (element.propertyName ?? element.name).text,
626
+ from,
627
+ named: bindings,
628
+ })
629
+ }
630
+ }
631
+ const localsOf = (exported: string | readonly string[], from?: string): Set<string> =>
632
+ new Set(
633
+ [...bound]
634
+ .filter(
635
+ ([, entry]) =>
636
+ (typeof exported === "string"
637
+ ? entry.exported === exported
638
+ : exported.includes(entry.exported)) &&
639
+ (from === undefined || entry.from === from),
640
+ )
641
+ .map(([local]) => local),
642
+ )
643
+ const redirects = localsOf("redirect", "@nifrajs/web")
644
+ const useNavigates = localsOf("useNavigate")
645
+ const tags = localsOf(LINK_TAGS, LINK_PROVIDER)
646
+ if (redirects.size + useNavigates.size + tags.size === 0) return { text, count: 0, manual: [] }
647
+ const rawLocal = [...bound].find(([, entry]) => entry.exported === HREF_RAW)?.[0]
648
+ const importQuote = /from\s*'/.test(text) ? "'" : '"'
649
+ const quote = quoteOf(ts, tree, importQuote)
650
+
651
+ const navigates = new Set<string>()
652
+ const collect = (node: TS.Node): void => {
653
+ if (
654
+ ts.isVariableDeclaration(node) &&
655
+ ts.isIdentifier(node.name) &&
656
+ node.initializer !== undefined &&
657
+ ts.isCallExpression(node.initializer) &&
658
+ ts.isIdentifier(node.initializer.expression) &&
659
+ useNavigates.has(node.initializer.expression.text)
660
+ ) {
661
+ navigates.add(node.name.text)
662
+ }
663
+ ts.forEachChild(node, collect)
664
+ }
665
+ collect(tree)
666
+
667
+ const edits: Edit[] = []
668
+ const manualAt: { readonly pos: number; readonly reason: string }[] = []
669
+ // The import of the first name a rewritten site uses; `rawHref` is added to it.
670
+ let host: TS.NamedImports | undefined
671
+ let count = 0
672
+ const raw = rawLocal ?? HREF_RAW
673
+ // A `rawHref` of the file's own would be called in place of the export.
674
+ const taken = rawLocal === undefined && /\brawHref\b/.test(text)
675
+
676
+ const isStringy = (node: TS.Expression): boolean =>
677
+ ts.isStringLiteral(node) ||
678
+ ts.isNoSubstitutionTemplateLiteral(node) ||
679
+ ts.isTemplateExpression(node) ||
680
+ (ts.isBinaryExpression(node) &&
681
+ node.operatorToken.kind === ts.SyntaxKind.PlusToken &&
682
+ (isStringy(node.left) || isStringy(node.right)))
683
+ const list = (node: TS.Node, reason: string): void => {
684
+ manualAt.push({ pos: node.getStart(tree), reason })
685
+ }
686
+ // Rewrites one destination; `owner` names the import that brought the API in, and `attribute` is a
687
+ // JSX attribute's own string, which gains the braces of an expression.
688
+ const destination = (node: TS.Expression, owner: string, attribute = false): void => {
689
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
690
+ if (!isSameOriginPath(node.text)) {
691
+ list(
692
+ node,
693
+ `${JSON.stringify(node.text)} is not a same-origin path, which an Href must be: another site is a plain <a href>, or redirect(url, { external: true })`,
694
+ )
695
+ } else if (taken) {
696
+ list(node, `${HREF_RAW} is already a name in this file: import it under another name`)
697
+ } else {
698
+ const written =
699
+ attribute && ts.isStringLiteral(node) ? jsxAttributeValue(node) : source(node)
700
+ if (written === undefined) {
701
+ list(node, "wrap the path in rawHref(path), written as a JavaScript string")
702
+ return
703
+ }
704
+ edits.push({
705
+ start: node.getStart(tree),
706
+ end: node.end,
707
+ text: attribute ? `{${raw}(${written})}` : `${raw}(${written})`,
708
+ })
709
+ host ??= bound.get(owner)?.named
710
+ count++
711
+ }
712
+ } else if (isStringy(node)) list(node, STRING_BUILT)
713
+ }
714
+ // A JSX attribute string is not JavaScript: entities and escapes read differently.
715
+ const jsxAttributeValue = (node: TS.StringLiteral): string | undefined => {
716
+ const value = node.text
717
+ if (/[\\&\n]/.test(value) || value.includes(quote)) return undefined
718
+ return `${quote}${value}${quote}`
719
+ }
720
+
721
+ const visit = (node: TS.Node): void => {
722
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
723
+ const callee = node.expression.text
724
+ const first = node.arguments[0]
725
+ const options = node.arguments[1]
726
+ const isRedirect = redirects.has(callee)
727
+ if (first !== undefined && (isRedirect || navigates.has(callee))) {
728
+ const external =
729
+ isRedirect &&
730
+ options !== undefined &&
731
+ ts.isObjectLiteralExpression(options) &&
732
+ options.properties.some(
733
+ (p) => p.name !== undefined && propertyName(ts, p.name) === "external",
734
+ )
735
+ if (!external) {
736
+ if (ts.isObjectLiteralExpression(first)) {
737
+ list(
738
+ first,
739
+ "navigate({ to, search, replace }) is navigate(href({ to, search }), { replace }): the route and its params are the app's to name",
740
+ )
741
+ } else {
742
+ const owner = isRedirect
743
+ ? callee
744
+ : ([...bound].find(([, entry]) => entry.exported === "useNavigate")?.[0] ?? callee)
745
+ destination(first, owner)
746
+ }
747
+ }
748
+ }
749
+ } else if (
750
+ (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) &&
751
+ ts.isIdentifier(node.tagName) &&
752
+ tags.has(node.tagName.text)
753
+ ) {
754
+ for (const attribute of node.attributes.properties) {
755
+ if (!ts.isJsxAttribute(attribute) || attribute.name.getText(tree) !== "to") continue
756
+ const value = attribute.initializer
757
+ if (value === undefined) continue
758
+ if (ts.isStringLiteral(value)) destination(value, node.tagName.text, true)
759
+ else if (ts.isJsxExpression(value) && value.expression !== undefined)
760
+ destination(value.expression, node.tagName.text)
761
+ }
762
+ }
763
+ ts.forEachChild(node, visit)
764
+ }
765
+ visit(tree)
766
+
767
+ if (host !== undefined && rawLocal === undefined) {
768
+ const all = [...host.elements.map(source), HREF_RAW].toSorted(specifierOrder)
769
+ const multiline = source(host).includes("\n")
770
+ const first = host.elements[0]
771
+ const indent =
772
+ first === undefined
773
+ ? " "
774
+ : text.slice(text.lastIndexOf("\n", first.getStart(tree)) + 1, first.getStart(tree))
775
+ const close = text.slice(text.lastIndexOf("\n", host.end - 1) + 1, host.end - 1)
776
+ edits.push({
777
+ start: host.getStart(tree),
778
+ end: host.end,
779
+ text: multiline
780
+ ? `{\n${all.map((name) => `${indent}${name},`).join("\n")}\n${close}}`
781
+ : `{ ${all.join(", ")} }`,
782
+ })
783
+ }
784
+ const next = applyEdits(text, edits)
785
+ // The line a site has in the rewritten file, which is the one a reader opens.
786
+ const lineAfter = (pos: number): number => {
787
+ let at = pos
788
+ for (const edit of edits) if (edit.end <= pos) at += edit.text.length - (edit.end - edit.start)
789
+ return next.slice(0, at).split("\n").length
790
+ }
791
+ return {
792
+ text: next,
793
+ count,
794
+ manual: manualAt
795
+ .map(({ pos, reason }) => ({ line: lineAfter(pos), reason }))
796
+ .toSorted((a, b) => a.line - b.line),
797
+ }
798
+ }
799
+
800
+ const HREF_NAVIGATION: SourceRewrite = {
801
+ id: "href-navigation",
802
+ description:
803
+ "string paths given to navigate(), redirect() and React's Link, NavLink and Navigate → rawHref(path)",
804
+ mentions: (text) =>
805
+ /@nifrajs\/web/.test(text) && /\b(?:redirect|useNavigate|Link|NavLink|Navigate)\b/.test(text),
806
+ rewrite: rewriteHrefNavigation,
807
+ }
808
+
568
809
  const PPR_OPTION: SourceRewrite = {
569
810
  id: "ppr-option",
570
811
  description: "createWebApp({ experimental: { ppr } }) → createWebApp({ ppr })",
@@ -585,6 +826,7 @@ const SERVE_STATIC: SourceRewrite = {
585
826
  const REWRITES: Readonly<Record<string, SourceRewrite>> = {
586
827
  [SERVE_STATIC.id]: SERVE_STATIC,
587
828
  [PPR_OPTION.id]: PPR_OPTION,
829
+ [HREF_NAVIGATION.id]: HREF_NAVIGATION,
588
830
  }
589
831
 
590
832
  export function getSourceRewrite(id: string): SourceRewrite | undefined {
package/src/upgrade.ts CHANGED
@@ -78,13 +78,16 @@ import { getSourceRewrite } from "./source-rewrites.ts"
78
78
 
79
79
  export interface UpgradeOptions {
80
80
  /** Target version, e.g. "1.8.0". Required unless `list` is set. */
81
- readonly version?: string
81
+ readonly version?: string | undefined
82
82
  /** Apply the edits. Without it, the run is a dry-run that only prints the plan. */
83
83
  readonly write?: boolean
84
84
  /** Emit a machine-readable plan/result instead of the human report. */
85
85
  readonly json?: boolean
86
86
  /** Print the available target versions and return. */
87
87
  readonly list?: boolean
88
+ /** The version to upgrade from, in place of the lowest one the project's pins name. After the
89
+ * pins were bumped by hand, the recipes they skipped apply again only from this version. */
90
+ readonly from?: string | undefined
88
91
  /** After `--write`, run `nifra check` and fail the command if it fails, once the install matches
89
92
  * the target; until then, print the install command to run first. Default true. */
90
93
  readonly verify?: boolean
@@ -1888,11 +1891,76 @@ async function uncoveredContracts(cwd: string): Promise<string[]> {
1888
1891
  const uncoveredContractsNote = (routes: readonly string[]): string =>
1889
1892
  `note: contracts.lock.json records no request schema for ${routes.slice(0, 3).join(", ")}${routes.length > 3 ? ` and ${routes.length - 3} more` : ""}. Where this release reads a schema the installed one could not, \`nifra check\` reports it as newly covered: review it, then run \`nifra contracts snapshot\`.`
1890
1893
 
1894
+ const UPGRADE_SWITCHES: readonly string[] = [
1895
+ "--write",
1896
+ "--json",
1897
+ "--list",
1898
+ "--exact",
1899
+ "--allow-downgrade",
1900
+ "--allow-linked-skew",
1901
+ "--no-verify",
1902
+ "--no-hooks",
1903
+ ]
1904
+
1905
+ export interface UpgradeArgs {
1906
+ readonly version: string | undefined
1907
+ readonly from: string | undefined
1908
+ readonly write: boolean
1909
+ readonly json: boolean
1910
+ readonly list: boolean
1911
+ readonly exact: boolean
1912
+ readonly allowDowngrade: boolean
1913
+ readonly allowLinkedSkew: boolean
1914
+ readonly verify: boolean
1915
+ readonly hooks: boolean
1916
+ }
1917
+
1918
+ /** The arguments of `nifra upgrade`. Anything else is refused: an ignored `--from` would plan the
1919
+ * upgrade from the wrong version and still exit 0. */
1920
+ export function parseUpgradeArgs(args: readonly string[]): UpgradeArgs {
1921
+ const on = new Set<string>()
1922
+ let version: string | undefined
1923
+ let from: string | undefined
1924
+ for (let i = 0; i < args.length; i++) {
1925
+ const arg = args[i] ?? ""
1926
+ const equals = arg.startsWith("--") ? arg.indexOf("=") : -1
1927
+ const name = equals === -1 ? arg : arg.slice(0, equals)
1928
+ if (name === "--from") {
1929
+ const value = equals === -1 ? args[++i] : arg.slice(equals + 1)
1930
+ if (value === undefined || value === "" || (equals === -1 && value.startsWith("-")))
1931
+ throw new Error("[nifra] --from needs a version, e.g. --from 5.8.0")
1932
+ from = value
1933
+ } else if (UPGRADE_SWITCHES.includes(arg)) on.add(arg)
1934
+ else if (arg.startsWith("-")) {
1935
+ throw new Error(`[nifra] unknown option: ${arg} - see \`nifra help\``)
1936
+ } else if (version === undefined) version = arg
1937
+ else throw new Error(`[nifra] unexpected argument: ${arg} - see \`nifra help\``)
1938
+ }
1939
+ return {
1940
+ version,
1941
+ from,
1942
+ write: on.has("--write"),
1943
+ json: on.has("--json"),
1944
+ list: on.has("--list"),
1945
+ exact: on.has("--exact"),
1946
+ allowDowngrade: on.has("--allow-downgrade"),
1947
+ allowLinkedSkew: on.has("--allow-linked-skew"),
1948
+ verify: !on.has("--no-verify"),
1949
+ hooks: !on.has("--no-hooks"),
1950
+ }
1951
+ }
1952
+
1891
1953
  export async function runUpgrade(cwd: string, options: UpgradeOptions): Promise<boolean> {
1892
1954
  const cliVersion = options.cliVersion ?? listRecipeVersions().at(-1) ?? "0.0.0"
1893
1955
  const targets = upgradeTargets(cliVersion)
1956
+ if (options.from !== undefined && !RELEASE_VERSION.test(options.from)) {
1957
+ console.error(
1958
+ `[nifra] --from ${JSON.stringify(options.from)} is not a release version, e.g. ${cliVersion}`,
1959
+ )
1960
+ return false
1961
+ }
1894
1962
  if (options.list) {
1895
- const installed = installedGroupVersion(cwd)
1963
+ const installed = options.from ?? installedGroupVersion(cwd)
1896
1964
  const notes = Object.fromEntries(targets.map((v) => [v, getRecipe(v)?.notes ?? []]))
1897
1965
  const ahead = targets.filter((v) => installed === null || compareSemverSpec(v, installed) > 0)
1898
1966
  const unaffected = unaffectedReleases(ahead, groupSurface(cwd))
@@ -1952,7 +2020,7 @@ export async function runUpgrade(cwd: string, options: UpgradeOptions): Promise<
1952
2020
  const write = options.write === true
1953
2021
  const allowDowngrade = options.allowDowngrade === true
1954
2022
  const exact = options.exact === true
1955
- const from = installedGroupVersion(cwd)
2023
+ const from = options.from ?? installedGroupVersion(cwd)
1956
2024
  const recipe = chainRecipes(version, from)
1957
2025
 
1958
2026
  // Fail-closed on rollback: a dry pass writes nothing, so we can refuse before any package.json is touched.