knip 6.44.1 → 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 (231) 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/bun.js +2 -2
  21. package/dist/binaries/resolvers/index.d.ts +1 -0
  22. package/dist/binaries/resolvers/index.js +2 -0
  23. package/dist/binaries/resolvers/npm.js +7 -5
  24. package/dist/binaries/resolvers/npx.js +15 -12
  25. package/dist/binaries/resolvers/nub.js +2 -2
  26. package/dist/binaries/resolvers/vp.d.ts +2 -0
  27. package/dist/binaries/resolvers/vp.js +52 -0
  28. package/dist/binaries/util.d.ts +13 -1
  29. package/dist/binaries/util.js +35 -1
  30. package/dist/cli.js +10 -84
  31. package/dist/compilers/scss.js +2 -1
  32. package/dist/configuration-hints.d.ts +16 -0
  33. package/dist/configuration-hints.js +64 -0
  34. package/dist/constants.d.ts +2 -1
  35. package/dist/constants.js +37 -0
  36. package/dist/graph/SubpathReferences.d.ts +33 -0
  37. package/dist/graph/SubpathReferences.js +114 -0
  38. package/dist/graph/analyze.d.ts +4 -1
  39. package/dist/graph/analyze.js +16 -5
  40. package/dist/graph/build.d.ts +3 -1
  41. package/dist/graph/build.js +47 -23
  42. package/dist/graph-explorer/operations/resolve-export-origins.js +1 -1
  43. package/dist/plugins/angular/index.js +10 -17
  44. package/dist/plugins/aws-cdk/index.d.ts +3 -0
  45. package/dist/plugins/aws-cdk/index.js +32 -0
  46. package/dist/plugins/aws-cdk/types.d.ts +5 -0
  47. package/dist/plugins/aws-cdk/types.js +1 -0
  48. package/dist/plugins/babel/index.d.ts +1 -1
  49. package/dist/plugins/babel/index.js +25 -6
  50. package/dist/plugins/babel/types.d.ts +1 -0
  51. package/dist/plugins/bun/index.js +8 -7
  52. package/dist/plugins/c8/index.js +17 -4
  53. package/dist/plugins/changesets/index.js +3 -2
  54. package/dist/plugins/commitizen/index.js +6 -3
  55. package/dist/plugins/commitlint/index.js +10 -11
  56. package/dist/plugins/cypress/index.js +4 -2
  57. package/dist/plugins/danger/index.js +1 -1
  58. package/dist/plugins/docusaurus/helpers.js +6 -6
  59. package/dist/plugins/docusaurus/index.js +2 -2
  60. package/dist/plugins/electron-forge/index.js +2 -2
  61. package/dist/plugins/electron-vite/index.js +2 -2
  62. package/dist/plugins/eleventy/index.js +3 -2
  63. package/dist/plugins/eslint/helpers.js +4 -3
  64. package/dist/plugins/eslint/resolveFromAST.js +2 -2
  65. package/dist/plugins/evalite/index.d.ts +3 -0
  66. package/dist/plugins/evalite/index.js +26 -0
  67. package/dist/plugins/flue/index.js +2 -2
  68. package/dist/plugins/gatsby/index.js +1 -1
  69. package/dist/plugins/github-action/index.js +2 -2
  70. package/dist/plugins/github-actions/index.js +2 -2
  71. package/dist/plugins/graphql-codegen/index.js +13 -9
  72. package/dist/plugins/index.d.ts +5 -0
  73. package/dist/plugins/index.js +10 -0
  74. package/dist/plugins/jest/index.js +5 -5
  75. package/dist/plugins/knex/index.js +2 -2
  76. package/dist/plugins/laravel-vite-plugin/resolveFromAST.js +2 -2
  77. package/dist/plugins/lunaria/index.js +5 -2
  78. package/dist/plugins/markdownlint/index.js +8 -2
  79. package/dist/plugins/marko/index.js +2 -2
  80. package/dist/plugins/marko/taglibs.d.ts +1 -1
  81. package/dist/plugins/marko/taglibs.js +4 -28
  82. package/dist/plugins/mdx/index.d.ts +2 -1
  83. package/dist/plugins/mdx/index.js +7 -4
  84. package/dist/plugins/mdxlint/index.js +18 -15
  85. package/dist/plugins/mikro-orm/index.d.ts +3 -0
  86. package/dist/plugins/mikro-orm/index.js +77 -0
  87. package/dist/plugins/mikro-orm/types.d.ts +21 -0
  88. package/dist/plugins/mikro-orm/types.js +1 -0
  89. package/dist/plugins/msw/index.js +6 -3
  90. package/dist/plugins/msw/types.d.ts +1 -1
  91. package/dist/plugins/netlify/index.js +7 -3
  92. package/dist/plugins/next/index.js +63 -9
  93. package/dist/plugins/next/types.d.ts +5 -0
  94. package/dist/plugins/next-mdx/resolveFromAST.js +15 -10
  95. package/dist/plugins/nitro/index.js +5 -6
  96. package/dist/plugins/node/index.js +4 -4
  97. package/dist/plugins/npm-package-json-lint/index.js +10 -3
  98. package/dist/plugins/nuxt/index.js +18 -10
  99. package/dist/plugins/nuxt/types.d.ts +4 -0
  100. package/dist/plugins/nx/index.js +6 -3
  101. package/dist/plugins/openclaw/index.js +11 -11
  102. package/dist/plugins/oxlint/index.js +2 -2
  103. package/dist/plugins/payload/index.js +1 -1
  104. package/dist/plugins/playwright/index.js +3 -3
  105. package/dist/plugins/pm2/index.js +7 -7
  106. package/dist/plugins/prettier/index.js +2 -1
  107. package/dist/plugins/prisma/index.js +2 -2
  108. package/dist/plugins/quasar/resolveFromAST.js +14 -9
  109. package/dist/plugins/react-router/index.js +12 -15
  110. package/dist/plugins/release-it/index.js +6 -2
  111. package/dist/plugins/remix/index.js +3 -3
  112. package/dist/plugins/retry-cli/index.d.ts +3 -0
  113. package/dist/plugins/retry-cli/index.js +14 -0
  114. package/dist/plugins/rollup/index.js +1 -4
  115. package/dist/plugins/rstest/index.js +3 -3
  116. package/dist/plugins/semantic-release/index.js +3 -3
  117. package/dist/plugins/serverless-framework/index.js +10 -8
  118. package/dist/plugins/solidjs-vite-plugin/resolveFromAST.js +2 -2
  119. package/dist/plugins/stencil/resolveFromAST.js +5 -5
  120. package/dist/plugins/storybook/index.js +9 -3
  121. package/dist/plugins/stryker/index.js +2 -2
  122. package/dist/plugins/stylelint/index.js +2 -2
  123. package/dist/plugins/swc/index.js +4 -3
  124. package/dist/plugins/tailwind/index.js +2 -2
  125. package/dist/plugins/tanstack-router/index.js +2 -2
  126. package/dist/plugins/ts-node/index.js +6 -1
  127. package/dist/plugins/turbo/index.js +3 -3
  128. package/dist/plugins/typedoc/index.js +2 -2
  129. package/dist/plugins/typescript/content-mappers.d.ts +1 -1
  130. package/dist/plugins/typescript/index.js +6 -9
  131. package/dist/plugins/unocss/index.js +3 -0
  132. package/dist/plugins/varlock/scan.js +1 -1
  133. package/dist/plugins/vite/helpers.d.ts +1 -0
  134. package/dist/plugins/vite/helpers.js +13 -3
  135. package/dist/plugins/vite/index.js +5 -2
  136. package/dist/plugins/vite-plugin-pwa/resolveFromAST.js +2 -2
  137. package/dist/plugins/vitest/index.js +26 -18
  138. package/dist/plugins/vitest/types.d.ts +1 -0
  139. package/dist/plugins/vue/index.js +1 -1
  140. package/dist/plugins/web-test-runner/index.d.ts +3 -0
  141. package/dist/plugins/web-test-runner/index.js +86 -0
  142. package/dist/plugins/wrangler/index.js +3 -3
  143. package/dist/plugins/yarn/index.js +5 -5
  144. package/dist/plugins.js +2 -5
  145. package/dist/reporters/github-actions.js +3 -7
  146. package/dist/reporters/json.d.ts +1 -0
  147. package/dist/reporters/json.js +1 -0
  148. package/dist/reporters/util/configuration-hints.d.ts +3 -1
  149. package/dist/reporters/util/configuration-hints.js +40 -21
  150. package/dist/reporters/util/util.d.ts +1 -1
  151. package/dist/run-cli.d.ts +2 -0
  152. package/dist/run-cli.js +82 -0
  153. package/dist/run.js +12 -0
  154. package/dist/session/incremental.d.ts +1 -0
  155. package/dist/session/incremental.js +1 -0
  156. package/dist/session/watch.js +2 -1
  157. package/dist/types/PluginNames.d.ts +2 -2
  158. package/dist/types/PluginNames.js +5 -0
  159. package/dist/types/args.d.ts +3 -1
  160. package/dist/types/config.d.ts +17 -10
  161. package/dist/types/configuration.d.ts +45 -0
  162. package/dist/types/configuration.js +1 -0
  163. package/dist/types/issues.d.ts +4 -0
  164. package/dist/types/module-graph.d.ts +1 -0
  165. package/dist/types/options.d.ts +1 -0
  166. package/dist/types/package-json.d.ts +3 -8
  167. package/dist/types/workspace.d.ts +1 -0
  168. package/dist/typescript/get-imports-and-exports.js +18 -6
  169. package/dist/typescript/resolve-module-names.js +7 -45
  170. package/dist/typescript/visitors/calls.d.ts +1 -1
  171. package/dist/typescript/visitors/calls.js +14 -10
  172. package/dist/typescript/visitors/exports.js +16 -26
  173. package/dist/typescript/visitors/imports.d.ts +2 -1
  174. package/dist/typescript/visitors/imports.js +41 -24
  175. package/dist/typescript/visitors/members.d.ts +1 -1
  176. package/dist/typescript/visitors/members.js +38 -24
  177. package/dist/typescript/visitors/shadow.d.ts +2 -0
  178. package/dist/typescript/visitors/shadow.js +25 -0
  179. package/dist/typescript/visitors/walk.d.ts +20 -12
  180. package/dist/typescript/visitors/walk.js +78 -48
  181. package/dist/util/Performance.d.ts +25 -3
  182. package/dist/util/Performance.js +51 -27
  183. package/dist/util/cli-arguments.d.ts +2 -1
  184. package/dist/util/cli-arguments.js +5 -3
  185. package/dist/util/create-input-handler.js +138 -119
  186. package/dist/util/create-options.d.ts +4 -2071
  187. package/dist/util/create-options.js +6 -4
  188. package/dist/util/create-workspace-graph.js +2 -1
  189. package/dist/util/errors.d.ts +5 -2
  190. package/dist/util/errors.js +11 -18
  191. package/dist/util/fs.js +4 -2
  192. package/dist/util/input.d.ts +2 -2
  193. package/dist/util/input.js +2 -2
  194. package/dist/util/is-plugin-name.d.ts +2 -0
  195. package/dist/util/is-plugin-name.js +3 -0
  196. package/dist/util/jiti.d.ts +2 -1
  197. package/dist/util/jiti.js +11 -3
  198. package/dist/util/load-config.d.ts +1 -1
  199. package/dist/util/load-config.js +3 -2
  200. package/dist/util/loader.js +3 -2
  201. package/dist/util/map-workspaces.js +23 -1
  202. package/dist/util/module-graph.js +1 -0
  203. package/dist/util/modules.d.ts +2 -0
  204. package/dist/util/modules.js +78 -0
  205. package/dist/util/package-json.d.ts +12 -5
  206. package/dist/util/package-json.js +54 -26
  207. package/dist/util/parse-and-convert-gitignores.d.ts +2 -2
  208. package/dist/util/parse-and-convert-gitignores.js +5 -5
  209. package/dist/util/parse-configuration.d.ts +2 -0
  210. package/dist/util/parse-configuration.js +66 -0
  211. package/dist/util/plugin.js +8 -12
  212. package/dist/util/resolve.d.ts +1 -0
  213. package/dist/util/resolve.js +3 -2
  214. package/dist/util/scripts.d.ts +0 -5
  215. package/dist/util/scripts.js +1 -32
  216. package/dist/util/to-source-path.d.ts +4 -1
  217. package/dist/util/to-source-path.js +2 -2
  218. package/dist/util/unhandled-rejection.d.ts +8 -0
  219. package/dist/util/unhandled-rejection.js +29 -0
  220. package/dist/util/validation.d.ts +11 -0
  221. package/dist/util/validation.js +68 -0
  222. package/dist/util/watch.d.ts +3 -1
  223. package/dist/util/watch.js +5 -2
  224. package/dist/version.d.ts +1 -1
  225. package/dist/version.js +1 -1
  226. package/package.json +9 -10
  227. package/schema.json +34 -0
  228. package/dist/schema/configuration.d.ts +0 -3103
  229. package/dist/schema/configuration.js +0 -94
  230. package/dist/schema/plugins.d.ts +0 -1019
  231. 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,5 +1,5 @@
