@virmator/deps 14.23.1 → 14.24.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,7 +47,7 @@ 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.
50
+ Reads 'configs/deps-regen.config.ts' for a list of packages (exact names or globs) to exempt from min-release-age during the install, via npm's '--min-release-age-exclude' flag.
51
51
 
52
52
  - Examples
53
53
  - `virmator deps regen`
@@ -1,14 +1,14 @@
1
1
  /** These packages bypass min-release-age when running `virmator deps regen`. */
2
- export type RecentDepsAllowList = ReadonlyArray<string | RegExp>;
2
+ export type RecentDepsAllowList = ReadonlyArray<string>;
3
3
 
4
4
  const electrovirPackages: RecentDepsAllowList = [
5
- /^@augment-vir\//,
6
- /^@date-vir\//,
7
- /^@electrovir\//,
8
- /^@rest-vir\//,
9
- /^@review-vir\//,
10
- /^@updating-secrets\//,
11
- /^@virmator\//,
5
+ '@augment-vir/*',
6
+ '@date-vir/*',
7
+ '@electrovir/*',
8
+ '@rest-vir/*',
9
+ '@review-vir/*',
10
+ '@updating-secrets/*',
11
+ '@virmator/*',
12
12
  'auth-vir',
13
13
  'catch-exit',
14
14
  'cli-vir',
@@ -55,8 +55,9 @@ const electrovirPackages: RecentDepsAllowList = [
55
55
  ];
56
56
 
57
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).
58
+ * The default allow list: electrovir's own commonly-used packages. Each entry is an exact package
59
+ * name or a `minimatch` glob pattern matched against the package name (forwarded to npm's
60
+ * `min-release-age-exclude`).
60
61
  */
