knip 6.44.2 → 6.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/dist/ConfigurationChief.d.ts +23 -1033
  2. package/dist/ConfigurationChief.js +71 -15
  3. package/dist/DependencyDeputy.d.ts +10 -6
  4. package/dist/DependencyDeputy.js +51 -27
  5. package/dist/IssueCollector.d.ts +14 -11
  6. package/dist/IssueCollector.js +25 -20
  7. package/dist/IssueFixer.js +1 -1
  8. package/dist/PackagePeeker.d.ts +6 -0
  9. package/dist/PackagePeeker.js +43 -14
  10. package/dist/ProjectPrincipal.d.ts +6 -3
  11. package/dist/ProjectPrincipal.js +83 -32
  12. package/dist/WorkspaceWorker.d.ts +5 -1
  13. package/dist/WorkspaceWorker.js +39 -22
  14. package/dist/binaries/bash-parser.js +1 -7
  15. package/dist/binaries/command.d.ts +3 -3
  16. package/dist/binaries/command.js +6 -2
  17. package/dist/binaries/fallback.js +1 -1
  18. package/dist/binaries/plugins.d.ts +4 -1
  19. package/dist/binaries/plugins.js +66 -18
  20. package/dist/binaries/resolvers/npm.js +7 -5
  21. package/dist/binaries/resolvers/npx.js +8 -40
  22. package/dist/binaries/util.d.ts +13 -1
  23. package/dist/binaries/util.js +35 -1
  24. package/dist/cli.js +10 -84
  25. package/dist/configuration-hints.d.ts +16 -0
  26. package/dist/configuration-hints.js +64 -0
  27. package/dist/constants.d.ts +2 -1
  28. package/dist/constants.js +2 -0
  29. package/dist/graph/SubpathReferences.d.ts +33 -0
  30. package/dist/graph/SubpathReferences.js +114 -0
  31. package/dist/graph/analyze.d.ts +4 -1
  32. package/dist/graph/analyze.js +16 -5
  33. package/dist/graph/build.d.ts +3 -1
  34. package/dist/graph/build.js +47 -23
  35. package/dist/graph-explorer/operations/resolve-export-origins.js +1 -1
  36. package/dist/plugins/angular/index.js +10 -17
  37. package/dist/plugins/aws-cdk/index.d.ts +3 -0
  38. package/dist/plugins/aws-cdk/index.js +32 -0
  39. package/dist/plugins/aws-cdk/types.d.ts +5 -0
  40. package/dist/plugins/aws-cdk/types.js +1 -0
  41. package/dist/plugins/babel/index.d.ts +1 -1
  42. package/dist/plugins/babel/index.js +19 -5
  43. package/dist/plugins/bun/index.js +8 -7
  44. package/dist/plugins/c8/index.js +17 -4
  45. package/dist/plugins/changesets/index.js +3 -2
  46. package/dist/plugins/commitizen/index.js +6 -3
  47. package/dist/plugins/commitlint/index.js +10 -11
  48. package/dist/plugins/cypress/index.js +4 -2
  49. package/dist/plugins/danger/index.js +1 -1
  50. package/dist/plugins/docusaurus/helpers.js +6 -6
  51. package/dist/plugins/docusaurus/index.js +2 -2
  52. package/dist/plugins/electron-forge/index.js +2 -2
  53. package/dist/plugins/electron-vite/index.js +2 -2
  54. package/dist/plugins/eleventy/index.js +3 -2
  55. package/dist/plugins/eslint/helpers.js +4 -3
  56. package/dist/plugins/eslint/resolveFromAST.js +2 -2
  57. package/dist/plugins/evalite/index.d.ts +3 -0
  58. package/dist/plugins/evalite/index.js +26 -0
  59. package/dist/plugins/flue/index.js +2 -2
  60. package/dist/plugins/github-action/index.js +2 -2
  61. package/dist/plugins/github-actions/index.js +2 -2
  62. package/dist/plugins/graphql-codegen/index.js +13 -9
  63. package/dist/plugins/index.d.ts +5 -0
  64. package/dist/plugins/index.js +10 -0
  65. package/dist/plugins/jest/index.js +5 -5
  66. package/dist/plugins/knex/index.js +2 -2
  67. package/dist/plugins/laravel-vite-plugin/resolveFromAST.js +2 -2
  68. package/dist/plugins/lunaria/index.js +5 -2
  69. package/dist/plugins/markdownlint/index.js +8 -2
  70. package/dist/plugins/marko/index.js +2 -2
  71. package/dist/plugins/marko/taglibs.d.ts +1 -1
  72. package/dist/plugins/marko/taglibs.js +4 -28
  73. package/dist/plugins/mdx/index.d.ts +2 -1
  74. package/dist/plugins/mdx/index.js +7 -4
  75. package/dist/plugins/mdxlint/index.js +18 -15
  76. package/dist/plugins/mikro-orm/index.d.ts +3 -0
  77. package/dist/plugins/mikro-orm/index.js +77 -0
  78. package/dist/plugins/mikro-orm/types.d.ts +21 -0
  79. package/dist/plugins/mikro-orm/types.js +1 -0
  80. package/dist/plugins/msw/index.js +6 -3
  81. package/dist/plugins/msw/types.d.ts +1 -1
  82. package/dist/plugins/netlify/index.js +7 -3
  83. package/dist/plugins/next/index.js +63 -9
  84. package/dist/plugins/next/types.d.ts +5 -0
  85. package/dist/plugins/next-mdx/resolveFromAST.js +15 -10
  86. package/dist/plugins/nitro/index.js +5 -6
  87. package/dist/plugins/node/index.js +4 -4
  88. package/dist/plugins/npm-package-json-lint/index.js +10 -3
  89. package/dist/plugins/nuxt/index.js +18 -10
  90. package/dist/plugins/nuxt/types.d.ts +4 -0
  91. package/dist/plugins/nx/index.js +6 -3
  92. package/dist/plugins/openclaw/index.js +11 -11
  93. package/dist/plugins/oxlint/index.js +2 -2
  94. package/dist/plugins/payload/index.js +1 -1
  95. package/dist/plugins/playwright/index.js +3 -3
  96. package/dist/plugins/pm2/index.js +7 -7
  97. package/dist/plugins/prettier/index.js +2 -1
  98. package/dist/plugins/prisma/index.js +2 -2
  99. package/dist/plugins/quasar/resolveFromAST.js +14 -9
  100. package/dist/plugins/react-router/index.js +2 -2
  101. package/dist/plugins/release-it/index.js +6 -2
  102. package/dist/plugins/remix/index.js +3 -3
  103. package/dist/plugins/retry-cli/index.d.ts +3 -0
  104. package/dist/plugins/retry-cli/index.js +14 -0
  105. package/dist/plugins/rollup/index.js +1 -4
  106. package/dist/plugins/rstest/index.js +3 -3
  107. package/dist/plugins/semantic-release/index.js +3 -3
  108. package/dist/plugins/serverless-framework/index.js +10 -8
  109. package/dist/plugins/solidjs-vite-plugin/resolveFromAST.js +2 -2
  110. package/dist/plugins/stencil/resolveFromAST.js +5 -5
  111. package/dist/plugins/stryker/index.js +2 -2
  112. package/dist/plugins/swc/index.js +4 -3
  113. package/dist/plugins/tailwind/index.js +2 -2
  114. package/dist/plugins/tanstack-router/index.js +2 -2
  115. package/dist/plugins/ts-node/index.js +6 -1
  116. package/dist/plugins/turbo/index.js +3 -3
  117. package/dist/plugins/typedoc/index.js +2 -2
  118. package/dist/plugins/typescript/content-mappers.d.ts +1 -1
  119. package/dist/plugins/typescript/index.js +6 -9
  120. package/dist/plugins/varlock/scan.js +1 -1
  121. package/dist/plugins/vite/helpers.d.ts +1 -0
  122. package/dist/plugins/vite/helpers.js +13 -3
  123. package/dist/plugins/vite/index.js +5 -2
  124. package/dist/plugins/vite-plugin-pwa/resolveFromAST.js +2 -2
  125. package/dist/plugins/vitest/index.js +14 -16
  126. package/dist/plugins/vue/index.js +1 -1
  127. package/dist/plugins/web-test-runner/index.d.ts +3 -0
  128. package/dist/plugins/web-test-runner/index.js +86 -0
  129. package/dist/plugins/wrangler/index.js +3 -3
  130. package/dist/plugins/yarn/index.js +5 -5
  131. package/dist/plugins.js +2 -5
  132. package/dist/reporters/github-actions.js +3 -7
  133. package/dist/reporters/json.d.ts +1 -0
  134. package/dist/reporters/json.js +1 -0
  135. package/dist/reporters/util/configuration-hints.d.ts +3 -1
  136. package/dist/reporters/util/configuration-hints.js +40 -21
  137. package/dist/reporters/util/util.d.ts +1 -1
  138. package/dist/run-cli.d.ts +2 -0
  139. package/dist/run-cli.js +82 -0
  140. package/dist/run.js +12 -0
  141. package/dist/session/incremental.d.ts +1 -0
  142. package/dist/session/incremental.js +1 -0
  143. package/dist/session/watch.js +2 -1
  144. package/dist/types/PluginNames.d.ts +2 -2
  145. package/dist/types/PluginNames.js +5 -0
  146. package/dist/types/args.d.ts +3 -1
  147. package/dist/types/config.d.ts +17 -10
  148. package/dist/types/configuration.d.ts +45 -0
  149. package/dist/types/configuration.js +1 -0
  150. package/dist/types/issues.d.ts +4 -0
  151. package/dist/types/module-graph.d.ts +1 -0
  152. package/dist/types/options.d.ts +1 -0
  153. package/dist/types/package-json.d.ts +3 -8
  154. package/dist/types/workspace.d.ts +1 -0
  155. package/dist/typescript/get-imports-and-exports.js +18 -6
  156. package/dist/typescript/resolve-module-names.js +7 -45
  157. package/dist/typescript/visitors/calls.d.ts +1 -1
  158. package/dist/typescript/visitors/calls.js +14 -10
  159. package/dist/typescript/visitors/exports.js +16 -26
  160. package/dist/typescript/visitors/imports.d.ts +2 -1
  161. package/dist/typescript/visitors/imports.js +41 -24
  162. package/dist/typescript/visitors/members.d.ts +1 -1
  163. package/dist/typescript/visitors/members.js +38 -24
  164. package/dist/typescript/visitors/shadow.d.ts +2 -0
  165. package/dist/typescript/visitors/shadow.js +25 -0
  166. package/dist/typescript/visitors/walk.d.ts +20 -12
  167. package/dist/typescript/visitors/walk.js +78 -48
  168. package/dist/util/Performance.d.ts +25 -3
  169. package/dist/util/Performance.js +51 -27
  170. package/dist/util/cli-arguments.d.ts +2 -1
  171. package/dist/util/cli-arguments.js +4 -2
  172. package/dist/util/create-input-handler.js +138 -119
  173. package/dist/util/create-options.d.ts +4 -2071
  174. package/dist/util/create-options.js +6 -4
  175. package/dist/util/create-workspace-graph.js +2 -1
  176. package/dist/util/errors.d.ts +5 -2
  177. package/dist/util/errors.js +11 -18
  178. package/dist/util/fs.js +4 -2
  179. package/dist/util/input.d.ts +2 -2
  180. package/dist/util/input.js +2 -2
  181. package/dist/util/is-plugin-name.d.ts +2 -0
  182. package/dist/util/is-plugin-name.js +3 -0
  183. package/dist/util/jiti.d.ts +2 -1
  184. package/dist/util/jiti.js +10 -3
  185. package/dist/util/load-config.d.ts +1 -1
  186. package/dist/util/load-config.js +3 -2
  187. package/dist/util/loader.js +3 -2
  188. package/dist/util/map-workspaces.js +23 -1
  189. package/dist/util/module-graph.js +1 -0
  190. package/dist/util/modules.d.ts +2 -0
  191. package/dist/util/modules.js +78 -0
  192. package/dist/util/package-json.d.ts +12 -5
  193. package/dist/util/package-json.js +54 -26
  194. package/dist/util/parse-and-convert-gitignores.d.ts +2 -2
  195. package/dist/util/parse-and-convert-gitignores.js +5 -5
  196. package/dist/util/parse-configuration.d.ts +2 -0
  197. package/dist/util/parse-configuration.js +66 -0
  198. package/dist/util/plugin.js +8 -12
  199. package/dist/util/resolve.d.ts +1 -0
  200. package/dist/util/resolve.js +3 -2
  201. package/dist/util/scripts.d.ts +0 -5
  202. package/dist/util/scripts.js +1 -32
  203. package/dist/util/to-source-path.d.ts +4 -1
  204. package/dist/util/to-source-path.js +2 -2
  205. package/dist/util/unhandled-rejection.d.ts +8 -0
  206. package/dist/util/unhandled-rejection.js +29 -0
  207. package/dist/util/validation.d.ts +11 -0
  208. package/dist/util/validation.js +68 -0
  209. package/dist/util/watch.d.ts +3 -1
  210. package/dist/util/watch.js +5 -2
  211. package/dist/version.d.ts +1 -1
  212. package/dist/version.js +1 -1
  213. package/package.json +6 -7
  214. package/schema.json +34 -0
  215. package/dist/schema/configuration.d.ts +0 -3103
  216. package/dist/schema/configuration.js +0 -94
  217. package/dist/schema/plugins.d.ts +0 -1019
  218. package/dist/schema/plugins.js +0 -215
