@eslint-sh/eslint-plugin 0.7.0 → 0.9.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 (182) hide show
  1. package/README.md +53 -40
  2. package/dist/api.d.ts +92 -0
  3. package/dist/api.js +83 -0
  4. package/dist/command-harvest/builtins/bash.d.ts +1 -1
  5. package/dist/command-harvest/builtins/bash.js +1 -1
  6. package/dist/command-harvest/builtins/bats.d.ts +2 -0
  7. package/dist/command-harvest/builtins/bats.js +3 -0
  8. package/dist/command-harvest/harvest-commands.d.ts +2 -2
  9. package/dist/command-harvest/harvest-commands.js +2 -2
  10. package/dist/command-harvest/wrapper-table.d.ts +3 -19
  11. package/dist/command-harvest/wrapper-table.js +8 -38
  12. package/dist/configs/bash-3-2.d.ts +7 -6
  13. package/dist/configs/bash-3-2.js +4 -3
  14. package/dist/configs/posix-portable.d.ts +7 -11
  15. package/dist/configs/posix-portable.js +4 -6
  16. package/dist/configuration-message.d.ts +14 -0
  17. package/dist/configuration-message.js +33 -0
  18. package/dist/declaration-conventions/get-declared-commands.d.ts +41 -0
  19. package/dist/declaration-conventions/{read-declared-commands.js → get-declared-commands.js} +43 -43
  20. package/dist/eslint-plugin-api.d.ts +1506 -0
  21. package/dist/eslint-plugin-syntax-analyze.d.ts +3 -3
  22. package/dist/eslint-plugin-syntax.d.ts +7 -4
  23. package/dist/eslint-plugin.d.ts +16 -1514
  24. package/dist/index.d.ts +14 -78
  25. package/dist/index.js +22 -74
  26. package/dist/language/command-resolution.d.ts +5 -5
  27. package/dist/language/command-resolution.js +11 -7
  28. package/dist/language/selector-classes.d.ts +7 -3
  29. package/dist/language/selector-classes.js +13 -4
  30. package/dist/language/shell-language-options.d.ts +21 -18
  31. package/dist/language/shell-language-options.js +41 -39
  32. package/dist/language/shell-language.d.ts +13 -10
  33. package/dist/language/shell-language.js +23 -45
  34. package/dist/language/shell-source-code.d.ts +74 -49
  35. package/dist/language/shell-source-code.js +135 -68
  36. package/dist/language/source-coordinates.d.ts +2 -0
  37. package/dist/language/source-coordinates.js +8 -4
  38. package/dist/language/syntax-view.js +19 -7
  39. package/dist/language/word-resolution.d.ts +2 -1
  40. package/dist/language/word-resolution.js +8 -3
  41. package/dist/rules/bash-variable-semantics.d.ts +22 -0
  42. package/dist/rules/bash-variable-semantics.js +41 -0
  43. package/dist/rules/compat/create-compat-rule.js +1 -1
  44. package/dist/rules/compat/declaration-options.d.ts +2 -2
  45. package/dist/rules/compat/declaration-options.js +5 -2
  46. package/dist/rules/compat/no-append-all-redirect.js +1 -1
  47. package/dist/rules/compat/no-associative-arrays.js +2 -2
  48. package/dist/rules/compat/no-brace-sequence-padding-step.js +4 -4
  49. package/dist/rules/compat/no-case-attributes.js +3 -3
  50. package/dist/rules/compat/no-case-fallthrough.js +2 -2
  51. package/dist/rules/compat/no-case-modification.js +2 -2
  52. package/dist/rules/compat/no-coproc.js +1 -1
  53. package/dist/rules/compat/no-declare-g.js +3 -3
  54. package/dist/rules/compat/no-double-bracket.js +2 -2
  55. package/dist/rules/compat/no-epoch-variables.js +2 -2
  56. package/dist/rules/compat/no-fd-variable.js +1 -1
  57. package/dist/rules/compat/no-globstar.js +1 -1
  58. package/dist/rules/compat/no-lastpipe-semantics.js +2 -2
  59. package/dist/rules/compat/no-let.js +2 -1
  60. package/dist/rules/compat/no-mapfile.js +4 -2
  61. package/dist/rules/compat/no-nameref.js +3 -3
  62. package/dist/rules/compat/no-negative-array-index.js +39 -9
  63. package/dist/rules/compat/no-nounset-empty-array.js +15 -4
  64. package/dist/rules/compat/no-parameter-transformation.js +2 -2
  65. package/dist/rules/compat/no-pipe-all.js +1 -1
  66. package/dist/rules/compat/no-printf-time-format.js +4 -2
  67. package/dist/rules/compat/no-source.js +2 -1
  68. package/dist/rules/compat/no-test-v.js +4 -2
  69. package/dist/rules/compat/no-unicode-escape.js +2 -2
  70. package/dist/rules/compat/no-wait-n.js +4 -2
  71. package/dist/rules/compat/nounset-array-proof.d.ts +8 -0
  72. package/dist/rules/compat/nounset-array-proof.js +563 -0
  73. package/dist/rules/compat/posix-absent-command.d.ts +7 -8
  74. package/dist/rules/compat/posix-absent-command.js +17 -15
  75. package/dist/rules/compat/shopt-options.js +3 -1
  76. package/dist/rules/compat/version-gates.d.ts +9 -9
  77. package/dist/rules/compat/version-gates.js +13 -13
  78. package/dist/rules/create-wrapper-rule.d.ts +1 -1
  79. package/dist/rules/create-wrapper-rule.js +23 -16
  80. package/dist/rules/define-shell-rule.js +1 -1
  81. package/dist/rules/no-dynamic-invocation.d.ts +0 -8
  82. package/dist/rules/no-dynamic-invocation.js +7 -15
  83. package/dist/rules/no-eval.js +3 -1
  84. package/dist/rules/no-masked-exit-status.d.ts +4 -3
  85. package/dist/rules/no-masked-exit-status.js +18 -10
  86. package/dist/rules/no-secret-env-reads.d.ts +6 -3
  87. package/dist/rules/no-secret-env-reads.js +49 -15
  88. package/dist/rules/no-secret-flags.d.ts +4 -1
  89. package/dist/rules/no-secret-flags.js +21 -11
  90. package/dist/rules/no-unchecked-cd.js +6 -3
  91. package/dist/rules/no-undeclared-commands.d.ts +1 -15
  92. package/dist/rules/no-undeclared-commands.js +11 -18
  93. package/dist/rules/no-unused-declarations.d.ts +1 -18
  94. package/dist/rules/no-unused-declarations.js +15 -36
  95. package/dist/rules/prefer-local.d.ts +3 -2
  96. package/dist/rules/prefer-local.js +7 -4
  97. package/dist/rules/quote-expansions.js +3 -28
  98. package/dist/rules/require-network-wrapper.d.ts +3 -18
  99. package/dist/rules/require-network-wrapper.js +43 -10
  100. package/dist/rules/require-strict-mode.d.ts +5 -46
  101. package/dist/rules/require-strict-mode.js +17 -107
  102. package/dist/rules/require-tty-guard.d.ts +2 -0
  103. package/dist/rules/require-tty-guard.js +8 -1
  104. package/dist/rules/resolve-declaration-convention.d.ts +9 -89
  105. package/dist/rules/resolve-declaration-convention.js +19 -72
  106. package/dist/rules/resolve-network-wrapper.d.ts +20 -2
  107. package/dist/rules/resolve-network-wrapper.js +71 -36
  108. package/dist/rules/resolve-transparent-wrappers.d.ts +38 -0
  109. package/dist/rules/resolve-transparent-wrappers.js +108 -0
  110. package/dist/rules/set-options.d.ts +3 -2
  111. package/dist/rules/set-options.js +18 -6
  112. package/dist/rules/shebang-interpreter.js +4 -2
  113. package/dist/rules/strict-mode-prologue.d.ts +43 -0
  114. package/dist/rules/strict-mode-prologue.js +91 -0
  115. package/dist/rules/transparent-wrappers.d.ts +4 -3
  116. package/dist/rules/transparent-wrappers.js +5 -4
  117. package/dist/rules/user-pattern.d.ts +9 -6
  118. package/dist/rules/user-pattern.js +16 -12
  119. package/dist/shell-dialect.d.ts +8 -0
  120. package/dist/shell-dialect.js +22 -0
  121. package/dist/syntax/analyze.d.ts +3 -3
  122. package/dist/syntax/analyze.js +3 -3
  123. package/dist/syntax/index.d.ts +7 -4
  124. package/dist/syntax/index.js +7 -4
  125. package/dist/version.js +2 -1
  126. package/docs/compat.md +81 -33
  127. package/docs/custom-rule-tutorial.md +31 -21
  128. package/docs/declaration-conventions.md +20 -23
  129. package/docs/error-codes.md +93 -0
  130. package/docs/examples/no-listed-commands-rule.ts +2 -2
  131. package/docs/examples/no-rm-rf-rule.mjs +8 -10
  132. package/docs/examples/sorted-declarations-rule.mjs +6 -9
  133. package/docs/examples/tsconfig.json +10 -0
  134. package/docs/rules/README.md +46 -6
  135. package/docs/rules/_template.md +2 -2
  136. package/docs/rules/compat/no-append-all-redirect.md +12 -12
  137. package/docs/rules/compat/no-associative-arrays.md +14 -14
  138. package/docs/rules/compat/no-brace-sequence-padding-step.md +12 -12
  139. package/docs/rules/compat/no-case-attributes.md +13 -13
  140. package/docs/rules/compat/no-case-fallthrough.md +12 -12
  141. package/docs/rules/compat/no-case-modification.md +11 -11
  142. package/docs/rules/compat/no-coproc.md +13 -13
  143. package/docs/rules/compat/no-declare-g.md +13 -13
  144. package/docs/rules/compat/no-double-bracket.md +2 -2
  145. package/docs/rules/compat/no-epoch-variables.md +13 -13
  146. package/docs/rules/compat/no-fd-variable.md +12 -12
  147. package/docs/rules/compat/no-globstar.md +13 -13
  148. package/docs/rules/compat/no-lastpipe-semantics.md +13 -13
  149. package/docs/rules/compat/no-let.md +2 -2
  150. package/docs/rules/compat/no-mapfile.md +16 -16
  151. package/docs/rules/compat/no-nameref.md +13 -13
  152. package/docs/rules/compat/no-negative-array-index.md +14 -14
  153. package/docs/rules/compat/no-nounset-empty-array.md +72 -17
  154. package/docs/rules/compat/no-parameter-transformation.md +19 -19
  155. package/docs/rules/compat/no-pipe-all.md +13 -13
  156. package/docs/rules/compat/no-printf-time-format.md +13 -13
  157. package/docs/rules/compat/no-source.md +2 -2
  158. package/docs/rules/compat/no-test-v.md +12 -12
  159. package/docs/rules/compat/no-unicode-escape.md +13 -13
  160. package/docs/rules/compat/no-wait-n.md +13 -13
  161. package/docs/rules/no-dynamic-invocation.md +17 -12
  162. package/docs/rules/no-eval.md +6 -1
  163. package/docs/rules/no-masked-exit-status.md +6 -2
  164. package/docs/rules/no-secret-env-reads.md +46 -5
  165. package/docs/rules/no-secret-flags.md +32 -6
  166. package/docs/rules/no-unchecked-cd.md +22 -2
  167. package/docs/rules/no-undeclared-commands.md +16 -15
  168. package/docs/rules/no-unused-declarations.md +17 -20
  169. package/docs/rules/prefer-local.md +20 -2
  170. package/docs/rules/quote-expansions.md +8 -5
  171. package/docs/rules/require-network-wrapper.md +26 -21
  172. package/docs/rules/require-shebang.md +10 -4
  173. package/docs/rules/require-strict-mode.md +31 -23
  174. package/docs/rules/require-tty-guard.md +12 -3
  175. package/docs/selectors.md +7 -2
  176. package/docs/shellcheck.md +9 -5
  177. package/docs/transparent-wrappers.md +97 -0
  178. package/docs/wrapper-rules.md +11 -0
  179. package/package.json +3 -3
  180. package/dist/declaration-conventions/read-declared-commands.d.ts +0 -70
  181. package/dist/language/end-of-input-marker.d.ts +0 -29
  182. package/dist/language/end-of-input-marker.js +0 -88
