@virmator/deps 14.23.1 → 14.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -47,8 +47,5 @@ A default plugin for [virmator](https://www.npmjs.com/package/virmator).
47
47
 
48
48
  Force regeneration of all all dependencies by deleting all node_modules directories and package-lock.json and then running 'npm i'.
49
49
 
50
- Reads 'configs/deps-regen.config.ts' for intelligently working around min-release-age for explicitly allowed packages.
51
-
52
50
  - Examples
53
51
  - `virmator deps regen`
54
- - use a custom deps-regen allow list: `virmator deps regen --config ./configs/deps-regen.config.ts`
package/dist/deps.d.ts CHANGED
@@ -122,12 +122,9 @@ export declare const virmatorDepsPlugin: Readonly<Readonly<{
122
122
  };
123
123
  readonly regen: {
124
124
  readonly doc: {
125
- readonly sections: readonly ["\n Force regeneration of all all dependencies by deleting all\n node_modules directories and package-lock.json and then\n running 'npm i'.\n ", "\n Reads 'configs/deps-regen.config.ts' for intelligently working\n around min-release-age for explicitly allowed packages.\n "];
125
+ readonly sections: readonly ["\n Force regeneration of all all dependencies by deleting all\n node_modules directories and package-lock.json and then\n running 'npm i'.\n "];
126
126
  readonly examples: readonly [{
127
127
  readonly content: "virmator deps regen";
128
- }, {
129
- readonly title: "use a custom deps-regen allow list";
130
- readonly content: "virmator deps regen --config ./configs/deps-regen.config.ts";
131
128
  }];
132
129
  };
133
130
  };
@@ -256,12 +253,9 @@ export declare const virmatorDepsPlugin: Readonly<Readonly<{
256
253
  };
257
254
  readonly regen: {
258
255
  readonly doc: {
259
- readonly sections: readonly ["\n Force regeneration of all all dependencies by deleting all\n node_modules directories and package-lock.json and then\n running 'npm i'.\n ", "\n Reads 'configs/deps-regen.config.ts' for intelligently working\n around min-release-age for explicitly allowed packages.\n "];
256
+ readonly sections: readonly ["\n Force regeneration of all all dependencies by deleting all\n node_modules directories and package-lock.json and then\n running 'npm i'.\n "];
260
257
  readonly examples: readonly [{
261
258
  readonly content: "virmator deps regen";
262
- }, {
263
- readonly title: "use a custom deps-regen allow list";
264
- readonly content: "virmator deps regen --config ./configs/deps-regen.config.ts";
265
259
  }];
266
260
  };
267
261
  };
package/dist/deps.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { check } from '@augment-vir/assert';
2
- import { awaitedBlockingMap, getObjectTypedEntries, RuntimeEnv } from '@augment-vir/common';
3
- import { listAllDirectNpmDeps, toPosixPath } from '@augment-vir/node';
2
+ import { awaitedBlockingMap, RuntimeEnv } from '@augment-vir/common';
3
+ import { toPosixPath } from '@augment-vir/node';
4
4
  import { copyConfigFile, defineVirmatorPlugin, JsModuleType, NpmDepType, PackageType, VirmatorNoTraceError, withCompiledTsFile, withImportedTsFile, } from '@virmator/core';
5
5
  import mri from 'mri';
6
6
  import { rm } from 'node:fs/promises';
7
- import { dirname, join, matchesGlob, relative } from 'node:path';
8
- import { installFlagsByDepKey } from './install-flags.js';
9
- import { extractRegenConfigArg, getMinReleaseAgeDays, prepareRecentDepDowngrades, reinstallOriginalDeps, resolveRegenConfigPath, restoreOriginalPackageJsonVersions, } from './regen-recent-deps.js';
7
+ import { join, relative } from 'node:path';
8
+ import { listRegenNodeModulesDirs } from './regen-node-modules.js';
9
+ import { runArgBasedUpgrade } from './upgrade-deps.js';
10
10
  /** A virmator plugin for checking package TS dependencies. */
11
11
  export const virmatorDepsPlugin = defineVirmatorPlugin(import.meta.dirname, {
12
12
  name: 'Deps',
@@ -177,19 +177,11 @@ export const virmatorDepsPlugin = defineVirmatorPlugin(import.meta.dirname, {
177
177
  node_modules directories and package-lock.json and then
178
178
  running 'npm i'.
179
179
  `,
180
- `
181
- Reads 'configs/deps-regen.config.ts' for intelligently working
182
- around min-release-age for explicitly allowed packages.
183
- `,
184
180
  ],
185
181
  examples: [
186
182
  {
187
183
  content: 'virmator deps regen',
188
184
  },
189
- {
190
- title: 'use a custom deps-regen allow list',
191
- content: 'virmator deps regen --config ./configs/deps-regen.config.ts',
192
- },
193
185
  ],
194
186
  },
195
187
  },
@@ -247,72 +239,11 @@ export const virmatorDepsPlugin = defineVirmatorPlugin(import.meta.dirname, {
247
239
  const upgradeArgs = mri(filteredArgs);
248
240
  const depPattern = upgradeArgs._[0];
249
241
  if (depPattern) {
250
- const passthroughArgs = filteredArgs.toSpliced(filteredArgs.indexOf(depPattern), 1);
251
- /**
252
- * Split off an optional trailing '@<version>'. The first '@' in a scoped name like
253
- * '@augment-vir/*' is part of the name, so only a non-leading '@' separates name
254
- * from version.
255
- */
256
- const lastAtIndex = depPattern.lastIndexOf('@');
257
- const namePattern = lastAtIndex > 0 ? depPattern.slice(0, lastAtIndex) : depPattern;
258
- const versionSpecifier = lastAtIndex > 0 ? depPattern.slice(lastAtIndex + 1) : 'latest';
259
- const allDirectDeps = await listAllDirectNpmDeps(monoRepoRootPath);
260
- const matchedDepsByPackageAndKey = Object.entries(allDirectDeps).reduce((accum, [depName, usages,]) => {
261
- if (!matchesGlob(depName, namePattern)) {
262
- return accum;
263
- }
264
- return usages.reduce((innerAccumulator, usage) => {
265
- if (usage.isWorkspace ||
266
- installFlagsByDepKey[usage.dependencyKey] == undefined) {
267
- return innerAccumulator;
268
- }
269
- const packageDir = dirname(usage.requiredBy);
270
- const existingDepsByKey = innerAccumulator[packageDir] ?? {};
271
- const existingDeps = existingDepsByKey[usage.dependencyKey] ?? [];
272
- return {
273
- ...innerAccumulator,
274
- [packageDir]: {
275
- ...existingDepsByKey,
276
- [usage.dependencyKey]: [
277
- ...existingDeps,
278
- depName,
279
- ],
280
- },
281
- };
282
- }, accum);
283
- }, {});
284
- const matches = Object.entries(matchedDepsByPackageAndKey);
285
- if (!matches.length) {
286
- throw new VirmatorNoTraceError(`No direct dependencies matching '${depPattern}' found in any package.json.`);
287
- }
288
- await awaitedBlockingMap(matches, async ([packageDir, depsByKey,]) => {
289
- await awaitedBlockingMap(getObjectTypedEntries(depsByKey), async ([dependencyKey, depNames,]) => {
290
- const flag = installFlagsByDepKey[dependencyKey];
291
- /**
292
- * Defensive guard: upstream filter at 'matchedDepsByPackageAndKey'
293
- * already drops entries whose dep key maps to an undefined flag, so
294
- * this branch is unreachable in practice.
295
- */
296
- /* node:coverage ignore next 3 */
297
- if (flag == undefined) {
298
- return;
299
- }
300
- const command = [
301
- 'npm',
302
- 'i',
303
- flag,
304
- ...passthroughArgs,
305
- ...depNames.map((depName) => `${depName}@${versionSpecifier}`),
306
- ]
307
- .filter(check.isTruthy)
308
- .join(' ');
309
- await runShellCommand(command, {
310
- cwd: packageDir,
311
- }, {
312
- logPrefix: relative(monoRepoRootPath, packageDir) || '.',
313
- prefixCommandOnly: true,
314
- });
315
- });
242
+ await runArgBasedUpgrade({
243
+ depPattern,
244
+ filteredArgs,
245
+ monoRepoRootPath,
246
+ runShellCommand,
316
247
  });
317
248
  }
318
249
  else {
@@ -337,65 +268,29 @@ export const virmatorDepsPlugin = defineVirmatorPlugin(import.meta.dirname, {
337
268
  }
338
269
  }
339
270
  else if (usedCommands.deps?.subCommands.regen) {
340
- /** Strip '--config <path>' so it isn't forwarded to 'npm i'. */
341
- const { configValue, passthroughArgs } = extractRegenConfigArg(filteredArgs);
342
- /**
343
- * Direct deps that match the allow list but pin a too-recent version are temporarily
344
- * downgraded so the install below succeeds, then restored afterwards. When the repo has
345
- * no 'min-release-age', this is a no-op.
346
- */
347
- const recentDepViolators = await prepareRecentDepDowngrades({
271
+ const allNodeModulesDirectories = listRegenNodeModulesDirs({
348
272
  monoRepoRootPath,
349
- configPath: resolveRegenConfigPath({
350
- configValue,
351
- cwd,
352
- monoRepoRootPath,
353
- }),
354
- configIsExplicit: check.isTruthy(configValue),
355
- minReleaseAgeDays: await getMinReleaseAgeDays(monoRepoRootPath),
356
- log,
273
+ monoRepoPackages,
357
274
  });
358
- try {
359
- const allNodeModulesDirectories = [
360
- ...monoRepoPackages.map((monoPackage) => join(monoRepoRootPath, monoPackage.relativePath, 'node_modules')),
361
- join(monoRepoRootPath, 'node_modules'),
362
- ];
363
- await awaitedBlockingMap(allNodeModulesDirectories, async (path) => {
364
- log.faint(`Removing ${relative(monoRepoRootPath, path)}...`);
365
- await rm(path, {
366
- force: true,
367
- recursive: true,
368
- });
369
- });
370
- log.faint('Removing package-lock.json...');
371
- await rm(join(monoRepoRootPath, 'package-lock.json'), {
275
+ await awaitedBlockingMap(allNodeModulesDirectories, async (path) => {
276
+ log.faint(`Removing ${relative(monoRepoRootPath, path)}...`);
277
+ await rm(path, {
372
278
  force: true,
279
+ recursive: true,
373
280
  });
374
- const installCommand = [
375
- 'npm',
376
- 'i',
377
- ...passthroughArgs,
378
- ].join(' ');
379
- await runShellCommand(installCommand);
380
- /** Run twice because npm needs this sometimes. */
381
- await runShellCommand(installCommand);
382
- /** A no-op when there were no too-recent matches. */
383
- await reinstallOriginalDeps({
384
- violators: recentDepViolators,
385
- monoRepoRootPath,
386
- runVirmatorShellCommand: runShellCommand,
387
- });
388
- }
389
- finally {
390
- /**
391
- * Always restore the original `package.json` versions, even if regen failed
392
- * partway, so a failed run never leaves dependencies silently downgraded. A no-op
393
- * when there were no matches.
394
- */
395
- await restoreOriginalPackageJsonVersions({
396
- violators: recentDepViolators,
397
- });
398
- }
281
+ });
282
+ log.faint('Removing package-lock.json...');
283
+ await rm(join(monoRepoRootPath, 'package-lock.json'), {
284
+ force: true,
285
+ });
286
+ const installCommand = [
287
+ 'npm',
288
+ 'i',
289
+ ...filteredArgs,
290
+ ].join(' ');
291
+ await runShellCommand(installCommand);
292
+ /** Run twice because npm needs this sometimes. */
293
+ await runShellCommand(installCommand);
399
294
  }
400
295
  else {
401
296
  throw new VirmatorNoTraceError("deps sub-command needed: 'virmator deps check', 'virmator deps upgrade', or 'virmator deps regen'");
@@ -0,0 +1,10 @@
1
+ import { type MonoRepoPackage } from '@virmator/core';
2
+ /**
3
+ * All `node_modules` directories deleted before a regen install: one per mono-repo package plus the
4
+ * mono-repo root. For a single (non-mono) package, `monoRepoPackages` is empty so only the root is
5
+ * returned.
6
+ */
7
+ export declare function listRegenNodeModulesDirs({ monoRepoRootPath, monoRepoPackages, }: {
8
+ monoRepoRootPath: string;
9
+ monoRepoPackages: ReadonlyArray<Pick<MonoRepoPackage, 'relativePath'>>;
10
+ }): string[];
@@ -0,0 +1,12 @@
1
+ import { join } from 'node:path';
2
+ /**
3
+ * All `node_modules` directories deleted before a regen install: one per mono-repo package plus the
4
+ * mono-repo root. For a single (non-mono) package, `monoRepoPackages` is empty so only the root is
5
+ * returned.
6
+ */
7
+ export function listRegenNodeModulesDirs({ monoRepoRootPath, monoRepoPackages, }) {
8
+ return [
9
+ ...monoRepoPackages.map((monoPackage) => join(monoRepoRootPath, monoPackage.relativePath, 'node_modules')),
10
+ join(monoRepoRootPath, 'node_modules'),
11
+ ];
12
+ }
@@ -0,0 +1,59 @@
1
+ import { type NpmDeps, type PackageJsonDependencyKey } from '@augment-vir/node';
2
+ import { type ExtraRunShellCommandOptions } from '@virmator/core';
3
+ /** The matched, installable direct deps to upgrade, grouped by package directory and dep section. */
4
+ export type UpgradeMatches = Record<string, Partial<Record<PackageJsonDependencyKey, string[]>>>;
5
+ /**
6
+ * Whether a dependency name is a safe npm package name to interpolate (single-quoted) into a shell
7
+ * command. Restricting names read out of an (untrusted) `package.json` to this shape guarantees
8
+ * they cannot contain shell metacharacters or quotes.
9
+ */
10
+ export declare function isSafePackageName(depName: string): boolean;
11
+ /**
12
+ * The subset of a plugin's `runShellCommand` used to run upgrade installs. Loosely typed so the
13
+ * plugin-provided implementation is assignable.
14
+ */
15
+ export type RunUpgradeShellCommand = (command: string, options: {
16
+ cwd: string;
17
+ }, extraOptions: Partial<ExtraRunShellCommandOptions>) => Promise<unknown>;
18
+ /**
19
+ * Splits a `deps upgrade` pattern into its name pattern and version specifier. The first `@` in a
20
+ * scoped name like `@augment-vir/*` is part of the name, so only a non-leading `@` separates the
21
+ * name from the version. A missing version defaults to `latest`.
22
+ */
23
+ export declare function splitUpgradePattern(depPattern: string): {
24
+ namePattern: string;
25
+ versionSpecifier: string;
26
+ };
27
+ /**
28
+ * Finds every direct dependency usage whose name matches `namePattern` and which is installable
29
+ * (not a workspace dep, not a non-installable section like `overrides`), grouped by the
30
+ * `package.json` directory and dependency section so each install runs in the right place.
31
+ */
32
+ export declare function buildUpgradeMatches({ allDirectDeps, namePattern, }: {
33
+ allDirectDeps: Readonly<NpmDeps>;
34
+ namePattern: string;
35
+ }): UpgradeMatches;
36
+ /**
37
+ * Builds the `npm i` command that installs the given deps at the requested version. Each
38
+ * `<name>@<version>` spec is single-quoted; combined with the {@link isSafePackageName} validation
39
+ * done while matching and the version-specifier validation in {@link runArgBasedUpgrade}, this
40
+ * prevents shell injection from `package.json` names or the CLI version argument.
41
+ */
42
+ export declare function buildUpgradeInstallCommand({ flag, passthroughArgs, depNames, versionSpecifier, }: {
43
+ flag: string;
44
+ passthroughArgs: ReadonlyArray<string>;
45
+ depNames: ReadonlyArray<string>;
46
+ versionSpecifier: string;
47
+ }): string;
48
+ /**
49
+ * Runs the argument-based `deps upgrade` path: matches direct deps against `depPattern` across the
50
+ * mono-repo (or single package), then installs each matched group at the requested version in its
51
+ * own package directory. Throws when nothing matches.
52
+ */
53
+ export declare function runArgBasedUpgrade({ depPattern, filteredArgs, monoRepoRootPath, runShellCommand, listDirectDeps, }: {
54
+ depPattern: string;
55
+ filteredArgs: ReadonlyArray<string>;
56
+ monoRepoRootPath: string;
57
+ runShellCommand: RunUpgradeShellCommand;
58
+ listDirectDeps?: ((rootPath: string) => Promise<NpmDeps>) | undefined;
59
+ }): Promise<void>;
@@ -0,0 +1,121 @@
1
+ import { check } from '@augment-vir/assert';
2
+ import { awaitedBlockingMap, getObjectTypedEntries } from '@augment-vir/common';
3
+ import { listAllDirectNpmDeps } from '@augment-vir/node';
4
+ import { VirmatorNoTraceError } from '@virmator/core';
5
+ import { dirname, matchesGlob, relative } from 'node:path';
6
+ import { installFlagsByDepKey } from './install-flags.js';
7
+ /**
8
+ * Whether a dependency name is a safe npm package name to interpolate (single-quoted) into a shell
9
+ * command. Restricting names read out of an (untrusted) `package.json` to this shape guarantees
10
+ * they cannot contain shell metacharacters or quotes.
11
+ */
12
+ export function isSafePackageName(depName) {
13
+ return /^@?[a-z0-9][a-z0-9._-]*(\/[a-z0-9][a-z0-9._-]*)?$/i.test(depName);
14
+ }
15
+ /**
16
+ * Splits a `deps upgrade` pattern into its name pattern and version specifier. The first `@` in a
17
+ * scoped name like `@augment-vir/*` is part of the name, so only a non-leading `@` separates the
18
+ * name from the version. A missing version defaults to `latest`.
19
+ */
20
+ export function splitUpgradePattern(depPattern) {
21
+ const lastAtIndex = depPattern.lastIndexOf('@');
22
+ return {
23
+ namePattern: lastAtIndex > 0 ? depPattern.slice(0, lastAtIndex) : depPattern,
24
+ versionSpecifier: lastAtIndex > 0 ? depPattern.slice(lastAtIndex + 1) : 'latest',
25
+ };
26
+ }
27
+ /**
28
+ * Finds every direct dependency usage whose name matches `namePattern` and which is installable
29
+ * (not a workspace dep, not a non-installable section like `overrides`), grouped by the
30
+ * `package.json` directory and dependency section so each install runs in the right place.
31
+ */
32
+ export function buildUpgradeMatches({ allDirectDeps, namePattern, }) {
33
+ return getObjectTypedEntries(allDirectDeps).reduce((accum, [depName, usages,]) => {
34
+ if (!isSafePackageName(depName) || !matchesGlob(depName, namePattern)) {
35
+ return accum;
36
+ }
37
+ return usages.reduce((innerAccumulator, usage) => {
38
+ if (usage.isWorkspace || installFlagsByDepKey[usage.dependencyKey] == undefined) {
39
+ return innerAccumulator;
40
+ }
41
+ const packageDir = dirname(usage.requiredBy);
42
+ const existingDepsByKey = innerAccumulator[packageDir] ?? {};
43
+ const existingDeps = existingDepsByKey[usage.dependencyKey] ?? [];
44
+ return {
45
+ ...innerAccumulator,
46
+ [packageDir]: {
47
+ ...existingDepsByKey,
48
+ [usage.dependencyKey]: [
49
+ ...existingDeps,
50
+ depName,
51
+ ],
52
+ },
53
+ };
54
+ }, accum);
55
+ }, {});
56
+ }
57
+ /**
58
+ * Builds the `npm i` command that installs the given deps at the requested version. Each
59
+ * `<name>@<version>` spec is single-quoted; combined with the {@link isSafePackageName} validation
60
+ * done while matching and the version-specifier validation in {@link runArgBasedUpgrade}, this
61
+ * prevents shell injection from `package.json` names or the CLI version argument.
62
+ */
63
+ export function buildUpgradeInstallCommand({ flag, passthroughArgs, depNames, versionSpecifier, }) {
64
+ return [
65
+ 'npm',
66
+ 'i',
67
+ flag,
68
+ ...passthroughArgs,
69
+ ...depNames.map((depName) => `'${depName}@${versionSpecifier}'`),
70
+ ]
71
+ .filter(check.isTruthy)
72
+ .join(' ');
73
+ }
74
+ /**
75
+ * Runs the argument-based `deps upgrade` path: matches direct deps against `depPattern` across the
76
+ * mono-repo (or single package), then installs each matched group at the requested version in its
77
+ * own package directory. Throws when nothing matches.
78
+ */
79
+ export async function runArgBasedUpgrade({ depPattern, filteredArgs, monoRepoRootPath, runShellCommand, listDirectDeps = listAllDirectNpmDeps, }) {
80
+ const passthroughArgs = filteredArgs.toSpliced(filteredArgs.indexOf(depPattern), 1);
81
+ const { namePattern, versionSpecifier } = splitUpgradePattern(depPattern);
82
+ /**
83
+ * The version is interpolated single-quoted into the install command, so a literal single quote
84
+ * is the only character that could break out of the quoting. Reject it rather than risk shell
85
+ * injection from the CLI argument.
86
+ */
87
+ if (versionSpecifier.includes("'")) {
88
+ throw new VirmatorNoTraceError(`Invalid version specifier in upgrade target '${depPattern}'.`);
89
+ }
90
+ const matches = getObjectTypedEntries(buildUpgradeMatches({
91
+ allDirectDeps: await listDirectDeps(monoRepoRootPath),
92
+ namePattern,
93
+ }));
94
+ if (!matches.length) {
95
+ throw new VirmatorNoTraceError(`No direct dependencies matching '${depPattern}' found in any package.json.`);
96
+ }
97
+ await awaitedBlockingMap(matches, async ([packageDir, depsByKey,]) => {
98
+ await awaitedBlockingMap(getObjectTypedEntries(depsByKey), async ([dependencyKey, depNames,]) => {
99
+ const flag = installFlagsByDepKey[dependencyKey];
100
+ /**
101
+ * Defensive guard: `buildUpgradeMatches` already drops entries whose dep key
102
+ * maps to an undefined flag, so this branch is unreachable in practice.
103
+ */
104
+ /* node:coverage ignore next 3 */
105
+ if (flag == undefined) {
106
+ return;
107
+ }
108
+ await runShellCommand(buildUpgradeInstallCommand({
109
+ flag,
110
+ passthroughArgs,
111
+ depNames,
112
+ versionSpecifier,
113
+ }), {
114
+ cwd: packageDir,
115
+ }, {
116
+ logPrefix: relative(monoRepoRootPath, packageDir) || '.',
117
+ prefixCommandOnly: true,
118
+ });
119
+ });
120
+ });
121
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@virmator/deps",
3
- "version": "14.23.1",
3
+ "version": "14.25.0",
4
4
  "description": "Default TS deps plugin for virmator.",
5
5
  "keywords": [
6
6
  "virmator",
@@ -34,22 +34,22 @@
34
34
  "test:update": "npm test update"
35
35
  },
36
36
  "dependencies": {
37
- "@augment-vir/assert": "^31.71.3",
38
- "@augment-vir/common": "^31.71.3",
39
- "@augment-vir/node": "^31.71.3",
37
+ "@augment-vir/assert": "^31.72.1",
38
+ "@augment-vir/common": "^31.72.1",
39
+ "@augment-vir/node": "^31.72.1",
40
40
  "@npm/types": "^2.1.0",
41
- "@virmator/core": "^14.23.1",
42
- "date-vir": "^8.3.2",
41
+ "@virmator/core": "^14.25.0",
42
+ "date-vir": "^8.4.0",
43
43
  "mri": "^1.2.0"
44
44
  },
45
45
  "devDependencies": {
46
- "@augment-vir/test": "^31.71.3",
47
- "@types/node": "^25.9.1",
46
+ "@augment-vir/test": "^31.72.1",
47
+ "@types/node": "^25.9.2",
48
48
  "c8": "^11.0.0",
49
- "dependency-cruiser": "^17.4.2",
49
+ "dependency-cruiser": "^17.4.3",
50
50
  "esbuild": "^0.28.0",
51
51
  "istanbul-smart-text-reporter": "^1.1.5",
52
- "npm-check-updates": "^22.2.1"
52
+ "npm-check-updates": "^22.2.3"
53
53
  },
54
54
  "peerDependencies": {
55
55
  "npm-check-updates": ">=19"
@@ -1,63 +0,0 @@
1
- /** These packages bypass min-release-age when running `virmator deps regen`. */
2
- export type RecentDepsAllowList = ReadonlyArray<string | RegExp>;
3
-
4
- const electrovirPackages: RecentDepsAllowList = [
5
- /^@augment-vir\//,
6
- /^@date-vir\//,
7
- /^@electrovir\//,
8
- /^@rest-vir\//,
9
- /^@review-vir\//,
10
- /^@updating-secrets\//,
11
- /^@virmator\//,
12
- 'auth-vir',
13
- 'catch-exit',
14
- 'cli-vir',
15
- 'cron-vir',
16
- 'date-vir',
17
- 'deploy-vir',
18
- 'detect-activity',
19
- 'docker-vir',
20
- 'element-book',
21
- 'element-vir',
22
- 'execute-in-browser',
23
- 'i18n-vir',
24
- 'indexed-vir',
25
- 'istanbul-smart-text-reporter',
26
- 'lit-css-vars',
27
- 'local-db-client',
28
- 'markdown-code-example-inserter',
29
- 'mock-vir',
30
- 'mono-vir',
31
- 'object-shape-tester',
32
- 'observavir',
33
- 'parse-email-address',
34
- 'pdf-vir',
35
- 'pglite-cli',
36
- 'prettier-plugin-interpolated-html-tags',
37
- 'prettier-plugin-multiline-arrays',
38
- 'prevent-navigation',
39
- 'prisma-pglite',
40
- 'prisma-vir',
41
- 'pull-request-vir',
42
- 'runstorm',
43
- 'schema-vir',
44
- 'sentry-vir',
45
- 'spa-router-vir',
46
- 'structured-render',
47
- 'theme-vir',
48
- 'tidy-tsc',
49
- 'typed-event-target',
50
- 'updating-secrets',
51
- 'url-vir',
52
- 'vira',
53
- 'virmator',
54
- 'web-snaps',
55
- ];
56
-
57
- /**
58
- * The default allow list: electrovir's own commonly-used packages. Each entry matches a package by
59
- * exact name (string) or by pattern (RegExp tested against the package name).
60
- */
61
- export const baseAllowedRecentDeps: RecentDepsAllowList = [
62
- ...electrovirPackages,
63
- ];
@@ -1,191 +0,0 @@
1
- import { type Logger } from '@augment-vir/common';
2
- import { type NpmDeps, type PackageJsonDependencyKey } from '@augment-vir/node';
3
- import { type ExtraRunShellCommandOptions } from '@virmator/core';
4
- import { type FullDate } from 'date-vir';
5
- /** Returns whether a dependency name is safe to use in a shell command. */
6
- export declare function isSafePackageName(depName: string): boolean;
7
- /**
8
- * Pulls an optional `--config <path>` (or `--config=<path>`) flag out of the raw `deps regen` args,
9
- * returning the config value and the remaining args to forward to `npm i`.
10
- */
11
- export declare function extractRegenConfigArg(filteredArgs: ReadonlyArray<string>): {
12
- configValue: string | undefined;
13
- passthroughArgs: string[];
14
- };
15
- /**
16
- * Resolves the deps-regen config path: the explicit `--config` value relative to the cwd, or the
17
- * default `configs/deps-regen.config.ts` at the mono-repo root (as placed by `virmator init`).
18
- */
19
- export declare function resolveRegenConfigPath({ configValue, cwd, monoRepoRootPath, }: {
20
- configValue: string | undefined;
21
- cwd: string;
22
- monoRepoRootPath: string;
23
- }): string;
24
- /**
25
- * Structural copy of the allow list type defined in `configs/deps-regen.config.base.ts`. It is
26
- * re-declared here because `configs` lives outside this package's compiled `src` root, so it cannot
27
- * be type-imported. Each entry matches a package by exact name (string) or pattern (RegExp).
28
- */
29
- export type RecentDepsAllowList = ReadonlyArray<string | RegExp>;
30
- /** A direct dependency whose currently-pinned version is too recent for the repo's min-release-age. */
31
- export type RecentDepViolator = {
32
- /** Absolute path to the `package.json` that pins this dependency. */
33
- packageJsonPath: string;
34
- /** Directory containing {@link RecentDepViolator.packageJsonPath}. */
35
- packageDir: string;
36
- dependencyKey: PackageJsonDependencyKey;
37
- depName: string;
38
- /** The original version range string from `package.json`, including any prefix (e.g. `^1.2.3`). */
39
- originalVersionValue: string;
40
- /** The leading non-numeric prefix of the original version (e.g. `^` or `~` or `''`). */
41
- versionPrefix: string;
42
- /**
43
- * The most recent published version that does _not_ violate min-release-age, to temporarily
44
- * downgrade to. `undefined` when _no_ published version is old enough (e.g. a brand-new
45
- * package); in that case the dep is temporarily removed for the regen install instead, then
46
- * re-added by the bypass reinstall.
47
- */
48
- safeVersion: string | undefined;
49
- };
50
- export type RegistryInfo = {
51
- /** Map of published version (and `created`/`modified`) to ISO publish date. */
52
- time: Record<string, string>;
53
- };
54
- /** A single `package.json` dependency change applied by {@link updatePackageJsonVersions}. */
55
- export type VersionUpdate = {
56
- dependencyKey: PackageJsonDependencyKey;
57
- depName: string;
58
- /** The new version range, or `undefined` to remove the dependency entry entirely. */
59
- version: string | undefined;
60
- };
61
- /** A direct dependency name paired with its installable, non-workspace usages. */
62
- export type CandidateDepUsage = {
63
- depName: string;
64
- usages: NpmDeps[string];
65
- };
66
- /**
67
- * Injectable IO used by {@link prepareRecentDepDowngrades}. Defaults to real implementations;
68
- * overridden in tests so the orchestration can be exercised without touching the network or
69
- * filesystem.
70
- */
71
- export type RecentDepsIo = {
72
- fileExists: (filePath: string) => Promise<boolean>;
73
- loadAllowList: (configPath: string) => Promise<RecentDepsAllowList | undefined>;
74
- listDirectDeps: (rootPath: string) => Promise<NpmDeps>;
75
- queryRegistry: (depName: string, cwd: string) => Promise<RegistryInfo | undefined>;
76
- /**
77
- * Returns every published version satisfying the given range (ignoring min-release-age), or
78
- * `undefined` if the range matches nothing. Used to decide whether a cooldown-respecting
79
- * install could find an old-enough version.
80
- */
81
- queryInRangeVersions: (depName: string, range: string, cwd: string) => Promise<string[] | undefined>;
82
- updatePackageJsonVersions: (packageJsonPath: string, updates: ReadonlyArray<VersionUpdate>) => Promise<void>;
83
- };
84
- /** Parses the output of `npm config get min-release-age` into a positive day count, or `undefined`. */
85
- export declare function parseMinReleaseAgeDays(rawValue: string): number | undefined;
86
- /**
87
- * Returns the effective `min-release-age` (in days) as resolved by npm across all config sources
88
- * (project `.npmrc` overriding user, overriding global), or `undefined` if it is unset or
89
- * non-positive.
90
- */
91
- export declare function getMinReleaseAgeDays(monoRepoRootPath: string): Promise<number | undefined>;
92
- export declare function fileExists(filePath: string): Promise<boolean>;
93
- export declare function loadAllowList(configPath: string): Promise<RecentDepsAllowList | undefined>;
94
- /** Parses the JSON time map output of `npm view <pkg> time --json` into a {@link RegistryInfo}. */
95
- export declare function parseRegistryTime(stdout: string): RegistryInfo | undefined;
96
- /**
97
- * Parses the JSON output of `npm view <pkg>@<range> version --json` into the list of published
98
- * versions that satisfy the range (npm returns a single string when only one matches, an array
99
- * otherwise). `undefined` if nothing matched / the output was unusable.
100
- */
101
- export declare function parseInRangeVersions(stdout: string): string[] | undefined;
102
- /**
103
- * Reads, applies the given dependency changes to, and re-writes a `package.json` file in place. A
104
- * `string` version sets (or re-adds) the entry; an `undefined` version removes it. Sections that
105
- * don't exist are left untouched.
106
- */
107
- export declare function updatePackageJsonVersions(packageJsonPath: string, updates: ReadonlyArray<VersionUpdate>): Promise<void>;
108
- /**
109
- * Drops workspace-internal deps, non-installable sections (e.g. `overrides`), and any dependency
110
- * whose name is not a safe npm package name (the latter both as a correctness guard and to prevent
111
- * shell injection when the name is later passed to npm). Grouped by name.
112
- */
113
- export declare function getCandidateDepUsages(allDirectDeps: Readonly<NpmDeps>): CandidateDepUsage[];
114
- /** The lookup key for a specific dependency range (or version). */
115
- export declare function depRangeKey(depName: string, range: string): string;
116
- /**
117
- * Returns the `{depName, range}` pairs whose in-range versions must be looked up (to decide whether
118
- * a cooldown-respecting install could satisfy the range): only for allow-list-matched candidates
119
- * with a parseable range. Deduped.
120
- */
121
- export declare function getResolveTargets(candidateUsages: ReadonlyArray<CandidateDepUsage>, allowList: RecentDepsAllowList): {
122
- depName: string;
123
- range: string;
124
- }[];
125
- /**
126
- * Pure detection of every direct dependency usage that both matches the allow list and whose range
127
- * _cannot_ be satisfied by an old-enough version (so a cooldown-respecting `npm i` would fail),
128
- * paired with the safe version it should be temporarily downgraded to (or `undefined` to remove).
129
- * Deps whose range already has an old-enough version are left alone — `npm i` installs that
130
- * itself.
131
- */
132
- export declare function computeRecentDepViolators({ candidateUsages, allowList, registryByName, inRangeVersionsByRange, threshold, }: {
133
- candidateUsages: ReadonlyArray<CandidateDepUsage>;
134
- allowList: RecentDepsAllowList;
135
- registryByName: ReadonlyMap<string, RegistryInfo | undefined>;
136
- /** The published versions satisfying each `${depName}@${range}` (ignoring min-release-age). */
137
- inRangeVersionsByRange: ReadonlyMap<string, string[] | undefined>;
138
- /** The min-release-age cutoff: a version published after this is too recent. */
139
- threshold: FullDate;
140
- }): RecentDepViolator[];
141
- /** The real IO (network and filesystem) used by {@link prepareRecentDepDowngrades}. */
142
- export declare const defaultRecentDepsIo: RecentDepsIo;
143
- /**
144
- * Detects every direct dependency that both matches the deps-regen allow list and currently pins a
145
- * version that violates the repo's min-release-age. Each such dependency is temporarily downgraded
146
- * in its `package.json` to the most recent version that does _not_ violate min-release-age, so that
147
- * the subsequent `npm i` succeeds. The original version values are returned so they can be restored
148
- * via {@link reinstallOriginalDeps} and {@link restoreOriginalPackageJsonVersions} after
149
- * regeneration.
150
- */
151
- export declare function prepareRecentDepDowngrades({ monoRepoRootPath, configPath, configIsExplicit, minReleaseAgeDays, log, now, io, }: {
152
- monoRepoRootPath: string;
153
- configPath: string;
154
- /**
155
- * Whether `configPath` came from an explicit `--config` flag. A missing explicit config throws,
156
- * while a missing default config is silently skipped.
157
- */
158
- configIsExplicit: boolean;
159
- /**
160
- * The effective `min-release-age` in days. When unset, the whole feature is skipped without
161
- * even reading the deps-regen config.
162
- */
163
- minReleaseAgeDays: number | undefined;
164
- log: Logger;
165
- now?: FullDate | undefined;
166
- io?: RecentDepsIo | undefined;
167
- }): Promise<RecentDepViolator[]>;
168
- /**
169
- * Re-installs each downgraded dependency at its original version, bypassing min-release-age.
170
- * Installs are grouped per package directory and per dependency type (`-D`, `--save-peer`, or none)
171
- * so each `npm i` runs in the correct location (sub-packages and/or the mono-repo root). Each
172
- * install spec is single-quoted; combined with the package-name and version validation done while
173
- * detecting violators, this prevents shell injection from `package.json` values.
174
- */
175
- export declare function reinstallOriginalDeps({ violators, monoRepoRootPath, runVirmatorShellCommand, }: {
176
- violators: ReadonlyArray<RecentDepViolator>;
177
- monoRepoRootPath: string;
178
- runVirmatorShellCommand: (command: string, options: {
179
- cwd: string;
180
- }, extraOptions: Partial<ExtraRunShellCommandOptions>) => Promise<unknown>;
181
- }): Promise<void>;
182
- /**
183
- * Restores the original `package.json` version strings for each violator. Safe to call after a
184
- * successful regen (where `npm i` rewrote them to the resolved version) or in a `finally` after a
185
- * failed one (to undo the temporary downgrade), so `package.json` is never left silently
186
- * downgraded.
187
- */
188
- export declare function restoreOriginalPackageJsonVersions({ violators, updateVersions, }: {
189
- violators: ReadonlyArray<RecentDepViolator>;
190
- updateVersions?: RecentDepsIo['updatePackageJsonVersions'] | undefined;
191
- }): Promise<void>;
@@ -1,474 +0,0 @@
1
- import { check } from '@augment-vir/assert';
2
- import { awaitedBlockingMap, getObjectTypedEntries, removeDuplicates, wrapInTry, } from '@augment-vir/common';
3
- import { listAllDirectNpmDeps, runShellCommand, } from '@augment-vir/node';
4
- import { JsModuleType, VirmatorNoTraceError, withImportedTsFile, } from '@virmator/core';
5
- import { calculateRelativeDate, createUtcFullDate, getNowInUtcTimezone, isDateAfter, isValidIsoString, } from 'date-vir';
6
- import { readFile, stat, writeFile } from 'node:fs/promises';
7
- import { dirname, join, relative, resolve } from 'node:path';
8
- import { installFlagsByDepKey } from './install-flags.js';
9
- const defaultDepsRegenConfigRelativePath = join('configs', 'deps-regen.config.ts');
10
- /** Returns whether a dependency name is safe to use in a shell command. */
11
- export function isSafePackageName(depName) {
12
- /**
13
- * Conservative npm package-name shape. Restricting names to these characters guarantees that
14
- * values read out of an (untrusted) `package.json` and interpolated into shell commands cannot
15
- * contain shell metacharacters or quotes.
16
- */
17
- return /^@?[a-z0-9][a-z0-9._-]*(\/[a-z0-9][a-z0-9._-]*)?$/i.test(depName);
18
- }
19
- /**
20
- * Pulls an optional `--config <path>` (or `--config=<path>`) flag out of the raw `deps regen` args,
21
- * returning the config value and the remaining args to forward to `npm i`.
22
- */
23
- export function extractRegenConfigArg(filteredArgs) {
24
- const { configValue, passthroughArgs, skipNext } = filteredArgs.reduce((accum, arg) => {
25
- if (accum.skipNext) {
26
- return {
27
- configValue: arg,
28
- skipNext: false,
29
- passthroughArgs: accum.passthroughArgs,
30
- };
31
- }
32
- else if (arg === '--config') {
33
- return {
34
- ...accum,
35
- skipNext: true,
36
- };
37
- }
38
- else if (arg.startsWith('--config=')) {
39
- return {
40
- ...accum,
41
- configValue: arg.slice('--config='.length),
42
- };
43
- }
44
- return {
45
- ...accum,
46
- passthroughArgs: [
47
- ...accum.passthroughArgs,
48
- arg,
49
- ],
50
- };
51
- }, {
52
- configValue: undefined,
53
- skipNext: false,
54
- passthroughArgs: [],
55
- });
56
- /** A dangling '--config' (skipNext) or an empty '--config='/'--config ""' value is an error. */
57
- if (skipNext || configValue === '') {
58
- throw new VirmatorNoTraceError('The --config flag requires a file path value.');
59
- }
60
- return {
61
- configValue,
62
- passthroughArgs,
63
- };
64
- }
65
- /**
66
- * Resolves the deps-regen config path: the explicit `--config` value relative to the cwd, or the
67
- * default `configs/deps-regen.config.ts` at the mono-repo root (as placed by `virmator init`).
68
- */
69
- export function resolveRegenConfigPath({ configValue, cwd, monoRepoRootPath, }) {
70
- return configValue
71
- ? resolve(cwd, configValue)
72
- : join(monoRepoRootPath, defaultDepsRegenConfigRelativePath);
73
- }
74
- /** Parses the output of `npm config get min-release-age` into a positive day count, or `undefined`. */
75
- export function parseMinReleaseAgeDays(rawValue) {
76
- const days = Number(rawValue.trim());
77
- return Number.isFinite(days) && days > 0 ? days : undefined;
78
- }
79
- /* node:coverage disable -- thin wrapper around the npm CLI; parsing lives in parseMinReleaseAgeDays */
80
- /**
81
- * Returns the effective `min-release-age` (in days) as resolved by npm across all config sources
82
- * (project `.npmrc` overriding user, overriding global), or `undefined` if it is unset or
83
- * non-positive.
84
- */
85
- export async function getMinReleaseAgeDays(monoRepoRootPath) {
86
- const result = await runShellCommand('npm config get min-release-age', {
87
- cwd: monoRepoRootPath,
88
- });
89
- if (result.exitCode) {
90
- return undefined;
91
- }
92
- return parseMinReleaseAgeDays(result.stdout);
93
- }
94
- /* node:coverage enable */
95
- export async function fileExists(filePath) {
96
- return await wrapInTry(async () => {
97
- await stat(filePath);
98
- return true;
99
- }, {
100
- fallbackValue: false,
101
- });
102
- }
103
- export async function loadAllowList(configPath) {
104
- return await withImportedTsFile({
105
- inputPath: configPath,
106
- }, JsModuleType.Esm, (loadedConfig) => {
107
- const list = loadedConfig.depsRegenAllowList ?? loadedConfig.default;
108
- return check.isArray(list) ? list : undefined;
109
- });
110
- }
111
- /** Parses the JSON time map output of `npm view <pkg> time --json` into a {@link RegistryInfo}. */
112
- export function parseRegistryTime(stdout) {
113
- const parsed = wrapInTry(() => JSON.parse(stdout), {
114
- fallbackValue: undefined,
115
- });
116
- if (!check.isObject(parsed)) {
117
- return undefined;
118
- }
119
- return {
120
- time: parsed,
121
- };
122
- }
123
- /**
124
- * Parses the JSON output of `npm view <pkg>@<range> version --json` into the list of published
125
- * versions that satisfy the range (npm returns a single string when only one matches, an array
126
- * otherwise). `undefined` if nothing matched / the output was unusable.
127
- */
128
- export function parseInRangeVersions(stdout) {
129
- const parsed = wrapInTry(() => JSON.parse(stdout), {
130
- fallbackValue: undefined,
131
- });
132
- if (check.isString(parsed)) {
133
- return [
134
- parsed,
135
- ];
136
- }
137
- else if (check.isArray(parsed)) {
138
- return parsed.filter(check.isString);
139
- }
140
- return undefined;
141
- }
142
- /* node:coverage disable -- thin network wrappers around the npm registry; parsing lives in the parse* helpers */
143
- async function queryRegistry(depName, cwd) {
144
- const result = await runShellCommand(`npm view '${depName}' time --json`, {
145
- cwd,
146
- });
147
- if (result.exitCode) {
148
- return undefined;
149
- }
150
- return parseRegistryTime(result.stdout);
151
- }
152
- async function queryInRangeVersions(depName, range, cwd) {
153
- const result = await runShellCommand(`npm view '${depName}@${range}' version --json`, {
154
- cwd,
155
- });
156
- if (result.exitCode) {
157
- return undefined;
158
- }
159
- return parseInRangeVersions(result.stdout);
160
- }
161
- /* node:coverage enable */
162
- /** Whether a dependency name matches any allow-list entry (exact string or RegExp pattern). */
163
- function matchesAllowList(allowList, depName) {
164
- return allowList.some((entry) => entry instanceof RegExp ? entry.test(depName) : entry === depName);
165
- }
166
- /**
167
- * Splits a version range value into its leading prefix and a clean `x.y.z` version, if possible.
168
- * The prefix is restricted to known semver range operators so that values read out of an
169
- * (untrusted) `package.json` cannot smuggle shell metacharacters through as a "prefix".
170
- */
171
- function parseVersionValue(versionValue) {
172
- const match = /^(>=|<=|>|<|\^|~|=|v)?(\d+\.\d+\.\d+)\s*$/i.exec(versionValue);
173
- if (!match?.[2]) {
174
- return undefined;
175
- }
176
- return {
177
- prefix: match[1] || '',
178
- version: match[2],
179
- };
180
- }
181
- /**
182
- * Whether the given publish date is old enough to satisfy `threshold` (the min-release-age cutoff)
183
- * — i.e. a cooldown-respecting `npm i` would be allowed to install it. Missing/invalid dates are
184
- * treated as not old enough.
185
- */
186
- function isVersionOldEnough(publishDateString, threshold) {
187
- if (!publishDateString || !isValidIsoString(publishDateString)) {
188
- return false;
189
- }
190
- return !isDateAfter({
191
- fullDate: createUtcFullDate(publishDateString),
192
- relativeTo: threshold,
193
- });
194
- }
195
- /** Finds the most recently published stable version that is old enough to satisfy `threshold`. */
196
- function findMostRecentSafeVersion(time, threshold) {
197
- const safeVersions = getObjectTypedEntries(time)
198
- .filter(([version, dateString,]) => /^\d+\.\d+\.\d+$/.test(version) && isVersionOldEnough(dateString, threshold))
199
- .map(([version, dateString,]) => {
200
- return {
201
- version,
202
- date: createUtcFullDate(dateString),
203
- };
204
- });
205
- if (!safeVersions.length) {
206
- return undefined;
207
- }
208
- return safeVersions.reduce((mostRecent, current) => isDateAfter({
209
- fullDate: current.date,
210
- relativeTo: mostRecent.date,
211
- })
212
- ? current
213
- : mostRecent).version;
214
- }
215
- /**
216
- * Reads, applies the given dependency changes to, and re-writes a `package.json` file in place. A
217
- * `string` version sets (or re-adds) the entry; an `undefined` version removes it. Sections that
218
- * don't exist are left untouched.
219
- */
220
- export async function updatePackageJsonVersions(packageJsonPath, updates) {
221
- const originalContents = await readFile(packageJsonPath, 'utf8');
222
- const indent = /\n([ \t]+)\S/.exec(originalContents)?.[1] || ' ';
223
- const trailingNewLine = originalContents.endsWith('\n') ? '\n' : '';
224
- const parsed = JSON.parse(originalContents);
225
- updates.forEach(({ dependencyKey, depName, version }) => {
226
- const section = parsed[dependencyKey];
227
- if (!check.isObject(section)) {
228
- return;
229
- }
230
- if (version == undefined) {
231
- delete section[depName];
232
- }
233
- else {
234
- section[depName] = version;
235
- }
236
- });
237
- await writeFile(packageJsonPath, JSON.stringify(parsed, undefined, indent) + trailingNewLine);
238
- }
239
- /** Groups violators by their `package.json` path so each file is written exactly once. */
240
- function groupByPackageJson(violators) {
241
- return violators.reduce((accum, violator) => {
242
- const existing = accum.get(violator.packageJsonPath) ?? [];
243
- accum.set(violator.packageJsonPath, [
244
- ...existing,
245
- violator,
246
- ]);
247
- return accum;
248
- }, new Map());
249
- }
250
- /**
251
- * Drops workspace-internal deps, non-installable sections (e.g. `overrides`), and any dependency
252
- * whose name is not a safe npm package name (the latter both as a correctness guard and to prevent
253
- * shell injection when the name is later passed to npm). Grouped by name.
254
- */
255
- export function getCandidateDepUsages(allDirectDeps) {
256
- return getObjectTypedEntries(allDirectDeps)
257
- .filter(([depName]) => isSafePackageName(depName))
258
- .map(([depName, usages,]) => {
259
- return {
260
- depName,
261
- usages: usages.filter((usage) => !usage.isWorkspace &&
262
- installFlagsByDepKey[usage.dependencyKey] != undefined),
263
- };
264
- })
265
- .filter(({ usages }) => usages.length);
266
- }
267
- /** The lookup key for a specific dependency range (or version). */
268
- export function depRangeKey(depName, range) {
269
- return `${depName}@${range}`;
270
- }
271
- /** The simple range (prefix + `x.y.z`) reconstructed from a usage's version value, if parseable. */
272
- function rangeOfUsage(versionValue) {
273
- const parsedVersion = parseVersionValue(versionValue);
274
- return parsedVersion ? `${parsedVersion.prefix}${parsedVersion.version}` : undefined;
275
- }
276
- /**
277
- * Returns the `{depName, range}` pairs whose in-range versions must be looked up (to decide whether
278
- * a cooldown-respecting install could satisfy the range): only for allow-list-matched candidates
279
- * with a parseable range. Deduped.
280
- */
281
- export function getResolveTargets(candidateUsages, allowList) {
282
- const targets = new Map();
283
- candidateUsages.forEach(({ depName, usages }) => {
284
- if (!matchesAllowList(allowList, depName)) {
285
- return;
286
- }
287
- usages.forEach((usage) => {
288
- const range = rangeOfUsage(usage.versionValue);
289
- if (range != undefined) {
290
- targets.set(depRangeKey(depName, range), {
291
- depName,
292
- range,
293
- });
294
- }
295
- });
296
- });
297
- return Array.from(targets.values());
298
- }
299
- /**
300
- * Pure detection of every direct dependency usage that both matches the allow list and whose range
301
- * _cannot_ be satisfied by an old-enough version (so a cooldown-respecting `npm i` would fail),
302
- * paired with the safe version it should be temporarily downgraded to (or `undefined` to remove).
303
- * Deps whose range already has an old-enough version are left alone — `npm i` installs that
304
- * itself.
305
- */
306
- export function computeRecentDepViolators({ candidateUsages, allowList, registryByName, inRangeVersionsByRange, threshold, }) {
307
- return candidateUsages.flatMap(({ depName, usages }) => {
308
- const registry = registryByName.get(depName);
309
- if (!registry || !matchesAllowList(allowList, depName)) {
310
- return [];
311
- }
312
- return usages.flatMap((usage) => {
313
- const parsedVersion = parseVersionValue(usage.versionValue);
314
- if (!parsedVersion) {
315
- return [];
316
- }
317
- const range = `${parsedVersion.prefix}${parsedVersion.version}`;
318
- const inRangeVersions = inRangeVersionsByRange.get(depRangeKey(depName, range));
319
- /**
320
- * Leave the dep alone when its range matches nothing (a plain install would fail with a
321
- * clear error of its own) or when some in-range version is old enough (a plain install
322
- * resolves the range to that version on its own — no downgrade needed).
323
- */
324
- if (!inRangeVersions?.length ||
325
- inRangeVersions.some((version) => isVersionOldEnough(registry.time[version], threshold))) {
326
- return [];
327
- }
328
- /**
329
- * No in-range version is old enough, so a cooldown-respecting install can't satisfy the
330
- * range. Downgrade to the most recent old-enough version overall, or — when there is no
331
- * old-enough version at all (a brand-new package) — `undefined`, meaning the dep is
332
- * temporarily removed for the regen install rather than downgraded.
333
- */
334
- const safeVersion = findMostRecentSafeVersion(registry.time, threshold);
335
- return [
336
- {
337
- packageJsonPath: usage.requiredBy,
338
- packageDir: dirname(usage.requiredBy),
339
- dependencyKey: usage.dependencyKey,
340
- depName,
341
- originalVersionValue: usage.versionValue,
342
- versionPrefix: parsedVersion.prefix,
343
- safeVersion,
344
- },
345
- ];
346
- });
347
- });
348
- }
349
- /** The real IO (network and filesystem) used by {@link prepareRecentDepDowngrades}. */
350
- export const defaultRecentDepsIo = {
351
- fileExists,
352
- loadAllowList,
353
- listDirectDeps: listAllDirectNpmDeps,
354
- queryRegistry,
355
- queryInRangeVersions,
356
- updatePackageJsonVersions,
357
- };
358
- /**
359
- * Detects every direct dependency that both matches the deps-regen allow list and currently pins a
360
- * version that violates the repo's min-release-age. Each such dependency is temporarily downgraded
361
- * in its `package.json` to the most recent version that does _not_ violate min-release-age, so that
362
- * the subsequent `npm i` succeeds. The original version values are returned so they can be restored
363
- * via {@link reinstallOriginalDeps} and {@link restoreOriginalPackageJsonVersions} after
364
- * regeneration.
365
- */
366
- export async function prepareRecentDepDowngrades({ monoRepoRootPath, configPath, configIsExplicit, minReleaseAgeDays, log, now = getNowInUtcTimezone(), io = defaultRecentDepsIo, }) {
367
- if (!minReleaseAgeDays) {
368
- return [];
369
- }
370
- else if (!(await io.fileExists(configPath))) {
371
- if (configIsExplicit) {
372
- throw new VirmatorNoTraceError(`deps-regen config file not found: ${configPath}`);
373
- }
374
- return [];
375
- }
376
- const allowList = await io.loadAllowList(configPath);
377
- if (!allowList?.length) {
378
- return [];
379
- }
380
- const threshold = calculateRelativeDate(now, {
381
- days: -minReleaseAgeDays,
382
- });
383
- const candidateUsages = getCandidateDepUsages(await io.listDirectDeps(monoRepoRootPath));
384
- const resolveTargets = getResolveTargets(candidateUsages, allowList);
385
- /** The `time` map is only needed for deps that have a resolve target (a potential violator). */
386
- const registryByName = new Map(await awaitedBlockingMap(removeDuplicates(resolveTargets.map(({ depName }) => depName)), async (depName) => [
387
- depName,
388
- await io.queryRegistry(depName, monoRepoRootPath),
389
- ]));
390
- const inRangeVersionsByRange = new Map(await awaitedBlockingMap(resolveTargets, async ({ depName, range }) => [
391
- depRangeKey(depName, range),
392
- await io.queryInRangeVersions(depName, range, monoRepoRootPath),
393
- ]));
394
- const violators = computeRecentDepViolators({
395
- candidateUsages,
396
- allowList,
397
- registryByName,
398
- inRangeVersionsByRange,
399
- threshold,
400
- });
401
- await awaitedBlockingMap(Array.from(groupByPackageJson(violators).entries()), async ([packageJsonPath, packageViolators,]) => {
402
- packageViolators.forEach((violator) => {
403
- log.faint(violator.safeVersion == undefined
404
- ? `Temporarily removing ${violator.depName} (no version old enough) for regen.`
405
- : `Temporarily downgrading ${violator.depName} from ${violator.originalVersionValue} to ${violator.versionPrefix}${violator.safeVersion} for regen.`);
406
- });
407
- await io.updatePackageJsonVersions(packageJsonPath, packageViolators.map((violator) => {
408
- return {
409
- dependencyKey: violator.dependencyKey,
410
- depName: violator.depName,
411
- version: violator.safeVersion == undefined
412
- ? undefined
413
- : `${violator.versionPrefix}${violator.safeVersion}`,
414
- };
415
- }));
416
- });
417
- return violators;
418
- }
419
- /**
420
- * Re-installs each downgraded dependency at its original version, bypassing min-release-age.
421
- * Installs are grouped per package directory and per dependency type (`-D`, `--save-peer`, or none)
422
- * so each `npm i` runs in the correct location (sub-packages and/or the mono-repo root). Each
423
- * install spec is single-quoted; combined with the package-name and version validation done while
424
- * detecting violators, this prevents shell injection from `package.json` values.
425
- */
426
- export async function reinstallOriginalDeps({ violators, monoRepoRootPath, runVirmatorShellCommand, }) {
427
- const byPackageAndKey = violators.reduce((accum, violator) => {
428
- const byKey = accum.get(violator.packageDir) ?? new Map();
429
- const existing = byKey.get(violator.dependencyKey) ?? [];
430
- byKey.set(violator.dependencyKey, [
431
- ...existing,
432
- violator,
433
- ]);
434
- accum.set(violator.packageDir, byKey);
435
- return accum;
436
- }, new Map());
437
- await awaitedBlockingMap(Array.from(byPackageAndKey.entries()), async ([packageDir, byKey,]) => {
438
- await awaitedBlockingMap(Array.from(byKey.entries()), async ([dependencyKey, keyViolators,]) => {
439
- const flag = installFlagsByDepKey[dependencyKey];
440
- const command = [
441
- 'npm',
442
- 'i',
443
- flag,
444
- ...keyViolators.map((violator) => `'${violator.depName}@${violator.originalVersionValue.trim()}'`),
445
- '--min-release-age=0',
446
- ]
447
- .filter(check.isTruthy)
448
- .join(' ');
449
- await runVirmatorShellCommand(command, {
450
- cwd: packageDir,
451
- }, {
452
- logPrefix: relative(monoRepoRootPath, packageDir) || '.',
453
- prefixCommandOnly: true,
454
- });
455
- });
456
- });
457
- }
458
- /**
459
- * Restores the original `package.json` version strings for each violator. Safe to call after a
460
- * successful regen (where `npm i` rewrote them to the resolved version) or in a `finally` after a
461
- * failed one (to undo the temporary downgrade), so `package.json` is never left silently
462
- * downgraded.
463
- */
464
- export async function restoreOriginalPackageJsonVersions({ violators, updateVersions = updatePackageJsonVersions, }) {
465
- await awaitedBlockingMap(Array.from(groupByPackageJson(violators).entries()), async ([packageJsonPath, packageViolators,]) => {
466
- await updateVersions(packageJsonPath, packageViolators.map((violator) => {
467
- return {
468
- dependencyKey: violator.dependencyKey,
469
- depName: violator.depName,
470
- version: violator.originalVersionValue,
471
- };
472
- }));
473
- });
474
- }