1
1
  import parseArgs from '../../util/parse-args.js';
2
- import { toBinary, toEntry } from '../../util/input.js';
2
+ import { toBinary, toDeferResolveEntry } from '../../util/input.js';
3
3
  import { isAbsolute, join } from '../../util/path.js';
4
4
  import { _resolveSync } from '../../util/resolve.js';
5
5
  import { argsAfter, expandScript, toCommandBinary } from '../util.js';
@@ -82,7 +82,7 @@ export const resolve = (_binary, words, options) => {
82
82
  const _cwd = parsed.cwd ? join(cwd, parsed.cwd) : cwd;
83
83
  const resolved = _resolveSync(isAbsolute(filePath) ? filePath : join(_cwd, filePath), _cwd);
84
84
  if (resolved)
85
- return [binary, toEntry(resolved)];
85
+ return [binary, toDeferResolveEntry(resolved, { optional: true })];
86
86
  const dir = parsed.cwd ? join(cwd, parsed.cwd) : undefined;
87
87
  const opts = dir ? { cwd: dir } : {};
88
88
  if (command !== 'run')
@@ -10,6 +10,7 @@ declare const _default: {
10
10
  pn: import("../../types/config.ts").BinaryResolver;
11
11
  pnpx: import("../../types/config.ts").BinaryResolver;
12
12
  pnx: import("../../types/config.ts").BinaryResolver;
13
+ vp: import("../../types/config.ts").BinaryResolver;
13
14
  yarn: import("../../types/config.ts").BinaryResolver;
14
15
  find: import("../../types/config.ts").BinaryResolver;
15
16
  };
@@ -6,6 +6,7 @@ import * as npx from './npx.js';
6
6
  import * as nub from './nub.js';
7
7
  import * as pnpm from './pnpm.js';
8
8
  import * as pnpx from './pnpx.js';
9
+ import * as vp from './vp.js';
9
10
  import * as yarn from './yarn.js';
10
11
  const packageManagerResolvers = {
11
12
  bun: bun.resolve,
@@ -18,6 +19,7 @@ const packageManagerResolvers = {
18
19
  pn: pnpm.resolve,
19
20
  pnpx: pnpx.resolve,
20
21
  pnx: pnpx.resolve,
22
+ vp: vp.resolve,
21
23
  yarn: yarn.resolve,
22
24
  };
23
25
  export const isPackageManager = (binary) => binary in packageManagerResolvers;
@@ -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,29 +1,32 @@
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;
9
- const parsed = parseArgs(words, {
8
+ const { fromArgs, cwd } = options;
9
+ const toPackage = (id, opts) => isInternal(id) ? toDeferResolve(id, { ...opts, dir: cwd }) : toDependency(id, opts);
10
+ const args = {
10
11
  isStorePositions: true,
11
- boolean: ['yes', 'no', 'quiet'],
12
- alias: { yes: 'y', package: 'p', call: 'c' },
13
- });
12
+ boolean: npmBooleanFlags,
13
+ alias: { ...npmBooleanAliases, package: 'p', call: 'c' },
14
+ };
15
+ const parsed = parseArgs(words, args);
16
+ const commandIndex = parsed.positionalIndices[0] ?? words.length;
17
+ const flags = parseArgs(words.slice(0, commandIndex), args);
14
18
  const packageSpecifier = parsed._[0];
15
19
  const specifier = packageSpecifier ? stripVersionFromSpecifier(packageSpecifier) : '';
16
- const packages = parsed.package ? [parsed.package].flat().map(stripVersionFromSpecifier) : [];
17
- const command = parsed.call ? fromArgs([parsed.call]) : [];
20
+ const packages = flags.package ? [flags.package].flat().map(stripVersionFromSpecifier) : [];
21
+ const command = flags.call ? fromArgs([flags.call]) : [];
18
22
  const isBinary = specifier && !packageSpecifier.includes('@') && !isInternal(specifier);
19
- const commandIndex = parsed.positionalIndices[0] ?? words.length;
20
23
  const noInstall = words.slice(0, commandIndex).some(word => noInstallFlags.has(word.value));
21
24
  const opts = noInstall ? undefined : { optional: true };
22
- const dependency = isBinary ? toBinary(specifier, opts) : toDependency(specifier, opts);
25
+ const dependency = isBinary ? toBinary(specifier, opts) : toPackage(specifier, opts);
23
26
  const specifiers = dependency ? [dependency] : [];
24
27
  return [
25
28
  ...specifiers,
26
- ...packages.map(id => toDependency(id, { optional: true })),
29
+ ...packages.map(id => toPackage(id, { optional: true })),
27
30
  ...command,
28
31
  ...fromArgs(argsFrom(words, packageSpecifier)).slice(1),
29
32
  ];
@@ -1,5 +1,5 @@
1
1
  import parseArgs from '../../util/parse-args.js';
2
- import { toEntry } from '../../util/input.js';
2
+ import { toDeferResolveEntry } from '../../util/input.js';
3
3
  import { isAbsolute, join } from '../../util/path.js';
4
4
  import { _resolveSync } from '../../util/resolve.js';
5
5
  import { toCommandBinary } from '../util.js';
@@ -39,7 +39,7 @@ export const resolve = (_binary, words, options) => {
39
39
  if (!script || manifest.scriptNames.has(script))
40
40
  return [binary];
41
41
  const resolved = _resolveSync(isAbsolute(script) ? script : join(cwd, script), cwd);
42
- return resolved ? [binary, toEntry(resolved)] : [binary];
42
+ return resolved ? [binary, toDeferResolveEntry(resolved, { optional: true })] : [binary];
43
43
  }
44
44
  if (command && (commands.has(command) || manifest.scriptNames.has(command)))
45
45
  return [binary];
@@ -0,0 +1,2 @@
1
+ import type { BinaryResolver } from '../../types/config.ts';
2
+ export declare const resolve: BinaryResolver;
@@ -0,0 +1,52 @@
1
+ import parseArgs from '../../util/parse-args.js';
2
+ import { toAbsolute } from '../../util/path.js';
3
+ import { toCommandBinary } from '../util.js';
4
+ const parseOptions = {
5
+ isStorePositions: true,
6
+ string: ['filter', 'resume-from'],
7
+ boolean: [
8
+ 'fail-if-no-match',
9
+ 'parallel',
10
+ 'recursive',
11
+ 'report-summary',
12
+ 'reverse',
13
+ 'shell-mode',
14
+ 'transitive',
15
+ 'workspace-root',
16
+ ],
17
+ alias: { filter: 'F', recursive: 'r', 'shell-mode': 'c', transitive: 't', 'workspace-root': 'w' },
18
+ };
19
+ const parseLeadingChdir = (words) => {
20
+ const first = words[0]?.value;
21
+ if (first === '-C')
22
+ return [words[1]?.value, 2];
23
+ if (first?.startsWith('-C')) {
24
+ const dir = first[2] === '=' ? first.slice(3) : first.slice(2);
25
+ if (dir)
26
+ return [dir, 1];
27
+ }
28
+ return [undefined, 0];
29
+ };
30
+ export const resolve = (_binary, _words, options) => {
31
+ const binary = toCommandBinary(_binary, options);
32
+ const [C, consumed] = parseLeadingChdir(_words);
33
+ const words = _words.slice(consumed);
34
+ const parsed = parseArgs(words, parseOptions);
35
+ const [command] = parsed._;
36
+ if (command !== 'exec')
37
+ return [binary];
38
+ const [execIndex, commandIndex] = parsed.positionalIndices;
39
+ if (commandIndex === undefined)
40
+ return [binary];
41
+ const execOptions = parseArgs(words.slice(execIndex + 1, commandIndex), parseOptions);
42
+ if (execOptions.filter)
43
+ return [binary];
44
+ const dir = execOptions['workspace-root'] ? options.rootCwd : C ? toAbsolute(C, options.cwd) : undefined;
45
+ const rest = words.slice(commandIndex);
46
+ const script = rest.map(word => (execOptions['shell-mode'] ? word.value : word.text)).join(' ');
47
+ const inputs = options.fromArgs([script], dir ? { cwd: dir } : {});
48
+ if (dir)
49
+ for (const input of inputs)
50
+ input.dir ??= dir;
51
+ return [binary, ...inputs];
52
+ };
@@ -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);
@@ -1,4 +1,5 @@
1
1
  import { getUrlSpecifier, isScopedPackage, isTildePackage, splitSpec } from './shared.js';
2
+ import { hasUrlScheme } from '../util/url.js';
2
3
  const dependencies = ['sass', 'sass-embedded', 'node-sass'];
3
4
  const dependencyMatcher = /"(?:\\(?:\r\n|[\s\S]|$)|[^"\\\r\n\f])*(?:"|[\r\n\f]|$)|'(?:\\(?:\r\n|[\s\S]|$)|[^'\\\r\n\f])*(?:'|[\r\n\f]|$)|\/\*[\s\S]*?(?:\*\/|$)|\/\/[^\r\n]*(?:[\r\n]|$)|@(?:use|import|forward)\s+['"](pkg:)?([^'"]+)['"]|url\(\s*(?:["']([^"'\r\n]*)["']|([^'")\s]+))\s*\)/g;
4
5
  const candidates = (specifier) => {
@@ -29,7 +30,7 @@ export const compiler = text => {
29
30
  continue;
30
31
  }
31
32
  let spec = match[2];
32
- if (!spec || spec.startsWith('sass:'))
33
+ if (!spec || spec.startsWith('//') || hasUrlScheme(spec))
33
34
  continue;
34
35
  let isBare = Boolean(match[1]) || isScopedPackage(spec);
35
36
  if (isTildePackage(spec)) {
@@ -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';