@@ -1,90 +1,13 @@
1
1
  import { createRule } from './create-rule.js';
2
- import { SET_OPTION_NAMES, applySetOptionChanges, formatSetCommand, parseSetArguments, shebangOptionChanges, } from './set-options.js';
2
+ import { SET_OPTION_NAMES, formatSetCommand, shebangOptionChanges } from './set-options.js';
3
+ import { enabledAfter, resolveStrictModePrologue, setStatementChanges, } from './strict-mode-prologue.js';
3
4
  import { lineBreakOf } from '../language/line-breaks.js';
4
5
  /**
5
- * The prologue an unconfigured `mode` falls back to for every dialect except
6
- * `posix`.
6
+ * Dialect-aware policy defaults. Bats runs under Bash; POSIX omits pipefail
7
+ * because older dash and BusyBox ash reject it. Explicit requirements win.
7
8
  */
8
- const DEFAULT_PROLOGUE = 'set -euo pipefail';
9
- /**
10
- * The prologue an unconfigured `mode` falls back to under the `posix`
11
- * dialect: strict mode without `pipefail`, so the autofix never inserts a
12
- * line that a pre-POSIX.1-2024 `sh` rejects. `pipefail` stays available
13
- * there by configuring `mode`.
14
- */
15
- const POSIX_DEFAULT_PROLOGUE = 'set -eu';
16
- /**
17
- * The prologue used when `mode` is not configured, chosen by the file's
18
- * dialect. Only `posix` differs; `bats` files run under Bash and keep the
19
- * Bash default.
20
- */
21
- function defaultPrologueFor(dialect) {
22
- return dialect === 'posix' ? POSIX_DEFAULT_PROLOGUE : DEFAULT_PROLOGUE;
23
- }
24
- /** How many top-level statements `withinStatements` defaults to. */
25
- const DEFAULT_WITHIN_STATEMENTS = 5;
26
- /**
27
- * Turns the `mode` option into a {@link StrictModeRequirement}. A string mode
28
- * must be a `set` command whose arguments only enable known options (no `+`
29
- * flags, no positional parameters); anything else is a configuration error,
30
- * reported by throwing so ESLint surfaces it instead of linting against a
31
- * requirement nobody wrote.
32
- */
33
- function resolveRequirement(mode) {
34
- if (typeof mode !== 'string') {
35
- return { required: [...new Set(mode)], prologue: formatSetCommand(mode) };
36
- }
37
- const prologue = mode.trim();
38
- const [command, ...args] = prologue.split(/\s+/u);
39
- const parsed = parseSetArguments(args);
40
- if (command !== 'set' ||
41
- parsed.stoppedBy !== undefined ||
42
- parsed.changes.length === 0 ||
43
- parsed.changes.some((change) => !change.enable)) {
44
- throw new TypeError(`sh/require-strict-mode: \`mode\` must be a \`set\` command that only enables options ` +
45
- `(for example "${DEFAULT_PROLOGUE}") or a list of option names; got ${JSON.stringify(mode)}.`);
46
- }
47
- return { required: [...new Set(parsed.changes.map((change) => change.option))], prologue };
48
- }
49
- /**
50
- * Whether `stmt` is a plain, foreground, top-level `set` command, and if so
51
- * the option changes its arguments make (read through `sourceCode`, so a
52
- * non-static argument ends the reading).
53
- *
54
- * @internal
55
- */
56
- export function setStatementChanges(stmt, sourceCode) {
57
- if (stmt.background)
58
- return [];
59
- const { cmd } = stmt;
60
- if (cmd?.type !== 'CallExpr' || sourceCode.getCommandName(cmd) !== 'set')
61
- return [];
62
- const args = cmd.args.slice(1);
63
- return parseSetArguments(args.map((word) => sourceCode.resolveWordText(word))).changes;
64
- }
65
- /**
66
- * The options enabled after applying `seed`, then each statement's `set`
67
- * changes in order.
68
- */
69
- function enabledAfter(seed, statementChanges) {
70
- const enabled = applySetOptionChanges(new Set(), seed);
71
- for (const changes of statementChanges)
72
- applySetOptionChanges(enabled, changes);
73
- return enabled;
74
- }
75
- /**
76
- * The options a file's prologue leaves enabled: the state after the first
77
- * `withinStatements` top-level statements of `file`, plus the shebang's
78
- * options when `allowShebangOnly` is set. This is the single definition of
79
- * "what the prologue enables", shared with other rules (such as
80
- * `no-unchecked-cd`) that need to know whether strict mode is in force.
81
- *
82
- * @internal
83
- */
84
- export function prologueEnabledOptions(file, sourceCode, config = {}) {
85
- const shebangChanges = config.allowShebangOnly === true ? shebangOptionChanges(sourceCode.text) : [];
86
- const statements = file.stmts.slice(0, config.withinStatements ?? DEFAULT_WITHIN_STATEMENTS);
87
- return enabledAfter(shebangChanges, statements.map((stmt) => setStatementChanges(stmt, sourceCode)));
9
+ function defaultRequiredOptions(dialect) {
10
+ return dialect === 'posix' ? ['errexit', 'nounset'] : ['errexit', 'nounset', 'pipefail'];
88
11
  }
89
12
  /** Built-in rule `sh/require-strict-mode`. @internal */
90
13
  export const requireStrictMode = createRule({
@@ -99,32 +22,18 @@ export const requireStrictMode = createRule({
99
22
  {
100
23
  type: 'object',
101
24
  properties: {
102
- mode: {
103
- oneOf: [
104
- { type: 'string', minLength: 1 },
105
- {
106
- type: 'array',
107
- items: { enum: [...SET_OPTION_NAMES] },
108
- minItems: 1,
109
- uniqueItems: true,
110
- },
111
- ],
25
+ requiredOptions: {
26
+ type: 'array',
27
+ items: { enum: [...SET_OPTION_NAMES] },
28
+ minItems: 1,
29
+ uniqueItems: true,
112
30
  },
113
- allowShebangOnly: { type: 'boolean' },
114
- withinStatements: { type: 'integer', minimum: 1 },
115
31
  },
116
32
  additionalProperties: false,
117
33
  },
118
34
  ],
119
- // `mode` has no static default: an unconfigured `mode` resolves per file
120
- // from the dialect (see `defaultPrologueFor`), so it must stay absent here
121
- // for the rule to tell "not configured" apart from a configured value.
122
- defaultOptions: [
123
- {
124
- allowShebangOnly: false,
125
- withinStatements: DEFAULT_WITHIN_STATEMENTS,
126
- },
127
- ],
35
+ // Absence must survive defaulting so each file's dialect selects its policy.
36
+ defaultOptions: [{}],
128
37
  messages: {
129
38
  missingStrictMode: 'Enable strict mode with `{{prologue}}` within {{window}}; not enabled: {{missing}}.',
130
39
  },
@@ -132,12 +41,13 @@ export const requireStrictMode = createRule({
132
41
  create(context) {
133
42
  const [options] = context.options;
134
43
  const { sourceCode } = context;
135
- const { required, prologue } = resolveRequirement(options.mode ?? defaultPrologueFor(sourceCode.dialect));
136
- const withinStatements = options.withinStatements ?? DEFAULT_WITHIN_STATEMENTS;
44
+ const required = options.requiredOptions ?? defaultRequiredOptions(sourceCode.dialect);
45
+ const prologue = formatSetCommand(required);
46
+ const { allowShebangOnly, withinStatements } = resolveStrictModePrologue(context.settings);
137
47
  return {
138
48
  File(node) {
139
49
  const text = sourceCode.text;
140
- const shebangChanges = options.allowShebangOnly === true ? shebangOptionChanges(text) : [];
50
+ const shebangChanges = allowShebangOnly ? shebangOptionChanges(text) : [];
141
51
  const statements = node.stmts.slice(0, withinStatements);
142
52
  const statementChanges = statements.map((stmt) => setStatementChanges(stmt, sourceCode));
143
53
  const enabled = enabledAfter(shebangChanges, statementChanges);
@@ -6,6 +6,8 @@
6
6
  export interface RequireTtyGuardOptions {
7
7
  /** Replaces the default interactive commands (`read`, `select`). */
8
8
  readonly commands?: readonly string[];
9
+ /** Commands added to the replacement list, or to `read` and `select` when it is omitted. */
10
+ readonly additionalCommands?: readonly string[];
9
11
  }
10
12
  /** Message ids of this rule. @internal */
11
13
  export type RequireTtyGuardMessageId = 'unguardedInteractive' | 'wrapInTtyGuard';
@@ -204,6 +204,7 @@ export const requireTtyGuard = createRule({
204
204
  type: 'object',
205
205
  properties: {
206
206
  commands: { type: 'array', items: { type: 'string', minLength: 1 } },
207
+ additionalCommands: { type: 'array', items: { type: 'string', minLength: 1 } },
207
208
  },
208
209
  additionalProperties: false,
209
210
  },
@@ -215,7 +216,13 @@ export const requireTtyGuard = createRule({
215
216
  },
216
217
  create(context) {
217
218
  const { sourceCode } = context;
218
- const commands = new Set(context.options[0]?.commands ?? DEFAULT_COMMANDS);
219
+ const options = context.options[0];
220
+ // Empty replacements intentionally remove defaults; a set makes overlapping
221
+ // base/additional names one policy without mutating either configured list.
222
+ const commands = new Set([
223
+ ...(options?.commands ?? DEFAULT_COMMANDS),
224
+ ...(options?.additionalCommands ?? []),
225
+ ]);
219
226
  // Interactive commands found in the file, checked once every guard is known.
220
227
  const candidates = [];
221
228
  const guards = [];
@@ -1,96 +1,16 @@
1
- /**
2
- * Binding resolution for the declaration-convention extension point: the one
3
- * place a rule finds out which {@link DeclarationConvention} the consumer has
4
- * bound, if any.
5
- *
6
- * Every rule that consumes a convention calls
7
- * {@link resolveDeclarationConvention} from its `create()`, so all of them
8
- * agree on precedence, on what "not configured" means, and on how a
9
- * misconfiguration is reported. The precedence is:
10
- *
11
- * 1. the rule's own `declarationConvention` option (its first options
12
- * object), so one rule can be pointed at a different convention. ESLint
13
- * flat config copies rule options with `structuredClone`, so a convention
14
- * whose methods are own properties is rejected there by ESLint itself
15
- * ("could not be cloned"), and a class instance arrives with its methods
16
- * stripped and fails the check below. In practice consumers bind through
17
- * settings;
18
- * 2. the shared `settings.sh.declarationConvention`, bound once for every
19
- * consuming rule;
20
- * 3. otherwise `null`: no convention is bound and the consuming rule is
21
- * inert — it reports nothing. Shipping a default would smuggle one
22
- * project's declaration policy into every project.
23
- *
24
- * Only an absent (`undefined`) value falls through to the next source. Any
25
- * other value is the consumer's explicit choice and must be a convention; if
26
- * it is not, resolution throws an error that names the offending setting, so
27
- * the misconfiguration surfaces as a readable configuration message rather
28
- * than a `TypeError` from deep inside a rule.
29
- *
30
- * The resolver is public so a rule pack can write its own consumer of the
31
- * bound convention and get exactly the precedence, validation and error text
32
- * the built-in consumers (`sh/no-undeclared-commands`,
33
- * `sh/no-unused-declarations`) use, instead of re-implementing them.
34
- */
35
1
  import type { SettingsConfig } from '@eslint/core';
36
2
  import type { DeclarationConvention } from '../declaration-conventions/declaration-convention.js';
37
3
  /**
38
- * The slice of an ESLint rule context that binding resolution reads: the rule
39
- * id (for error messages), its configured options, and the shared settings.
40
- * Any rule `context` satisfies it, so a rule passes its own `context`.
4
+ * Returns the convention bound in `settings.sh.declarationConvention`, or `null`
5
+ * when absent. Present invalid values throw an error naming the shared setting.
41
6
  *
42
- * @public
43
- */
44
- export interface DeclarationConventionBindingContext {
45
- /** The rule id as configured (`pack/my-rule`), named in an option-binding error. */
46
- readonly id: string;
47
- /** The rule's configured options; the first may carry `declarationConvention`. */
48
- readonly options: readonly unknown[];
49
- /** The shared settings; `settings.sh.declarationConvention` is the usual binding. */
50
- readonly settings: SettingsConfig;
51
- }
52
- /**
53
- * Resolves the declaration convention bound for the rule running in
54
- * `context`: the rule's `declarationConvention` option, else
55
- * `settings.sh.declarationConvention`, else `null` (the rule is inert).
56
- *
57
- * Throws an `Error` naming the offending setting when the configured value is
58
- * present but does not implement `declaredCommands` (or has a non-function
59
- * `removeDeclaration`). The message names where the value came from and what
60
- * it was, for example one beginning
61
- * `Invalid settings.sh.declarationConvention: expected a declaration convention`
62
- * and ending `but got string "jq".` Call it from `create()`, so the error
63
- * surfaces as ESLint's
64
- * configuration message for the file being linted.
65
- *
66
- * A rule that receives `null` should register no listeners: with no
67
- * convention bound, a convention consumer has nothing to check.
68
- *
69
- * @example
70
- * ```ts
71
- * import {
72
- * defineShellRule,
73
- * readDeclaredCommands,
74
- * resolveDeclarationConvention,
75
- * } from '@eslint-sh/eslint-plugin';
76
- *
77
- * export const maxDeclaredCommands = defineShellRule({
78
- * meta: { schema: [], messages: { tooMany: 'Declare at most 5 commands.' } },
79
- * create(context) {
80
- * const convention = resolveDeclarationConvention(context);
81
- * if (convention === null) return {};
82
- * return {
83
- * File(node) {
84
- * // Validated declarations for the file `context` is linting.
85
- * if (readDeclaredCommands(convention, context).length > 5) {
86
- * context.report({ node, messageId: 'tooMany' });
87
- * }
88
- * },
89
- * };
90
- * },
91
- * });
92
- * ```
7
+ * Use {@link getDeclaredCommands} to read validated declarations. This narrow
8
+ * resolver exists for consumers that also need a convention hook, such as
9
+ * `removeDeclaration`; it never exposes rule-specific binding policy.
93
10
  *
11
+ * @throws Error with `ESLINT_SH_DECLARATION_CONVENTION` for malformed bindings or optional hooks.
94
12
  * @public
95
13
  */
96
- export declare function resolveDeclarationConvention(context: DeclarationConventionBindingContext): DeclarationConvention | null;
14
+ export declare function resolveDeclarationConvention(context: {
15
+ readonly settings: SettingsConfig;
16
+ }): DeclarationConvention | null;
@@ -1,35 +1,19 @@
1
1
  /**
2
- * The key a convention is bound under, both in a consuming rule's options
3
- * object and in the plugin's `settings.sh` namespace.
2
+ * Resolves the project-wide declaration policy from shared ESLint settings.
3
+ * Every consuming rule must use the same convention: rule options are cloned by
4
+ * ESLint and cannot carry the convention's methods. No implicit convention is
5
+ * supplied, because declaration policy belongs to the project.
6
+ *
7
+ * ESLINT_SH_DECLARATION_CONVENTION identifies a malformed binding, distinct
8
+ * from a bound hook returning invalid declarations or throwing its own error.
4
9
  */
10
+ import { configurationMessage } from '../configuration-message.js';
11
+ /** The shared setting key that names the project's declaration policy. */
5
12
  const DECLARATION_CONVENTION_KEY = 'declarationConvention';
6
13
  /** `value` is an object (not `null`) whose properties can be read. */
7
14
  function isObjectLike(value) {
8
15
  return (typeof value === 'object' || typeof value === 'function') && value !== null;
9
16
  }
10
- /** A short description of a value that is not a convention, for an error message. */
11
- function describeValue(value) {
12
- if (value === null)
13
- return 'null';
14
- if (Array.isArray(value))
15
- return 'an array';
16
- if (isObjectLike(value)) {
17
- return typeof value.declaredCommands === 'undefined'
18
- ? 'an object with no `declaredCommands` method'
19
- : `an object whose \`declaredCommands\` is ${typeof value.declaredCommands}, not a function`;
20
- }
21
- switch (typeof value) {
22
- case 'string':
23
- return `string ${JSON.stringify(value)}`;
24
- case 'number':
25
- case 'boolean':
26
- case 'bigint':
27
- case 'symbol':
28
- return `${typeof value} ${String(value)}`;
29
- default:
30
- return typeof value;
31
- }
32
- }
33
17
  /**
34
18
  * Checks that `value`, configured at `setting`, implements
35
19
  * {@link DeclarationConvention}: a `declaredCommands` function, and, when a
@@ -40,65 +24,28 @@ function describeValue(value) {
40
24
  function assertDeclarationConvention(value, setting) {
41
25
  const expected = 'expected a declaration convention: an object with a `declaredCommands(sourceCode)` method';
42
26
  if (!isObjectLike(value) || typeof value.declaredCommands !== 'function') {
43
- throw new Error(`Invalid ${setting}: ${expected}, but got ${describeValue(value)}.`);
27
+ throw Object.assign(new Error(configurationMessage(setting, expected, value)), {
28
+ code: 'ESLINT_SH_DECLARATION_CONVENTION',
29
+ });
44
30
  }
45
31
  for (const hook of ['removeDeclaration', 'declarationHint']) {
46
32
  if (value[hook] !== undefined && typeof value[hook] !== 'function') {
47
- throw new Error(`Invalid ${setting}: its optional \`${hook}\` hook must be a function when present, but got ${typeof value[hook]}.`);
33
+ throw Object.assign(new Error(configurationMessage(`${setting}.${hook}`, 'optional hook must be a function when present', value[hook])), { code: 'ESLINT_SH_DECLARATION_CONVENTION' });
48
34
  }
49
35
  }
50
36
  }
51
37
  /**
52
- * Resolves the declaration convention bound for the rule running in
53
- * `context`: the rule's `declarationConvention` option, else
54
- * `settings.sh.declarationConvention`, else `null` (the rule is inert).
38
+ * Returns the convention bound in `settings.sh.declarationConvention`, or `null`
39
+ * when absent. Present invalid values throw an error naming the shared setting.
55
40
  *
56
- * Throws an `Error` naming the offending setting when the configured value is
57
- * present but does not implement `declaredCommands` (or has a non-function
58
- * `removeDeclaration`). The message names where the value came from and what
59
- * it was, for example one beginning
60
- * `Invalid settings.sh.declarationConvention: expected a declaration convention`
61
- * and ending `but got string "jq".` Call it from `create()`, so the error
62
- * surfaces as ESLint's
63
- * configuration message for the file being linted.
64
- *
65
- * A rule that receives `null` should register no listeners: with no
66
- * convention bound, a convention consumer has nothing to check.
67
- *
68
- * @example
69
- * ```ts
70
- * import {
71
- * defineShellRule,
72
- * readDeclaredCommands,
73
- * resolveDeclarationConvention,
74
- * } from '@eslint-sh/eslint-plugin';
75
- *
76
- * export const maxDeclaredCommands = defineShellRule({
77
- * meta: { schema: [], messages: { tooMany: 'Declare at most 5 commands.' } },
78
- * create(context) {
79
- * const convention = resolveDeclarationConvention(context);
80
- * if (convention === null) return {};
81
- * return {
82
- * File(node) {
83
- * // Validated declarations for the file `context` is linting.
84
- * if (readDeclaredCommands(convention, context).length > 5) {
85
- * context.report({ node, messageId: 'tooMany' });
86
- * }
87
- * },
88
- * };
89
- * },
90
- * });
91
- * ```
41
+ * Use {@link getDeclaredCommands} to read validated declarations. This narrow
42
+ * resolver exists for consumers that also need a convention hook, such as
43
+ * `removeDeclaration`; it never exposes rule-specific binding policy.
92
44
  *
45
+ * @throws Error with `ESLINT_SH_DECLARATION_CONVENTION` for malformed bindings or optional hooks.
93
46
  * @public
94
47
  */
95
48
  export function resolveDeclarationConvention(context) {
96
- const ruleOptions = context.options[0];
97
- if (isObjectLike(ruleOptions) && ruleOptions[DECLARATION_CONVENTION_KEY] !== undefined) {
98
- const fromOption = ruleOptions[DECLARATION_CONVENTION_KEY];
99
- assertDeclarationConvention(fromOption, `option \`${DECLARATION_CONVENTION_KEY}\` of rule "${context.id}"`);
100
- return fromOption;
101
- }
102
49
  const shSettings = context.settings.sh;
103
50
  if (isObjectLike(shSettings) && shSettings[DECLARATION_CONVENTION_KEY] !== undefined) {
104
51
  const fromSettings = shSettings[DECLARATION_CONVENTION_KEY];
@@ -1,8 +1,13 @@
1
1
  import type { WrapperSpec } from 'sh-ast/analyze';
2
+ /**
3
+ * Checks a configured value and returns it typed: a non-empty command name,
4
+ * or a `WrapperSpec` object made of the JSON-expressible fields.
5
+ * @internal
6
+ */
7
+ export declare function validateWrapperSetting(value: unknown, setting: string): string | WrapperSpec;
2
8
  /**
3
9
  * Reads `settings.sh.networkWrapper`: the configured name or `WrapperSpec`,
4
- * or `undefined` when it is not set. Throws an error that starts
5
- * `Invalid settings.sh.networkWrapper:` when the value is malformed. Call it
10
+ * or `undefined` when it is not set. Throws `Error` with `ESLINT_SH_WRAPPER_SETTING` and the offending path when the value is malformed. Call it
6
11
  * from `create()`, so the error surfaces as ESLint's configuration message.
7
12
  *
8
13
  * @internal
@@ -17,3 +22,16 @@ export declare function readNetworkWrapperSetting(settings: Readonly<Record<stri
17
22
  * @internal
18
23
  */
19
24
  export declare function networkWrapperSpec(settings: Readonly<Record<string, unknown>>): WrapperSpec | null;
25
+ /**
26
+ * Whether overlapping wrapper names receive the same effective matcher grammar.
27
+ * Extra aliases are independent facts, not a conflict for the shared names.
28
+ * @internal
29
+ */
30
+ export declare function sameWrapperOptions(left: WrapperSpec, right: WrapperSpec): boolean;
31
+ /**
32
+ * Whether both specs approve the same names with the same effective grammar.
33
+ * Network policy compares the full name set: a transparent alias alone must
34
+ * not become an approved network wrapper. Name and flag order do not matter.
35
+ * @internal
36
+ */
37
+ export declare function sameWrapperSpec(left: WrapperSpec, right: WrapperSpec): boolean;
@@ -1,25 +1,8 @@
1
1
  /**
2
- * The shared `settings.sh.networkWrapper` binding: the one place a project
3
- * names the wrapper its network commands must run through, so every rule
4
- * whose findings depend on that wrapper reads the same declaration.
5
- *
6
- * Two different statements are involved, and this setting makes only one of
7
- * them:
8
- *
9
- * - **Policy:** network commands must run through this wrapper. That is what
10
- * `sh/require-network-wrapper` enforces, and this setting states it.
11
- * - **Fact:** this wrapper runs the command named after it. The policy implies
12
- * the fact (a wrapper that encloses `curl` runs `curl`), so
13
- * `sh/no-undeclared-commands` and `sh/no-unused-declarations` look through
14
- * the network wrapper when it is set here. The converse does not hold: a
15
- * transparent wrapper such as `with-lock` is not the network wrapper, and
16
- * stays in those rules' `transparentWrappers` option.
17
- *
18
- * ESLint gives a rule no way to read another rule's options, so a wrapper set
19
- * only as `require-network-wrapper`'s `wrapper` option is invisible to the
20
- * declaration rules. Shared settings are visible to every rule; that is why
21
- * the one declaration lives here.
2
+ * Reads the shared network policy and validates JSON-expressible wrapper specs.
3
+ * A network wrapper also supplies a transparent-wrapper fact to every consumer.
22
4
  */
5
+ import { configurationMessage } from '../configuration-message.js';
23
6
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-ast/analyze';
24
7
  /** The setting's dotted path, as error messages name it. */
25
8
  const SETTING = 'settings.sh.networkWrapper';
@@ -34,57 +17,65 @@ const KNOWN_FIELDS = new Set([
34
17
  ...STRING_LIST_FIELDS,
35
18
  'positionalOperandsBeforeCommand',
36
19
  'assignmentOperands',
20
+ 'shellBuiltin',
37
21
  ]);
38
22
  /** `true` when `value` is an array of non-empty strings. */
39
23
  function isStringList(value) {
40
24
  return (Array.isArray(value) &&
41
25
  value.every((item) => typeof item === 'string' && item.length > 0));
42
26
  }
43
- /** Throws the setting's configuration error with `detail`. */
44
- function invalid(detail) {
45
- throw new Error(`Invalid ${SETTING}: ${detail}`);
46
- }
47
27
  /**
48
28
  * Checks a configured value and returns it typed: a non-empty command name,
49
29
  * or a `WrapperSpec` object made of the JSON-expressible fields.
30
+ * @internal
50
31
  */
51
- function validate(value) {
32
+ export function validateWrapperSetting(value, setting) {
33
+ /** Names the configuration binding instead of exposing an analysis failure. */
34
+ function invalid(detail, field) {
35
+ // The setting owns malformed JSON specs; analysis errors keep their own identity.
36
+ const where = field === undefined ? setting : `${setting}.${field}`;
37
+ const received = field === undefined ? value : value[field];
38
+ throw Object.assign(new Error(configurationMessage(where, detail, received)), {
39
+ code: 'ESLINT_SH_WRAPPER_SETTING',
40
+ });
41
+ }
52
42
  if (typeof value === 'string') {
53
43
  if (value.length === 0)
54
- invalid('expected a command name or a wrapper spec, but got "".');
44
+ invalid('expected a command name or a wrapper spec');
55
45
  return value;
56
46
  }
57
47
  if (typeof value !== 'object' || value === null || Array.isArray(value)) {
58
- const got = value === null ? 'null' : Array.isArray(value) ? 'an array' : typeof value;
59
- invalid(`expected a command name or a wrapper spec ({ names: [...] }), but got ${got}.`);
48
+ invalid('expected a command name or a wrapper spec ({ names: [...] })');
60
49
  }
61
50
  const spec = value;
62
51
  for (const key of Object.keys(spec)) {
63
52
  if (!KNOWN_FIELDS.has(key))
64
- invalid(`unknown wrapper spec field \`${key}\`.`);
53
+ invalid('unknown wrapper spec field', key);
65
54
  }
66
55
  if (!isStringList(spec.names) || spec.names.length === 0) {
67
- invalid('`names` must be a non-empty array of non-empty strings.');
56
+ invalid('must be a non-empty array of non-empty strings', 'names');
68
57
  }
69
58
  for (const field of STRING_LIST_FIELDS) {
70
59
  if (spec[field] !== undefined && !isStringList(spec[field])) {
71
- invalid(`\`${field}\` must be an array of non-empty strings.`);
60
+ invalid('must be an array of non-empty strings', field);
72
61
  }
73
62
  }
63
+ if (spec.shellBuiltin !== undefined && typeof spec.shellBuiltin !== 'boolean') {
64
+ invalid('must be a boolean', 'shellBuiltin');
65
+ }
74
66
  const positional = spec.positionalOperandsBeforeCommand;
75
67
  if (positional !== undefined && !(Number.isInteger(positional) && positional >= 0)) {
76
- invalid('`positionalOperandsBeforeCommand` must be a non-negative integer.');
68
+ invalid('must be a non-negative integer', 'positionalOperandsBeforeCommand');
77
69
  }
78
70
  const assignment = spec.assignmentOperands;
79
71
  if (assignment !== undefined && !ASSIGNMENT_OPERANDS.includes(assignment)) {
80
- invalid(`\`assignmentOperands\` must be one of ${ASSIGNMENT_OPERANDS.join(', ')}.`);
72
+ invalid(`must be one of ${ASSIGNMENT_OPERANDS.join(', ')}`, 'assignmentOperands');
81
73
  }
82
74
  return spec;
83
75
  }
84
76
  /**
85
77
  * Reads `settings.sh.networkWrapper`: the configured name or `WrapperSpec`,
86
- * or `undefined` when it is not set. Throws an error that starts
87
- * `Invalid settings.sh.networkWrapper:` when the value is malformed. Call it
78
+ * or `undefined` when it is not set. Throws `Error` with `ESLINT_SH_WRAPPER_SETTING` and the offending path when the value is malformed. Call it
88
79
  * from `create()`, so the error surfaces as ESLint's configuration message.
89
80
  *
90
81
  * @internal
@@ -94,7 +85,7 @@ export function readNetworkWrapperSetting(settings) {
94
85
  if (typeof sh !== 'object' || sh === null)
95
86
  return undefined;
96
87
  const value = sh.networkWrapper;
97
- return value === undefined ? undefined : validate(value);
88
+ return value === undefined ? undefined : validateWrapperSetting(value, SETTING);
98
89
  }
99
90
  /**
100
91
  * The `WrapperSpec` for the network wrapper set in `settings.sh.networkWrapper`,
@@ -114,3 +105,47 @@ export function networkWrapperSpec(settings) {
114
105
  names: [wrapper],
115
106
  });
116
107
  }
108
+ /**
109
+ * Canonical effective grammar from sh-ast's WrapperSpec matcher, excluding
110
+ * the names that select it. Flags are membership sets; omitted lists are empty,
111
+ * shellBuiltin defaults to false (utility matching), and positional count
112
+ * defaults to zero. An explicit assignment grammar supersedes the legacy
113
+ * shell-identifier alias; otherwise there is no assignment grammar.
114
+ *
115
+ * Expanded built-ins may contain a flag pattern even though JSON settings may
116
+ * not. Compare its source and flags structurally, including absence, rather
117
+ * than attempting regex-language equivalence or inheriting omitted fields.
118
+ */
119
+ function canonicalWrapperGrammar(spec) {
120
+ /** Stable membership representation for the matcher's four flag lists. */
121
+ const flags = (values) => [...new Set(values ?? [])].sort();
122
+ const pattern = spec.noArgFlagPattern;
123
+ return JSON.stringify({
124
+ noArgFlags: flags(spec.noArgFlags),
125
+ argFlags: flags(spec.argFlags),
126
+ unresolvableFlags: flags(spec.unresolvableFlags),
127
+ stopsChainFlags: flags(spec.stopsChainFlags),
128
+ shellBuiltin: spec.shellBuiltin ?? false,
129
+ positionalOperandsBeforeCommand: spec.positionalOperandsBeforeCommand ?? 0,
130
+ assignmentOperands: spec.assignmentOperands ?? (spec.skipAssignmentOperands === true ? 'shell-identifier' : null),
131
+ noArgFlagPattern: pattern === undefined ? null : { source: pattern.source, flags: pattern.flags },
132
+ });
133
+ }
134
+ /**
135
+ * Whether overlapping wrapper names receive the same effective matcher grammar.
136
+ * Extra aliases are independent facts, not a conflict for the shared names.
137
+ * @internal
138
+ */
139
+ export function sameWrapperOptions(left, right) {
140
+ return canonicalWrapperGrammar(left) === canonicalWrapperGrammar(right);
141
+ }
142
+ /**
143
+ * Whether both specs approve the same names with the same effective grammar.
144
+ * Network policy compares the full name set: a transparent alias alone must
145
+ * not become an approved network wrapper. Name and flag order do not matter.
146
+ * @internal
147
+ */
148
+ export function sameWrapperSpec(left, right) {
149
+ return (JSON.stringify([...left.names].sort()) === JSON.stringify([...right.names].sort()) &&
150
+ sameWrapperOptions(left, right));
151
+ }
@@ -0,0 +1,38 @@
1
+ import type { SettingsConfig } from '@eslint/core';
2
+ import type { WrapperSpec } from 'sh-ast/analyze';
3
+ import type { ShellSourceCode } from '../language/shell-source-code.js';
4
+ /** The rule-context fields needed to resolve shared wrappers and their path spellings. @public */
5
+ export interface TransparentWrappersBindingContext {
6
+ /** Shared ESLint configuration containing the project's shell facts. */
7
+ readonly settings: SettingsConfig;
8
+ /** The current file supplies path spellings without filesystem inspection or execution. */
9
+ readonly sourceCode: ShellSourceCode;
10
+ }
11
+ /**
12
+ * Returns the shared project wrappers followed by `builtIns` (defaults when
13
+ * omitted). Entries accept command names or JSON-expressible `WrapperSpec`s
14
+ * in `settings: { sh: { transparentWrappers: [...] } }`. The shared network
15
+ * wrapper is also transparent; conflicting specs for the same project name
16
+ * throw rather than allowing policies to disagree. Shared specs compare effective
17
+ * grammars for overlapping names, normalizing matcher defaults and retaining
18
+ * expanded built-in flag patterns; an extra transparent alias does not acquire
19
+ * network approval. Explicit specs remain complete replacements. Duplicate project
20
+ * names are rejected so list order cannot silently choose their meaning.
21
+ *
22
+ * Utility wrappers match absolute and relative paths by basename. Path words
23
+ * remain unchanged in analysis results. `shellBuiltin: true` entries match
24
+ * exact names only: an executable path cannot acquire in-process semantics.
25
+ * An explicit path spec takes precedence over a basename fallback regardless
26
+ * of configuration order.
27
+ * Aliases are built even when only `builtIns` are supplied. Overridden names
28
+ * are removed from lower-priority entries, preserving their unrelated aliases
29
+ * and preventing a utility entry from undoing an exact-name builtin override.
30
+ * The input tables are never mutated.
31
+ *
32
+ * @param context - The consuming rule's context.
33
+ * @param builtIns - The rule's own built-in wrapper scope.
34
+ * @throws Error with `ESLINT_SH_WRAPPER_SETTING` for malformed bindings, or
35
+ * `ESLINT_SH_WRAPPER_CONFLICT` for duplicate names or contradictory shared policies.
36
+ * @public
37
+ */
38
+ export declare function resolveTransparentWrappers(context: TransparentWrappersBindingContext, builtIns?: readonly WrapperSpec[]): readonly WrapperSpec[];