61
62
  export const baseAllowedRecentDeps: RecentDepsAllowList = [
62
63
  ...electrovirPackages,
package/dist/deps.d.ts CHANGED
@@ -122,7 +122,7 @@ 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 ", "\n Reads 'configs/deps-regen.config.ts' for a list of packages\n (exact names or globs) to exempt from min-release-age during the\n install, via npm's '--min-release-age-exclude' flag.\n "];
126
126
  readonly examples: readonly [{
127
127
  readonly content: "virmator deps regen";
128
128
  }, {
@@ -256,7 +256,7 @@ export declare const virmatorDepsPlugin: Readonly<Readonly<{
256
256
  };
257
257
  readonly regen: {
258
258
  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 "];
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 a list of packages\n (exact names or globs) to exempt from min-release-age during the\n install, via npm's '--min-release-age-exclude' flag.\n "];
260
260
  readonly examples: readonly [{
261
261
  readonly content: "virmator deps regen";
262
262
  }, {
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 { buildMinReleaseAgeExcludeFlags, extractRegenConfigArg, listRegenNodeModulesDirs, resolveRegenConfigPath, resolveRegenExcludes, } from './regen-recent-deps.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',
@@ -178,8 +178,9 @@ export const virmatorDepsPlugin = defineVirmatorPlugin(import.meta.dirname, {
178
178
  running 'npm i'.
179
179
  `,
180
180
  `
181
- Reads 'configs/deps-regen.config.ts' for intelligently working
182
- around min-release-age for explicitly allowed packages.
181
+ Reads 'configs/deps-regen.config.ts' for a list of packages
182
+ (exact names or globs) to exempt from min-release-age during the
183
+ install, via npm's '--min-release-age-exclude' flag.
183
184
  `,
184
185
  ],
185
186
  examples: [
@@ -247,72 +248,11 @@ export const virmatorDepsPlugin = defineVirmatorPlugin(import.meta.dirname, {
247
248
  const upgradeArgs = mri(filteredArgs);
248
249
  const depPattern = upgradeArgs._[0];
249
250
  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
- });
251
+ await runArgBasedUpgrade({
252
+ depPattern,
253
+ filteredArgs,
254
+ monoRepoRootPath,
255
+ runShellCommand,
316
256
  });
317
257
  }
318
258
  else {
@@ -340,62 +280,41 @@ export const virmatorDepsPlugin = defineVirmatorPlugin(import.meta.dirname, {
340
280
  /** Strip '--config <path>' so it isn't forwarded to 'npm i'. */
341
281
  const { configValue, passthroughArgs } = extractRegenConfigArg(filteredArgs);
342
282
  /**
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.
283
+ * Allow-listed packages (exact names or globs) that bypass min-release-age during the
284
+ * install via npm's '--min-release-age-exclude' flag. Empty when there is no config.
346
285
  */
347
- const recentDepViolators = await prepareRecentDepDowngrades({
348
- monoRepoRootPath,
286
+ const regenExcludes = await resolveRegenExcludes({
349
287
  configPath: resolveRegenConfigPath({
350
288
  configValue,
351
289
  cwd,
352
290
  monoRepoRootPath,
353
291
  }),
354
292
  configIsExplicit: check.isTruthy(configValue),
355
- minReleaseAgeDays: await getMinReleaseAgeDays(monoRepoRootPath),
356
- log,
357
293
  });
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'), {
294
+ const allNodeModulesDirectories = listRegenNodeModulesDirs({
295
+ monoRepoRootPath,
296
+ monoRepoPackages,
297
+ });
298
+ await awaitedBlockingMap(allNodeModulesDirectories, async (path) => {
299
+ log.faint(`Removing ${relative(monoRepoRootPath, path)}...`);
300
+ await rm(path, {
372
301
  force: true,
302
+ recursive: true,
373
303
  });
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
- }
304
+ });
305
+ log.faint('Removing package-lock.json...');
306
+ await rm(join(monoRepoRootPath, 'package-lock.json'), {
307
+ force: true,
308
+ });
309
+ const installCommand = [
310
+ 'npm',
311
+ 'i',
312
+ ...passthroughArgs,
313
+ ...buildMinReleaseAgeExcludeFlags(regenExcludes),
314
+ ].join(' ');
315
+ await runShellCommand(installCommand);
316
+ /** Run twice because npm needs this sometimes. */
317
+ await runShellCommand(installCommand);
399
318
  }
400
319
  else {
401
320
  throw new VirmatorNoTraceError("deps sub-command needed: 'virmator deps check', 'virmator deps upgrade', or 'virmator deps regen'");
@@ -1,9 +1,19 @@
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;
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[];
11
+ /**
12
+ * Whether an allow-list entry is safe to interpolate (single-quoted) into a shell command. Allows
13
+ * npm package names and `minimatch` glob patterns (the `*` wildcard) while rejecting anything that
14
+ * could smuggle shell metacharacters or quotes out of an (untrusted) config file.
15
+ */
16
+ export declare function isSafeExcludePattern(pattern: string): boolean;
7
17
  /**
8
18
  * Pulls an optional `--config <path>` (or `--config=<path>`) flag out of the raw `deps regen` args,
9
19
  * returning the config value and the remaining args to forward to `npm i`.
@@ -24,168 +34,41 @@ export declare function resolveRegenConfigPath({ configValue, cwd, monoRepoRootP
24
34
  /**
25
35
  * Structural copy of the allow list type defined in `configs/deps-regen.config.base.ts`. It is
26
36
  * 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).
37
+ * be type-imported. Each entry is an exact npm package name or a `minimatch` glob pattern matched
38
+ * against the package name (forwarded directly to npm's `min-release-age-exclude`).
28
39
  */
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
- };
40
+ export type RecentDepsAllowList = ReadonlyArray<string>;
66
41
  /**
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.
42
+ * Injectable IO used by {@link resolveRegenExcludes}. Defaults to real implementations; overridden
43
+ * in tests so the orchestration can be exercised without touching the filesystem.
70
44
  */
71
- export type RecentDepsIo = {
45
+ export type RegenExcludesIo = {
72
46
  fileExists: (filePath: string) => Promise<boolean>;
73
47
  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
48
  };
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
49
  export declare function fileExists(filePath: string): Promise<boolean>;
93
50
  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;
51
+ /** The real (filesystem) IO used by {@link resolveRegenExcludes}. */
52
+ export declare const defaultRegenExcludesIo: RegenExcludesIo;
96
53
  /**
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.
54
+ * Loads the deps-regen allow list and returns the deduped package names / glob patterns that should
55
+ * bypass `min-release-age` during the regen install. A missing explicit config (from `--config`)
56
+ * throws; a missing default config is silently skipped (returns `[]`). Unsafe entries (which can't
57
+ * be safely interpolated into a shell command) throw rather than being silently dropped.
100
58
  */
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;
59
+ export declare function resolveRegenExcludes({ configPath, configIsExplicit, io, }: {
153
60
  configPath: string;
154
61
  /**
155
62
  * Whether `configPath` came from an explicit `--config` flag. A missing explicit config throws,
156
63
  * while a missing default config is silently skipped.
157
64
  */
158
65
  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>;
66
+ io?: RegenExcludesIo | undefined;
67
+ }): Promise<string[]>;
182
68
  /**
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.
69
+ * Builds the `--min-release-age-exclude='<pattern>'` flags appended to the regen `npm i` so the
70
+ * allow-listed packages can install their newest versions even while a release-age window is set.
71
+ * Each pattern is single-quoted; combined with {@link isSafeExcludePattern} validation, this
72
+ * prevents shell injection from config values.
187
73
  */
188
- export declare function restoreOriginalPackageJsonVersions({ violators, updateVersions, }: {
189
- violators: ReadonlyArray<RecentDepViolator>;
190
- updateVersions?: RecentDepsIo['updatePackageJsonVersions'] | undefined;
191
- }): Promise<void>;
74
+ export declare function buildMinReleaseAgeExcludeFlags(patterns: ReadonlyArray<string>): string[];
@@ -1,20 +1,27 @@
1
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';
2
+ import { removeDuplicates, wrapInTry } from '@augment-vir/common';
4
3
  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';
4
+ import { stat } from 'node:fs/promises';
5
+ import { join, resolve } from 'node:path';
9
6
  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);
7
+ /**
8
+ * All `node_modules` directories deleted before a regen install: one per mono-repo package plus the
9
+ * mono-repo root. For a single (non-mono) package, `monoRepoPackages` is empty so only the root is
10
+ * returned.
11
+ */
12
+ export function listRegenNodeModulesDirs({ monoRepoRootPath, monoRepoPackages, }) {
13
+ return [
14
+ ...monoRepoPackages.map((monoPackage) => join(monoRepoRootPath, monoPackage.relativePath, 'node_modules')),
15
+ join(monoRepoRootPath, 'node_modules'),
16
+ ];
17
+ }
18
+ /**
19
+ * Whether an allow-list entry is safe to interpolate (single-quoted) into a shell command. Allows
20
+ * npm package names and `minimatch` glob patterns (the `*` wildcard) while rejecting anything that
21
+ * could smuggle shell metacharacters or quotes out of an (untrusted) config file.
22
+ */
23
+ export function isSafeExcludePattern(pattern) {
24
+ return /^@?[a-z0-9*][a-z0-9._*-]*(\/[a-z0-9*][a-z0-9._*-]*)?$/i.test(pattern);
18
25
  }
19
26
  /**
20
27
  * Pulls an optional `--config <path>` (or `--config=<path>`) flag out of the raw `deps regen` args,
@@ -71,27 +78,6 @@ export function resolveRegenConfigPath({ configValue, cwd, monoRepoRootPath, })
71
78
  ? resolve(cwd, configValue)
72
79
  : join(monoRepoRootPath, defaultDepsRegenConfigRelativePath);
73
80
  }
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
81
  export async function fileExists(filePath) {
96
82
  return await wrapInTry(async () => {
97
83
  await stat(filePath);
@@ -105,269 +91,22 @@ export async function loadAllowList(configPath) {
105
91
  inputPath: configPath,
106
92
  }, JsModuleType.Esm, (loadedConfig) => {
107
93
  const list = loadedConfig.depsRegenAllowList ?? loadedConfig.default;
108
- return check.isArray(list) ? list : undefined;
94
+ return check.isArray(list) ? list.filter(check.isString) : undefined;
109
95
  });
110
96
  }
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 = {
97
+ /** The real (filesystem) IO used by {@link resolveRegenExcludes}. */
98
+ export const defaultRegenExcludesIo = {
351
99
  fileExists,
352
100
  loadAllowList,
353
- listDirectDeps: listAllDirectNpmDeps,
354
- queryRegistry,
355
- queryInRangeVersions,
356
- updatePackageJsonVersions,
357
101
  };
358
102
  /**
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.
103
+ * Loads the deps-regen allow list and returns the deduped package names / glob patterns that should
104
+ * bypass `min-release-age` during the regen install. A missing explicit config (from `--config`)
105
+ * throws; a missing default config is silently skipped (returns `[]`). Unsafe entries (which can't
106
+ * be safely interpolated into a shell command) throw rather than being silently dropped.
365
107
  */
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))) {
108
+ export async function resolveRegenExcludes({ configPath, configIsExplicit, io = defaultRegenExcludesIo, }) {
109
+ if (!(await io.fileExists(configPath))) {
371
110
  if (configIsExplicit) {
372
111
  throw new VirmatorNoTraceError(`deps-regen config file not found: ${configPath}`);
373
112
  }
@@ -377,98 +116,18 @@ export async function prepareRecentDepDowngrades({ monoRepoRootPath, configPath,
377
116
  if (!allowList?.length) {
378
117
  return [];
379
118
  }
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
- });
119
+ const unsafePatterns = allowList.filter((pattern) => !isSafeExcludePattern(pattern));
120
+ if (unsafePatterns.length) {
121
+ throw new VirmatorNoTraceError(`deps-regen allow list contains unsafe package patterns: ${unsafePatterns.join(', ')}`);
122
+ }
123
+ return removeDuplicates([...allowList]);
457
124
  }
458
125
  /**
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.
126
+ * Builds the `--min-release-age-exclude='<pattern>'` flags appended to the regen `npm i` so the
127
+ * allow-listed packages can install their newest versions even while a release-age window is set.
128
+ * Each pattern is single-quoted; combined with {@link isSafeExcludePattern} validation, this
129
+ * prevents shell injection from config values.
463
130
  */
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
- });
131
+ export function buildMinReleaseAgeExcludeFlags(patterns) {
132
+ return patterns.map((pattern) => `--min-release-age-exclude='${pattern}'`);
474
133
  }
@@ -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.24.0",
4
4
  "description": "Default TS deps plugin for virmator.",
5
5
  "keywords": [
6
6
  "virmator",
@@ -38,7 +38,7 @@
38
38
  "@augment-vir/common": "^31.71.3",
39
39
  "@augment-vir/node": "^31.71.3",
40
40
  "@npm/types": "^2.1.0",
41
- "@virmator/core": "^14.23.1",
41
+ "@virmator/core": "^14.24.0",
42
42
  "date-vir": "^8.3.2",
43
43
  "mri": "^1.2.0"
44
44
  },