upgrade-impact 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,179 @@
1
- # Temporary Holding Version
1
+ # upgrade-impact
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Find out exactly which lines of your code a dependency upgrade would break, before you upgrade.**
4
+
5
+ ```
6
+ $ npx upgrade-impact zod@4
7
+
8
+ zod 3.25.76 → 4.6.7
9
+ ✖ 3 new type error(s) in 1 file(s)
10
+
11
+ src/index.ts:5:27 TS2554 Expected 2-3 arguments, but got 1.
12
+ src/index.ts:7:31 TS2353 Object literal may only specify known properties, and 'invalid_type_error' does not exist in type '$ZodNumberParams'.
13
+ src/index.ts:10:16 TS2339 Property 'errors' does not exist on type 'ZodError<unknown>'.
14
+ ```
15
+
16
+ One command, no install, and your project is never touched.
17
+
18
+ ## What it does
19
+
20
+ A new major version of a library ships with a list of breaking changes. To know whether *your* code is affected, you'd normally read the changelog, search your code for every API it mentions, upgrade, and see what breaks. That's slow, easy to get wrong, and often turns out to be unnecessary, because many breaking changes don't touch the parts of a library you actually use.
21
+
22
+ `upgrade-impact` answers the question directly. Give it a package and the version you're considering, and it type-checks your real code against that version. It tells you either:
23
+
24
+ - **"✔ No new type errors in your code."** Every API you use still has the same shape, so the upgrade is safe as far as types can tell; or
25
+ - **the exact file, line and column of every place that breaks**, with TypeScript's explanation of why.
26
+
27
+ It does this without upgrading anything. The new version is downloaded into a temporary folder, checked, and deleted. Your `package.json`, lockfile and `node_modules` stay exactly as they were.
28
+
29
+ ## Quick start
30
+
31
+ In the folder that holds your project's `tsconfig.json`:
32
+
33
+ ```
34
+ npx upgrade-impact <package>@<version>
35
+ ```
36
+
37
+ Examples:
38
+
39
+ ```
40
+ npx upgrade-impact react-router@7
41
+ npx upgrade-impact zod@^4.1.0
42
+ npx upgrade-impact next@latest
43
+ npx upgrade-impact @tanstack/react-query@5
44
+ ```
45
+
46
+ There's nothing to install or configure: `npx` downloads the tool, runs it and leaves nothing behind.
47
+
48
+ ## When to use it
49
+
50
+ - **Before a major upgrade**, to see how much work it is: zero changes, a few lines, or a rewrite.
51
+ - **When reviewing a Renovate or Dependabot pull request**, to see what the bump breaks instead of guessing from the version number.
52
+ - **In CI**, to fail a build or flag a pull request when an upgrade would break the code (see below).
53
+ - **When choosing between versions**, by running it once per candidate version and comparing the results.
54
+
55
+ ## Options and exit codes
56
+
57
+ ```
58
+ npx upgrade-impact <package>@<version> [--json]
59
+ ```
60
+
61
+ | Option | What it does |
62
+ | --- | --- |
63
+ | `<package>@<version>` | The package and the version to check. The version can be exact (`4.1.2`), a range (`^4.1.0`, `~2.3`), a major (`4`) or a tag (`latest`, `next`). |
64
+ | `--json` | Print the result as JSON instead of text, for scripts and CI |
65
+ | `-h`, `--help` | Show usage |
66
+
67
+ | Exit code | Meaning |
68
+ | --- | --- |
69
+ | `0` | No new type errors: the upgrade doesn't break your code's types |
70
+ | `1` | The upgrade breaks your code; each problem is listed |
71
+ | `2` | The check couldn't run (bad arguments, no `tsconfig.json`, package not installed, download failed). The reason is printed. |
72
+
73
+ ## Using it in CI
74
+
75
+ Because the exit code is `1` when something breaks, a single step is enough to fail a build:
76
+
77
+ ```yaml
78
+ - run: npx upgrade-impact zod@4
79
+ ```
80
+
81
+ With `--json` you get structured output to post as a pull-request comment or feed into other tools:
82
+
83
+ ```json
84
+ {
85
+ "name": "zod",
86
+ "from": "3.25.76",
87
+ "to": "4.6.7",
88
+ "breakages": [
89
+ {
90
+ "file": "src/index.ts",
91
+ "line": 5,
92
+ "column": 27,
93
+ "code": 2554,
94
+ "message": "Expected 2-3 arguments, but got 1."
95
+ }
96
+ ]
97
+ }
98
+ ```
99
+
100
+ `from` is the version you have installed and `to` is the exact version the requested version resolved to. Each breakage gives the file (relative to where you ran the command, with forward slashes on every OS), the 1-based line and column, the TypeScript error number and its message.
101
+
102
+ ## What it works with
103
+
104
+ - **TypeScript projects** with a `tsconfig.json`.
105
+ - **Packages with or without bundled types.** If a package ships no type declarations, its matching `@types/*` package is used, for example `@types/lodash@4` for `lodash@4`.
106
+ - **Monorepos and workspaces.** The installed version is found in the nearest `node_modules`, including hoisted ones in parent folders.
107
+ - **Solution-style configs.** If `tsconfig.json` only lists `references` (as in Vite's templates), every referenced project is checked.
108
+ - **ESM and CommonJS**, including packages that use `exports` maps and subpath imports such as `zod/mini`.
109
+
110
+ ## How it works
111
+
112
+ 1. Downloads the requested version into a new temporary folder with `npm install --ignore-scripts`, using your normal npm settings, such as a private registry.
113
+ 2. Type-checks your project with the TypeScript compiler, exactly as it is today.
114
+ 3. Type-checks it again, this time resolving imports of that one package to the downloaded version.
115
+ 4. Reports only the errors that appear in the second check, so errors your project already has aren't blamed on the upgrade.
116
+ 5. Deletes the temporary folder.
117
+
118
+ ## Safety
119
+
120
+ - **Package code never runs.** Install scripts are disabled, and the check only reads type declarations.
121
+ - **Your project is never modified.** Nothing is written outside the temporary folder.
122
+ - **Arguments are strictly validated**, so a package argument can't be used to run shell commands.
123
+
124
+ ## What it can't catch
125
+
126
+ `upgrade-impact` finds what the **types** reveal: removed or renamed exports, changed function signatures, removed options, and changed return types. Some breaking changes don't show up in types:
127
+
128
+ - **Behaviour changes with the same types**, such as a new default value, a different sort order, or an error thrown in a new situation. Still read the release notes and run your tests.
129
+ - **Plain JavaScript projects.** A `tsconfig.json` is required.
130
+ - **Outdated `@types/*` packages.** Community types sometimes lag behind the library they describe, so results for packages without bundled types are less precise.
131
+ - **Global types.** Types loaded through `"types"` in `tsconfig.json` or `/// <reference types>` are still checked against the installed version. Only `import` and `require` are pointed at the new version.
132
+ - **TypeScript 7-only settings.** Checks use TypeScript 6. A `tsconfig.json` that uses options only TypeScript 7 understands is rejected with TypeScript's own error.
133
+
134
+ ## FAQ
135
+
136
+ **Does it change my `package.json`, lockfile or `node_modules`?**
137
+ No. The new version goes into a temporary folder that's deleted afterwards.
138
+
139
+ **Do I need to install it?**
140
+ No. `npx upgrade-impact …` is enough. You can also add it as a dev dependency if you want a fixed version in CI.
141
+
142
+ **Does it need internet access?**
143
+ Yes, to download the version you're checking from your npm registry.
144
+
145
+ **Is it safe to run on packages I don't trust?**
146
+ It never runs their code: install scripts are disabled and only type declarations are read. The download itself trusts your npm registry, the same as `npm install`.
147
+
148
+ **I pressed Ctrl+C and a folder was left behind.**
149
+ If the check is interrupted during the download, a folder named `upgrade-impact-*` may stay in your system temp folder. It's safe to delete.
150
+
151
+ ## Requirements
152
+
153
+ - Node.js 20 or newer, with npm on your `PATH`
154
+ - A TypeScript project with a `tsconfig.json`
155
+ - Network access to your npm registry
156
+
157
+ ## Changelog
158
+
159
+ **0.1.1**
160
+ - Fixed: projects whose `tsconfig.json` only lists `references` (such as Vite templates) were reported as safe without being checked. Every referenced project is now checked.
161
+ - Fixed: in monorepos, a package installed in a parent folder's `node_modules` was reported as "not installed".
162
+ - `--json` file paths now use forward slashes on every OS.
163
+ - Clearer error messages, and full stack traces for unexpected errors.
164
+
165
+ **0.1.0**
166
+ - First release.
167
+
168
+ ## Development
169
+
170
+ ```
171
+ npm install
172
+ npm test
173
+ ```
174
+
175
+ The tests download `zod` from the npm registry, so they need network access. `npm publish` runs the tests first.
176
+
177
+ ## License
178
+
179
+ MIT
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from "node:util";
3
+ import { UpgradeImpactError } from "../src/errors.js";
4
+ import { checkUpgrade } from "../src/index.js";
5
+ import { formatReport } from "../src/report.js";
6
+
7
+ const USAGE = "Usage: upgrade-impact <package>@<version> [--json]";
8
+ const EXIT_BREAKAGES_FOUND = 1;
9
+ const EXIT_ERROR = 2;
10
+
11
+ try {
12
+ const { values, positionals } = parseArgs({
13
+ allowPositionals: true,
14
+ options: { json: { type: "boolean" }, help: { type: "boolean", short: "h" } },
15
+ });
16
+ if (values.help) {
17
+ console.log(USAGE);
18
+ } else if (positionals.length !== 1) {
19
+ console.error(USAGE);
20
+ process.exitCode = EXIT_ERROR;
21
+ } else {
22
+ const result = checkUpgrade(positionals[0], process.cwd());
23
+ console.log(values.json ? JSON.stringify(result, null, 2) : formatReport(result));
24
+ if (result.breakages.length > 0) process.exitCode = EXIT_BREAKAGES_FOUND;
25
+ }
26
+ } catch (error) {
27
+ // parseArgs rejects unknown flags with ERR_PARSE_ARGS_*; that is a usage problem, not a bug.
28
+ const isUsageProblem = error instanceof UpgradeImpactError || error.code?.startsWith("ERR_PARSE_ARGS");
29
+ console.error(isUsageProblem ? `upgrade-impact: ${error.message}` : error);
30
+ process.exitCode = EXIT_ERROR;
31
+ }
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "upgrade-impact",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "See exactly which lines of your code a dependency upgrade would break, before you upgrade.",
5
+ "type": "module",
6
+ "bin": {
7
+ "upgrade-impact": "bin/upgrade-impact.js"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src"
12
+ ],
13
+ "engines": {
14
+ "node": ">=20"
15
+ },
16
+ "scripts": {
17
+ "test": "node --test test/*.test.js",
18
+ "prepublishOnly": "npm test"
19
+ },
20
+ "keywords": [
21
+ "upgrade",
22
+ "dependencies",
23
+ "breaking-changes",
24
+ "typescript",
25
+ "semver",
26
+ "cli"
27
+ ],
28
+ "license": "MIT",
29
+ "dependencies": {
30
+ "typescript": "^6.0.3"
31
+ }
32
+ }
package/src/analyze.js ADDED
@@ -0,0 +1,119 @@
1
+ import path from "node:path";
2
+ import ts from "typescript";
3
+ import { UpgradeImpactError } from "./errors.js";
4
+
5
+ const DECLARATION_EXTENSIONS = new Set([ts.Extension.Dts, ts.Extension.Dmts, ts.Extension.Dcts]);
6
+
7
+ const FORMAT_HOST = {
8
+ getCanonicalFileName: (fileName) => fileName,
9
+ getCurrentDirectory: ts.sys.getCurrentDirectory,
10
+ getNewLine: () => "\n",
11
+ };
12
+
13
+ /**
14
+ * Parsed configs to type-check: tsconfig.json itself, or, for a solution-style tsconfig.json
15
+ * that lists no files (as in Vite templates), every project it references.
16
+ */
17
+ export function readProjectConfigs(projectDir) {
18
+ const rootPath = path.join(projectDir, "tsconfig.json");
19
+ if (!ts.sys.fileExists(rootPath)) {
20
+ throw new UpgradeImpactError(`No tsconfig.json in ${projectDir}`);
21
+ }
22
+ const configs = collectConfigs(rootPath, new Set());
23
+ if (configs.length === 0) {
24
+ throw new UpgradeImpactError(`${rootPath} and the projects it references include no files`);
25
+ }
26
+ return configs;
27
+ }
28
+
29
+ function collectConfigs(configPath, visitedPaths) {
30
+ if (visitedPaths.has(configPath)) return [];
31
+ visitedPaths.add(configPath);
32
+ const config = readConfig(configPath);
33
+ if (config.fileNames.length > 0) return [config];
34
+ return (config.projectReferences ?? []).flatMap((reference) =>
35
+ collectConfigs(ts.resolveProjectReferencePath(reference), visitedPaths),
36
+ );
37
+ }
38
+
39
+ function readConfig(configPath) {
40
+ const host = {
41
+ ...ts.sys,
42
+ onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
43
+ throw new UpgradeImpactError(ts.formatDiagnostics([diagnostic], FORMAT_HOST));
44
+ },
45
+ };
46
+ const config = ts.getParsedCommandLineOfConfigFile(configPath, undefined, host);
47
+ if (config.errors.length > 0) {
48
+ throw new UpgradeImpactError(ts.formatDiagnostics(config.errors, FORMAT_HOST));
49
+ }
50
+ return config;
51
+ }
52
+
53
+ /** True when the package resolves to type declarations from installDir. */
54
+ export function hasTypes(packageName, installDir, options) {
55
+ const { resolvedModule } = ts.resolveModuleName(packageName, anchorFile(installDir), options, ts.sys);
56
+ return resolvedModule !== undefined && DECLARATION_EXTENSIONS.has(resolvedModule.extension);
57
+ }
58
+
59
+ /** Type errors in the project's own files that appear only when the package resolves from installDir. */
60
+ export function findBreakages(configs, projectDir, packageName, installDir) {
61
+ // Keyed so a file shared by two referenced projects is reported once.
62
+ const newErrors = new Map();
63
+ for (const config of configs) {
64
+ const existingErrors = new Set(projectErrors(config).map(errorKey));
65
+ for (const diagnostic of projectErrors(config, { packageName, installDir })) {
66
+ const key = errorKey(diagnostic);
67
+ if (!existingErrors.has(key)) newErrors.set(key, diagnostic);
68
+ }
69
+ }
70
+ return [...newErrors.values()].map((diagnostic) => toBreakage(diagnostic, projectDir));
71
+ }
72
+
73
+ function errorKey(diagnostic) {
74
+ return `${diagnostic.file.fileName}:${diagnostic.start}:${diagnostic.code}`;
75
+ }
76
+
77
+ // A file inside installDir, so module resolution searches installDir/node_modules.
78
+ function anchorFile(installDir) {
79
+ return path.join(installDir, "index.ts");
80
+ }
81
+
82
+ function projectErrors(config, redirect) {
83
+ const host = ts.createCompilerHost(config.options);
84
+ if (redirect) {
85
+ host.resolveModuleNameLiterals = (literals, containingFile, redirectedReference, options, containingSourceFile) =>
86
+ literals.map((literal) => {
87
+ const isTargetImport = literal.text === redirect.packageName || literal.text.startsWith(`${redirect.packageName}/`);
88
+ const resolveFrom = isTargetImport ? anchorFile(redirect.installDir) : containingFile;
89
+ const mode = ts.getModeForUsageLocation(containingSourceFile, literal, options);
90
+ return ts.resolveModuleName(literal.text, resolveFrom, options, host, undefined, redirectedReference, mode);
91
+ });
92
+ }
93
+ const program = ts.createProgram({
94
+ rootNames: config.fileNames,
95
+ options: config.options,
96
+ projectReferences: config.projectReferences,
97
+ host,
98
+ });
99
+ return ts
100
+ .getPreEmitDiagnostics(program)
101
+ .filter(
102
+ (diagnostic) =>
103
+ diagnostic.category === ts.DiagnosticCategory.Error &&
104
+ diagnostic.file !== undefined &&
105
+ !diagnostic.file.fileName.includes("/node_modules/"),
106
+ );
107
+ }
108
+
109
+ function toBreakage(diagnostic, projectDir) {
110
+ const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
111
+ return {
112
+ // Forward slashes on every OS, so --json output is the same on Windows and in Linux CI.
113
+ file: path.relative(projectDir, diagnostic.file.fileName).split(path.sep).join("/"),
114
+ line: line + 1,
115
+ column: character + 1,
116
+ code: diagnostic.code,
117
+ message: ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"),
118
+ };
119
+ }
package/src/errors.js ADDED
@@ -0,0 +1,2 @@
1
+ /** A problem the user can fix (bad arguments, missing tsconfig, failed install). Printed without a stack trace. */
2
+ export class UpgradeImpactError extends Error {}
package/src/index.js ADDED
@@ -0,0 +1,35 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { findBreakages, hasTypes, readProjectConfigs } from "./analyze.js";
5
+ import { UpgradeImpactError } from "./errors.js";
6
+ import { installPackages, parseSpec, readInstalledVersion, typesPackageName } from "./install.js";
7
+
8
+ /**
9
+ * Type-checks the project against another version of one dependency and returns the new errors.
10
+ * The target version is installed into a temporary folder; the project itself is never modified.
11
+ */
12
+ export function checkUpgrade(spec, projectDir) {
13
+ const { name, version } = parseSpec(spec);
14
+ const configs = readProjectConfigs(projectDir);
15
+ const from = readInstalledVersion(name, projectDir);
16
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), "upgrade-impact-"));
17
+ try {
18
+ installPackages([`${name}@${version}`], installDir);
19
+ const to = readInstalledVersion(name, installDir);
20
+ ensureTypes(name, to, installDir, configs[0].options);
21
+ return { name, from, to, breakages: findBreakages(configs, projectDir, name, installDir) };
22
+ } finally {
23
+ fs.rmSync(installDir, { recursive: true, force: true });
24
+ }
25
+ }
26
+
27
+ // Packages without bundled types are checked against the matching major of their @types package.
28
+ function ensureTypes(name, version, installDir, options) {
29
+ if (hasTypes(name, installDir, options)) return;
30
+ const typesSpec = `${typesPackageName(name)}@${version.split(".")[0]}`;
31
+ installPackages([typesSpec], installDir);
32
+ if (!hasTypes(name, installDir, options)) {
33
+ throw new UpgradeImpactError(`${name}@${version} has no type declarations, and installing ${typesSpec} did not provide any`);
34
+ }
35
+ }
package/src/install.js ADDED
@@ -0,0 +1,59 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { UpgradeImpactError } from "./errors.js";
5
+
6
+ // Only name and semver characters are allowed: on Windows the spec passes through a shell.
7
+ const SPEC_PATTERN = /^((?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*)@([\w.^~*-]+)$/i;
8
+
9
+ /** Splits "name@version" into its parts, rejecting anything that is not a plain package spec. */
10
+ export function parseSpec(spec) {
11
+ const match = SPEC_PATTERN.exec(spec);
12
+ if (!match) {
13
+ throw new UpgradeImpactError(`Expected <package>@<version>, for example zod@4 or @scope/pkg@^2.1.0. Got: ${spec}`);
14
+ }
15
+ return { name: match[1], version: match[2] };
16
+ }
17
+
18
+ /** Installs packages into installDir without running their install scripts. */
19
+ export function installPackages(specs, installDir) {
20
+ const args = ["install", ...specs, "--prefix", installDir, "--ignore-scripts", "--no-audit", "--no-fund", "--silent"];
21
+ const isWindows = process.platform === "win32";
22
+ // On Windows npm is a .cmd file that only starts through cmd.exe, which splits unquoted
23
+ // arguments at spaces and strips ^ from version ranges.
24
+ const shellSafeArgs = isWindows ? args.map((arg) => `"${arg}"`) : args;
25
+ const result = spawnSync("npm", shellSafeArgs, { encoding: "utf8", env: npmChildEnv(), shell: isWindows });
26
+ if (result.error) {
27
+ throw new UpgradeImpactError("Could not run npm. Check that Node.js and npm are installed and on PATH.", {
28
+ cause: result.error,
29
+ });
30
+ }
31
+ if (result.status !== 0) {
32
+ throw new UpgradeImpactError(`npm install ${specs.join(" ")} failed:\n${result.stderr.trim()}`);
33
+ }
34
+ }
35
+
36
+ // Under npx or npm run, npm exports its resolved config as lowercase npm_config_* variables. A nested
37
+ // install treats those as command-line flags (npm 11 rejects allow-scripts passed that way), so drop
38
+ // them and let the child read .npmrc files itself. User-set NPM_CONFIG_* variables are kept.
39
+ function npmChildEnv() {
40
+ return Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("npm_config_")));
41
+ }
42
+
43
+ /** Version of the package Node would load from baseDir, searching parent node_modules folders as Node does. */
44
+ export function readInstalledVersion(name, baseDir) {
45
+ for (let dir = path.resolve(baseDir); ; dir = path.dirname(dir)) {
46
+ const manifestPath = path.join(dir, "node_modules", name, "package.json");
47
+ if (fs.existsSync(manifestPath)) {
48
+ return JSON.parse(fs.readFileSync(manifestPath, "utf8")).version;
49
+ }
50
+ if (path.dirname(dir) === dir) {
51
+ throw new UpgradeImpactError(`${name} is not installed in ${baseDir} or any parent folder`);
52
+ }
53
+ }
54
+ }
55
+
56
+ /** "@scope/pkg" -> "@types/scope__pkg", "pkg" -> "@types/pkg" */
57
+ export function typesPackageName(name) {
58
+ return `@types/${name.replace(/^@/, "").replace("/", "__")}`;
59
+ }
package/src/report.js ADDED
@@ -0,0 +1,11 @@
1
+ export function formatReport({ name, from, to, breakages }) {
2
+ const header = `${name} ${from} → ${to}`;
3
+ if (breakages.length === 0) {
4
+ return `${header}\n✔ No new type errors in your code.`;
5
+ }
6
+ const fileCount = new Set(breakages.map((breakage) => breakage.file)).size;
7
+ const details = breakages.map(
8
+ ({ file, line, column, code, message }) => ` ${file}:${line}:${column} TS${code} ${message.replaceAll("\n", "\n ")}`,
9
+ );
10
+ return [header, `✖ ${breakages.length} new type error(s) in ${fileCount} file(s)`, "", ...details].join("\n");
11
+ }