@@ -1,33 +1,37 @@
1
+ import { parse as parseScript } from 'unbash';
1
2
  import parseArgs from '../util/parse-args.js';
2
3
  import { pluginArgsMap } from '../plugins.js';
3
4
  import { compact } from '../util/array.js';
4
5
  import { toBinary, toConfig, toDeferResolve, toDeferResolveEntry, toEntry } from '../util/input.js';
5
6
  import { extractBinary, isInNodeModulesBin } from '../util/modules.js';
6
7
  import { dirname } from '../util/path.js';
7
- import { isWrapper as isFallbackWrapper, resolve as fallbackResolve } from './fallback.js';
8
- import { toCommandBinary, toWordArgs } from './util.js';
8
+ import { collectCommands, getCommandWords } from '../util/scripts.js';
9
+ import { isWrapper as isFallbackWrapper, resolve as fallbackResolve, spawningBinaries } from './fallback.js';
10
+ import { spawningArgs, toCommandBinary, toScript, toWordArgs } from './util.js';
9
11
  const isGlobLikeMatch = /(^!|[*+\\(|{^$])/;
10
12
  const isGlobLike = (value) => isGlobLikeMatch.test(value);
11
13
  const nodeLoadersArgs = { import: ['r', 'experimental-loader', 'require', 'loader'] };
12
14
  export const isWrapper = (binary) => !!pluginArgsMap.get(binary)?.[1].fromArgs || isFallbackWrapper(binary);
13
- export const resolve = (binary, words, options) => {
14
- const { cwd, fromArgs, containingFilePath, manifest } = options;
15
- const [pluginName, pluginArgs] = pluginArgsMap.get(binary) ?? [];
16
- if (!pluginArgs)
17
- return fallbackResolve(binary, words, options);
18
- const inputOpts = {};
19
- if (cwd && dirname(containingFilePath) !== cwd)
20
- Object.assign(inputOpts, { dir: cwd });
15
+ const spawningPluginArgs = { fromArgs: spawningArgs };
16
+ const toArgs = (pluginArgs, words) => {
21
17
  const values = [];
22
18
  for (const word of words)
23
19
  values.push(word.value);
24
- const args = typeof pluginArgs.args === 'function' ? pluginArgs.args(values) : values;
25
- const parsed = parseArgs(args, {
26
- string: [
27
- ...(pluginArgs.nodeImportArgs ? ['import'] : []),
28
- ...(pluginArgs.config === true ? ['config'] : []),
29
- ...(pluginArgs.string ?? []),
30
- ],
20
+ return typeof pluginArgs.args === 'function' ? pluginArgs.args(values) : values;
21
+ };
22
+ const parse = (pluginArgs, args) => {
23
+ const config = pluginArgs.config === true ? ['config'] : pluginArgs.config || [];
24
+ const string = [
25
+ ...(pluginArgs.nodeImportArgs ? ['import'] : []),
26
+ ...(pluginArgs.resolve ?? []),
27
+ ...(pluginArgs.string ?? []),
28
+ ];
29
+ for (const value of config)
30
+ string.push(typeof value === 'string' ? value : value[0]);
31
+ if (Array.isArray(pluginArgs.fromArgs))
32
+ string.push(...pluginArgs.fromArgs);
33
+ return parseArgs(args, {
34
+ string,
31
35
  boolean: ['quiet', 'verbose', 'watch', ...(pluginArgs.boolean ?? [])],
32
36
  alias: {
33
37
  ...(pluginArgs.nodeImportArgs ? nodeLoadersArgs : {}),
@@ -36,6 +40,50 @@ export const resolve = (binary, words, options) => {
36
40
  },
37
41
  '--': true,
38
42
  });
43
+ };
44
+ export const getWrappedCommand = (binary, words, cwd = process.cwd()) => {
45
+ const pluginArgs = pluginArgsMap.get(binary)?.[1] ?? (spawningBinaries.includes(binary) ? spawningPluginArgs : undefined);
46
+ const fromArgs = pluginArgs?.fromArgs;
47
+ if (!pluginArgs || typeof fromArgs !== 'function')
48
+ return;
49
+ const args = toArgs(pluginArgs, words);
50
+ return toWordArgs(fromArgs(parse(pluginArgs, args), args, { cwd }), words);
51
+ };
52
+ export const getScriptCommands = (script, cwd = process.cwd()) => {
53
+ if (!script)
54
+ return [];
55
+ const out = [];
56
+ try {
57
+ for (const statement of parseScript(script).commands) {
58
+ for (const node of collectCommands(statement.command)) {
59
+ const text = node.name?.value;
60
+ if (!text)
61
+ continue;
62
+ const binary = extractBinary(text);
63
+ const words = getCommandWords(node);
64
+ const command = getWrappedCommand(binary, words, cwd);
65
+ if (command?.length)
66
+ out.push(...getScriptCommands(toScript(command), cwd));
67
+ else
68
+ out.push({ binary, args: words.map(word => word.value) });
69
+ }
70
+ }
71
+ }
72
+ catch {
73
+ return [];
74
+ }
75
+ return out;
76
+ };
77
+ export const resolve = (binary, words, options) => {
78
+ const { cwd, fromArgs, containingFilePath, manifest } = options;
79
+ const [pluginName, pluginArgs] = pluginArgsMap.get(binary) ?? [];
80
+ if (!pluginArgs)
81
+ return fallbackResolve(binary, words, options);
82
+ const inputOpts = {};
83
+ if (cwd && dirname(containingFilePath) !== cwd)
84
+ Object.assign(inputOpts, { dir: cwd });
85
+ const args = toArgs(pluginArgs, words);
86
+ const parsed = parse(pluginArgs, args);
39
87
  const positionals = [];
40
88
  if (pluginArgs.positional && parsed._[0]) {
41
89
  const id = parsed._[0];
@@ -52,7 +100,7 @@ export const resolve = (binary, words, options) => {
52
100
  const resolved = compact(pluginArgs.resolve ? pluginArgs.resolve.flatMap(mapToParsedKey) : []);
53
101
  const resolvedImports = pluginArgs.nodeImportArgs && parsed.import ? [parsed.import].flat() : [];
54
102
  const resolvedFromArgs = typeof pluginArgs.fromArgs === 'function'
55
- ? fromArgs(toWordArgs(pluginArgs.fromArgs(parsed, args), words))
103
+ ? fromArgs(toWordArgs(pluginArgs.fromArgs(parsed, args, { cwd }), words))
56
104
  : Array.isArray(pluginArgs.fromArgs)
57
105
  ? fromArgs(pluginArgs.fromArgs.flatMap(mapToParsedKey).filter(Boolean))
58
106
  : [];
@@ -1,8 +1,8 @@
1
1
  import parseArgs from '../../util/parse-args.js';
2
- import { isBinary, toBinary, toDependency } from '../../util/input.js';
2
+ import { isBinary, toBinary, toDeferResolve, toDependency } from '../../util/input.js';
3
3
  import { extractBinary, isValidBinary, stripVersionFromSpecifier } from '../../util/modules.js';
4
4
  import { isInternal } from '../../util/path.js';
5
- import { argsAfter, expandScript } from '../util.js';
5
+ import { argsAfter, expandScript, npmBooleanAliases, npmBooleanFlags } from '../util.js';
6
6
  const runCommands = new Set(['run', 'run-script', 'rum', 'urn']);
7
7
  const lifecycleScripts = new Map([
8
8
  ['start', 'start'],
@@ -16,15 +16,17 @@ export const resolve = (_binary, words, options) => {
16
16
  const { fromArgs, manifest } = options;
17
17
  const parsed = parseArgs(words, {
18
18
  isStorePositions: true,
19
- boolean: ['yes', 'no', 'parseable'],
19
+ boolean: [...npmBooleanFlags, 'parseable'],
20
20
  string: ['package', 'call'],
21
- alias: { yes: 'y', parseable: 'p', call: 'c' },
21
+ alias: { ...npmBooleanAliases, parseable: 'p', call: 'c' },
22
22
  '--': true,
23
23
  });
24
24
  const [command, script] = parsed._;
25
25
  if (command === 'exec' || command === 'x') {
26
26
  const packages = parsed.package ? [parsed.package].flat() : [];
27
- const packageInputs = packages.map(specifier => toDependency(stripVersionFromSpecifier(specifier), { optional: true }));
27
+ const packageInputs = packages.map(specifier => isInternal(specifier)
28
+ ? toDeferResolve(specifier, { optional: true, dir: options.cwd })
29
+ : toDependency(stripVersionFromSpecifier(specifier), { optional: true }));
28
30
  const separator = words.findIndex(word => word.value === '--');
29
31
  const args = parsed.positionalIndices.slice(1).map(index => words[index]);
30
32
  if (separator !== -1)
@@ -1,48 +1,16 @@
1
1
  import parseArgs from '../../util/parse-args.js';
2
- import { toBinary, toDependency } from '../../util/input.js';
2
+ import { toBinary, toDeferResolve, toDependency } from '../../util/input.js';
3
3
  import { stripVersionFromSpecifier } from '../../util/modules.js';
4
4
  import { isInternal } from '../../util/path.js';
5
- import { argsFrom } from '../util.js';
5
+ import { argsFrom, npmBooleanAliases, npmBooleanFlags } from '../util.js';
6
6
  const noInstallFlags = new Set(['--no', '--no-install', '--yes=false', '--no-yes']);
7
7
  export const resolve = (_binary, words, options) => {
8
- const { fromArgs } = options;
8
+ const { fromArgs, cwd } = options;
9
+ const toPackage = (id, opts) => isInternal(id) ? toDeferResolve(id, { ...opts, dir: cwd }) : toDependency(id, opts);
9
10
  const args = {
10
11
  isStorePositions: true,
11
- boolean: [
12
- 'color',
13
- 'd',
14
- 'dangerously-allow-all-scripts',
15
- 'dd',
16
- 'ddd',
17
- 'force',
18
- 'global',
19
- 'ignore-scripts',
20
- 'include-workspace-root',
21
- 'legacy-peer-deps',
22
- 'no',
23
- 'offline',
24
- 'prefer-offline',
25
- 'prefer-online',
26
- 'progress',
27
- 'quiet',
28
- 'silent',
29
- 'strict-allow-scripts',
30
- 'timing',
31
- 'verbose',
32
- 'workspaces',
33
- 'yes',
34
- ],
35
- alias: {
36
- force: 'f',
37
- global: 'g',
38
- 'include-workspace-root': 'iwr',
39
- quiet: 'q',
40
- silent: 's',
41
- workspaces: 'ws',
42
- yes: 'y',
43
- package: 'p',
44
- call: 'c',
45
- },
12
+ boolean: npmBooleanFlags,
13
+ alias: { ...npmBooleanAliases, package: 'p', call: 'c' },
46
14
  };
47
15
  const parsed = parseArgs(words, args);
48
16
  const commandIndex = parsed.positionalIndices[0] ?? words.length;
@@ -54,11 +22,11 @@ export const resolve = (_binary, words, options) => {
54
22
  const isBinary = specifier && !packageSpecifier.includes('@') && !isInternal(specifier);
55
23
  const noInstall = words.slice(0, commandIndex).some(word => noInstallFlags.has(word.value));
56
24
  const opts = noInstall ? undefined : { optional: true };
57
- const dependency = isBinary ? toBinary(specifier, opts) : toDependency(specifier, opts);
25
+ const dependency = isBinary ? toBinary(specifier, opts) : toPackage(specifier, opts);
58
26
  const specifiers = dependency ? [dependency] : [];
59
27
  return [
60
28
  ...specifiers,
61
- ...packages.map(id => toDependency(id, { optional: true })),
29
+ ...packages.map(id => toPackage(id, { optional: true })),
62
30
  ...command,
63
31
  ...fromArgs(argsFrom(words, packageSpecifier)).slice(1),
64
32
  ];
@@ -1,12 +1,24 @@
1
1
  import type { Word } from 'unbash';
2
+ import { type ParsedArgs } from '../util/parse-args.ts';
2
3
  import type { BinaryResolverOptions, GetInputsFromScriptsOptions, ScriptArg } from '../types/config.ts';
3
4
  import { type Input } from '../util/input.ts';
4
5
  export declare const toCommandBinary: (binary: string, { optionalBinaries }: GetInputsFromScriptsOptions, inputOptions?: {
5
6
  dir?: string;
6
7
  }) => Input;
8
+ export declare const npmBooleanFlags: string[];
9
+ export declare const npmBooleanAliases: {
10
+ force: string;
11
+ global: string;
12
+ 'include-workspace-root': string;
13
+ quiet: string;
14
+ silent: string;
15
+ workspaces: string;
16
+ yes: string;
17
+ };
7
18
  export declare const toScript: (args: ScriptArg[]) => string;
8
19
  export declare const argsFrom: <T extends string | Word>(args: readonly T[], from: string) => T[];
20
+ export declare const spawningArgs: (parsed: ParsedArgs, args: string[]) => string[];
9
21
  export declare const argsAfter: <T extends string | Word>(args: readonly T[], token: string) => T[];
10
22
  export declare const toWordArgs: (values: (string | number)[], words: Word[]) => ScriptArg[];
11
23
  export declare const expandScript: (name: string, forwardedArgs: ScriptArg[], scripts: Record<string, string> | undefined, options: BinaryResolverOptions, opts?: Partial<GetInputsFromScriptsOptions>) => Input[] | undefined;
12
- export declare const parseNodeArgs: (args: string[]) => import("../util/parse-args.ts").ParsedArgs;
24
+ export declare const parseNodeArgs: (args: string[]) => ParsedArgs;
@@ -1,6 +1,39 @@
1
- import parseArgs from '../util/parse-args.js';
1
+ import parseArgs, {} from '../util/parse-args.js';
2
2
  import { toBinary } from '../util/input.js';
3
3
  export const toCommandBinary = (binary, { optionalBinaries }, inputOptions = {}) => toBinary(binary, optionalBinaries ? { ...inputOptions, optional: true } : inputOptions);
4
+ export const npmBooleanFlags = [
5
+ 'color',
6
+ 'd',
7
+ 'dangerously-allow-all-scripts',
8
+ 'dd',
9
+ 'ddd',
10
+ 'force',
11
+ 'global',
12
+ 'ignore-scripts',
13
+ 'include-workspace-root',
14
+ 'legacy-peer-deps',
15
+ 'no',
16
+ 'offline',
17
+ 'prefer-offline',
18
+ 'prefer-online',
19
+ 'progress',
20
+ 'quiet',
21
+ 'silent',
22
+ 'strict-allow-scripts',
23
+ 'timing',
24
+ 'verbose',
25
+ 'workspaces',
26
+ 'yes',
27
+ ];
28
+ export const npmBooleanAliases = {
29
+ force: 'f',
30
+ global: 'g',
31
+ 'include-workspace-root': 'iwr',
32
+ quiet: 'q',
33
+ silent: 's',
34
+ workspaces: 'ws',
35
+ yes: 'y',
36
+ };
4
37
  const valueOf = (arg) => (typeof arg === 'string' ? arg : arg.value);
5
38
  export const toScript = (args) => {
6
39
  const parts = [];
@@ -15,6 +48,7 @@ export const toScript = (args) => {
15
48
  return parts.join(' ');
16
49
  };
17
50
  export const argsFrom = (args, from) => args.slice(args.findIndex(arg => valueOf(arg) === from));
51
+ export const spawningArgs = (parsed, args) => parsed._[0] ? argsFrom(args, parsed._[0]) : (parsed['--'] ?? []);
18
52
  export const argsAfter = (args, token) => {
19
53
  const index = args.findIndex(arg => valueOf(arg) === token);
20
54
  return index === -1 ? [] : args.slice(index + 1).filter(arg => valueOf(arg) !== '--');
package/dist/cli.js CHANGED
@@ -1,15 +1,5 @@
1
- import { fix } from './IssueFixer.js';
2
- import { run } from './run.js';
3
1
  import parseArgs, { helpText } from './util/cli-arguments.js';
4
- import { createOptions } from './util/create-options.js';
5
- import { getKnownErrors, hasErrorCause, isConfigurationError, isKnownError, isLoaderError, isModuleNotFoundError, } from './util/errors.js';
6
- import { logError } from './util/log.js';
7
- import { perfObserver } from './util/Performance.js';
8
- import { createPreprocessor, toReporterOptions } from './util/preprocessor.js';
9
- import { runReporters } from './util/reporter.js';
10
- import { prettyMilliseconds } from './util/string.js';
11
2
  import { version } from './version.js';
12
- import { watchSession } from './session/watch.js';
13
3
  let args = {};
14
4
  try {
15
5
  args = parseArgs();
@@ -22,77 +12,13 @@ catch (error) {
22
12
  }
23
13
  throw error;
24
14
  }
25
- const main = async () => {
26
- try {
27
- if (args.help) {
28
- console.log(helpText);
29
- process.exit(0);
30
- }
31
- if (args.version) {
32
- console.log(version);
33
- process.exit(0);
34
- }
35
- const options = await createOptions({ args });
36
- if (options.isWatch) {
37
- await watchSession(options);
38
- return;
39
- }
40
- const { results } = await run(options);
41
- if (options.isWatch || options.isTrace)
42
- return;
43
- const preprocess = await createPreprocessor(options.preprocessor);
44
- const finalData = await preprocess(toReporterOptions(options, results, args));
45
- if (options.isFix)
46
- await fix(finalData.issues, finalData.counters, options);
47
- await runReporters(args.reporter ?? ['symbols'], args['output-file'] ?? [], finalData);
48
- const totalErrorCount = Object.keys(finalData.report)
49
- .filter(reportGroup => finalData.report[reportGroup] && options.rules[reportGroup] === 'error')
50
- .reduce((errorCount, reportGroup) => errorCount + finalData.counters[reportGroup], 0);
51
- if (perfObserver.isEnabled)
52
- await perfObserver.finalize();
53
- if (perfObserver.isTimerifyFunctions)
54
- console.log(`\n${perfObserver.getTimerifiedFunctionsTable()}`);
55
- if (perfObserver.isMemoryUsageEnabled && !args['memory-realtime'])
56
- console.log(`\n${perfObserver.getMemoryUsageTable()}`);
57
- if (perfObserver.isEnabled || perfObserver.isDurationEnabled) {
58
- const duration = perfObserver.getCurrentDurationInMs();
59
- console.log('\nTotal running time:', prettyMilliseconds(duration));
60
- perfObserver.reset();
61
- }
62
- if (results.hasConfigLoadErrors) {
63
- process.exitCode = 2;
64
- return;
65
- }
66
- if (!args['no-exit-code'] &&
67
- (totalErrorCount > options.maxIssues ||
68
- (!options.isDisableConfigHints &&
69
- options.isTreatConfigHintsAsErrors &&
70
- finalData.configurationHints.length > 0) ||
71
- (!options.isDisableTagHints && options.isTreatTagHintsAsErrors && finalData.tagHints.size > 0))) {
72
- process.exitCode = 1;
73
- return;
74
- }
75
- }
76
- catch (error) {
77
- process.exitCode = 2;
78
- if (!args.debug && error instanceof Error && isKnownError(error)) {
79
- const knownErrors = getKnownErrors(error);
80
- for (const knownError of knownErrors)
81
- logError(knownError.message);
82
- if (hasErrorCause(knownErrors[0])) {
83
- console.error('Reason:', knownErrors[0].cause.message);
84
- if (isModuleNotFoundError(knownErrors[0].cause))
85
- console.log('Module load error? Visit https://knip.dev/reference/known-issues');
86
- if (isLoaderError(knownErrors[0]))
87
- console.log('Configuration file load error? Visit https://knip.dev/reference/known-issues');
88
- }
89
- if (isConfigurationError(knownErrors[0]))
90
- console.log('\nRun `knip --help` or visit https://knip.dev for help');
91
- process.exitCode = 2;
92
- return;
93
- }
94
- throw error;
95
- }
96
- process.exitCode = 0;
97
- };
98
- await main();
15
+ if (args.help) {
16
+ console.log(helpText);
17
+ process.exit(0);
18
+ }
19
+ if (args.version) {
20
+ console.log(version);
21
+ process.exit(0);
22
+ }
23
+ const { runCLI } = await import('./run-cli.js');
24
+ await runCLI(args);
@@ -0,0 +1,16 @@
1
+ import type { ConfigurationHint } from './types/issues.ts';
2
+ export type UnusedIgnorePattern = {
3
+ hints: ConfigurationHint[];
4
+ isMatch: (path: string) => boolean;
5
+ };
6
+ interface ReasonContext {
7
+ cwd: string;
8
+ filePaths: Iterable<string>[];
9
+ isGitIgnored: (filePath: string) => boolean;
10
+ }
11
+ interface SettleContext {
12
+ countWorkspaces: (configKey: string) => number;
13
+ }
14
+ export declare const getUnusedIgnorePatternHints: (patterns: UnusedIgnorePattern[], context: ReasonContext) => ConfigurationHint[];
15
+ export declare const settleConfigurationHints: (candidates: Iterable<ConfigurationHint>, context: SettleContext) => ConfigurationHint[];
16
+ export {};
@@ -0,0 +1,64 @@
1
+ import picomatch from 'picomatch';
2
+ import { ROOT_WORKSPACE_NAME } from './constants.js';
3
+ import { join, relative } from './util/path.js';
4
+ const isWorkspaceSpecificHint = (hint) => hint.type === 'project-extension-unregistered' || hint.type === 'project-extension-excluded';
5
+ export const getUnusedIgnorePatternHints = (patterns, context) => {
6
+ const hints = [];
7
+ if (patterns.length === 0)
8
+ return hints;
9
+ const reasons = new Map();
10
+ const pending = new Set(patterns);
11
+ for (const paths of context.filePaths) {
12
+ for (const filePath of paths) {
13
+ if (pending.size === 0)
14
+ break;
15
+ const relativePath = relative(context.cwd, filePath);
16
+ for (const pattern of pending) {
17
+ if (pattern.isMatch(relativePath)) {
18
+ reasons.set(pattern, 'no-issues');
19
+ pending.delete(pattern);
20
+ }
21
+ }
22
+ }
23
+ }
24
+ for (const pattern of patterns) {
25
+ for (const hint of pattern.hints) {
26
+ let reason = reasons.get(pattern);
27
+ if (!reason) {
28
+ const base = picomatch.scan(String(hint.identifier)).base;
29
+ const isIgnored = base && context.isGitIgnored(join(context.cwd, hint.workspaceName ?? '', base));
30
+ reason = isIgnored ? 'gitignored' : 'no-matches';
31
+ }
32
+ hints.push({ ...hint, reason });
33
+ }
34
+ }
35
+ return hints;
36
+ };
37
+ export const settleConfigurationHints = (candidates, context) => {
38
+ const groups = new Map();
39
+ for (const hint of candidates) {
40
+ const key = `${hint.configKey ?? hint.workspaceName}::${hint.type}::${hint.identifier}`;
41
+ const group = groups.get(key);
42
+ if (group) {
43
+ if (hint.workspaceName)
44
+ group.workspaces.add(hint.workspaceName);
45
+ }
46
+ else {
47
+ groups.set(key, { hint, workspaces: new Set(hint.workspaceName ? [hint.workspaceName] : []) });
48
+ }
49
+ }
50
+ const coverage = new Map();
51
+ const hints = [];
52
+ for (const { hint, workspaces } of groups.values()) {
53
+ const { configKey } = hint;
54
+ if (configKey && configKey !== ROOT_WORKSPACE_NAME && !isWorkspaceSpecificHint(hint)) {
55
+ let count = coverage.get(configKey);
56
+ if (count === undefined)
57
+ coverage.set(configKey, (count = context.countWorkspaces(configKey)));
58
+ if (workspaces.size < count)
59
+ continue;
60
+ }
61
+ hints.push(hint);
62
+ }
63
+ return hints;
64
+ };
@@ -17,9 +17,10 @@ export declare const IGNORED_DEPENDENCIES: Set<string>;
17
17
  export declare const IGNORED_RUNTIME_DEPENDENCIES: Set<string>;
18
18
  export declare const FOREIGN_FILE_EXTENSIONS: Set<string>;
19
19
  export declare const IGNORE_DEFINITELY_TYPED: Set<string>;
20
- export declare const ISSUE_TYPES: readonly ['files', 'dependencies', 'devDependencies', 'optionalPeerDependencies', 'unlisted', 'binaries', 'unresolved', 'exports', 'nsExports', 'types', 'nsTypes', 'enumMembers', 'namespaceMembers', 'duplicates', 'catalog', 'catalogReferences', 'cycles'];
20
+ export declare const ISSUE_TYPES: readonly ['files', 'subpaths', 'dependencies', 'devDependencies', 'optionalPeerDependencies', 'unlisted', 'binaries', 'unresolved', 'exports', 'nsExports', 'types', 'nsTypes', 'enumMembers', 'namespaceMembers', 'duplicates', 'catalog', 'catalogReferences', 'cycles'];
21
21
  export declare const ISSUE_TYPE_TITLE: {
22
22
  readonly files: 'Unused files';
23
+ readonly subpaths: 'Unused subpaths';
23
24
  readonly dependencies: 'Unused dependencies';
24
25
  readonly devDependencies: 'Unused devDependencies';
25
26
  readonly optionalPeerDependencies: 'Referenced optional peerDependencies';
package/dist/constants.js CHANGED
@@ -245,6 +245,7 @@ export const IGNORE_DEFINITELY_TYPED = new Set([
245
245
  ]);
246
246
  export const ISSUE_TYPES = [
247
247
  'files',
248
+ 'subpaths',
248
249
  'dependencies',
249
250
  'devDependencies',
250
251
  'optionalPeerDependencies',
@@ -264,6 +265,7 @@ export const ISSUE_TYPES = [
264
265
  ];
265
266
  export const ISSUE_TYPE_TITLE = {
266
267
  files: 'Unused files',
268
+ subpaths: 'Unused subpaths',
267
269
  dependencies: 'Unused dependencies',
268
270
  devDependencies: 'Unused devDependencies',
269
271
  optionalPeerDependencies: 'Referenced optional peerDependencies',
@@ -0,0 +1,33 @@
1
+ import type { ConfigurationChief, Workspace } from '../ConfigurationChief.ts';
2
+ import type { ProjectPrincipal } from '../ProjectPrincipal.ts';
3
+ import type { Issue } from '../types/issues.ts';
4
+ import type { Input } from '../util/input.ts';
5
+ import type { WorkspacePackageTargetHandler } from '../util/to-source-path.ts';
6
+ interface SubpathReferencesOptions {
7
+ chief: ConfigurationChief;
8
+ principal: ProjectPrincipal;
9
+ workspaces: Workspace[];
10
+ findWorkspacePackageTarget: WorkspacePackageTargetHandler;
11
+ isGitIgnored: (filePath: string) => boolean;
12
+ }
13
+ export declare class SubpathReferences {
14
+ private chief;
15
+ private principal;
16
+ private workspaces;
17
+ private findWorkspacePackageTarget;
18
+ private isGitIgnored;
19
+ private extensions;
20
+ private isActive;
21
+ private inputs;
22
+ private seen;
23
+ private referenced;
24
+ constructor({ chief, principal, workspaces, findWorkspacePackageTarget, isGitIgnored }: SubpathReferencesOptions);
25
+ private isSubpathSpecifier;
26
+ addInput(input: Input, owner: string): void;
27
+ add(specifier: string, containingFilePath: string): void;
28
+ release(owner: string): void;
29
+ reset(): void;
30
+ getIssues(): Issue[];
31
+ private hasModuleTarget;
32
+ }
33
+ export {};
@@ -0,0 +1,114 @@
1
+ import { DEFAULT_EXTENSIONS } from '../constants.js';
2
+ import { PackagePeeker } from '../PackagePeeker.js';
3
+ import { isFile } from '../util/fs.js';
4
+ import { getPackageNameFromModuleSpecifier, sanitizeSpecifier } from '../util/modules.js';
5
+ import { getEntriesFromExports, getExportEntries, getPackageTargetPaths } from '../util/package-json.js';
6
+ import { extname, join } from '../util/path.js';
7
+ export class SubpathReferences {
8
+ chief;
9
+ principal;
10
+ workspaces;
11
+ findWorkspacePackageTarget;
12
+ isGitIgnored;
13
+ extensions = [];
14
+ isActive = false;
15
+ inputs = new Map();
16
+ seen = new Set();
17
+ referenced = new Map();
18
+ constructor({ chief, principal, workspaces, findWorkspacePackageTarget, isGitIgnored }) {
19
+ this.chief = chief;
20
+ this.principal = principal;
21
+ this.workspaces = workspaces;
22
+ this.findWorkspacePackageTarget = findWorkspacePackageTarget;
23
+ this.isGitIgnored = isGitIgnored;
24
+ }
25
+ isSubpathSpecifier(specifier) {
26
+ if (specifier.startsWith('#'))
27
+ return true;
28
+ const packageName = getPackageNameFromModuleSpecifier(specifier);
29
+ return packageName !== undefined && this.chief.isWorkspacePackageName(packageName);
30
+ }
31
+ addInput(input, owner) {
32
+ const { specifier, containingFilePath, dir } = input;
33
+ if (!containingFilePath || !this.isSubpathSpecifier(specifier))
34
+ return;
35
+ const filePath = dir ? join(dir, 'package.json') : containingFilePath;
36
+ const references = this.inputs.get(owner);
37
+ if (references)
38
+ references.push([specifier, filePath]);
39
+ else
40
+ this.inputs.set(owner, [[specifier, filePath]]);
41
+ if (this.isActive)
42
+ this.add(specifier, filePath);
43
+ }
44
+ add(specifier, containingFilePath) {
45
+ const workspace = this.chief.findWorkspaceByFilePath(containingFilePath);
46
+ const id = `${workspace?.name ?? ''}\0${specifier}`;
47
+ if (this.seen.has(id))
48
+ return;
49
+ this.seen.add(id);
50
+ const target = this.findWorkspacePackageTarget(sanitizeSpecifier(specifier), containingFilePath);
51
+ if (!target)
52
+ return;
53
+ const subpaths = this.referenced.get(target.name);
54
+ if (subpaths)
55
+ subpaths.add(target.subpath);
56
+ else
57
+ this.referenced.set(target.name, new Set([target.subpath]));
58
+ for (const targetPath of getPackageTargetPaths(target.target, target.dir, target.patternMatch, true)) {
59
+ const filePath = this.principal.toSourceFilePath(targetPath, this.extensions) ?? (isFile(targetPath) ? targetPath : undefined);
60
+ if (filePath && !this.isGitIgnored(filePath))
61
+ this.principal.claimEntryPath(filePath);
62
+ }
63
+ }
64
+ release(owner) {
65
+ this.inputs.delete(owner);
66
+ }
67
+ reset() {
68
+ this.isActive = true;
69
+ this.extensions = [...DEFAULT_EXTENSIONS, ...this.principal.compilers.keys()];
70
+ this.seen.clear();
71
+ this.referenced.clear();
72
+ this.principal.releaseEntryClaims();
73
+ for (const references of this.inputs.values()) {
74
+ for (const [specifier, containingFilePath] of references)
75
+ this.add(specifier, containingFilePath);
76
+ }
77
+ }
78
+ getIssues() {
79
+ const issues = [];
80
+ for (const { name, manifestPath, manifestStr, config } of this.workspaces) {
81
+ const manifest = this.chief.getManifestForWorkspace(name);
82
+ if (!manifest)
83
+ continue;
84
+ const referenced = this.referenced.get(name);
85
+ const peeker = new PackagePeeker(manifestStr);
86
+ const addIssue = (section, key) => {
87
+ issues.push({
88
+ type: 'subpaths',
89
+ filePath: manifestPath,
90
+ workspace: name,
91
+ symbol: key,
92
+ ...(peeker.getPropertyLocation(section, key) ?? peeker.getPropertyLocation(section)),
93
+ fixes: [],
94
+ });
95
+ };
96
+ if (manifest.imports) {
97
+ for (const key in manifest.imports) {
98
+ if (key.startsWith('#') && manifest.imports[key] !== null && !referenced?.has(key))
99
+ addIssue('imports', key);
100
+ }
101
+ }
102
+ if (manifest.exports && config.isIncludeSubpathExports) {
103
+ for (const [key, value] of getExportEntries(manifest.exports)) {
104
+ if (value !== null && !referenced?.has(key) && this.hasModuleTarget(value))
105
+ addIssue('exports', key);
106
+ }
107
+ }
108
+ }
109
+ return issues;
110
+ }
111
+ hasModuleTarget(value) {
112
+ return getEntriesFromExports(value).some(target => !extname(target) || this.principal.hasAcceptedExtension(target));
113
+ }
114
+ }