@eslint-sh/eslint-plugin 0.8.0 → 0.10.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 (116) hide show
  1. package/README.md +58 -57
  2. package/dist/api.d.ts +92 -0
  3. package/dist/api.js +83 -0
  4. package/dist/command-harvest/builtins/bats.d.ts +1 -1
  5. package/dist/command-harvest/harvest-commands.d.ts +18 -7
  6. package/dist/command-harvest/harvest-commands.js +11 -10
  7. package/dist/command-harvest/wrapper-table.d.ts +1 -1
  8. package/dist/command-harvest/wrapper-table.js +1 -1
  9. package/dist/configs/posix-portable.d.ts +6 -10
  10. package/dist/configs/posix-portable.js +4 -6
  11. package/dist/configuration-message.d.ts +14 -0
  12. package/dist/configuration-message.js +33 -0
  13. package/dist/declaration-conventions/get-declared-commands.d.ts +41 -0
  14. package/dist/declaration-conventions/{read-declared-commands.js → get-declared-commands.js} +43 -43
  15. package/dist/eslint-plugin-api.d.ts +1516 -0
  16. package/dist/eslint-plugin.d.ts +16 -1560
  17. package/dist/index.d.ts +14 -81
  18. package/dist/index.js +22 -76
  19. package/dist/language/command-resolution.d.ts +47 -13
  20. package/dist/language/command-resolution.js +48 -18
  21. package/dist/language/selector-classes.d.ts +7 -3
  22. package/dist/language/selector-classes.js +13 -4
  23. package/dist/language/shell-language-options.d.ts +3 -3
  24. package/dist/language/shell-language-options.js +12 -17
  25. package/dist/language/shell-language.d.ts +3 -1
  26. package/dist/language/shell-language.js +6 -11
  27. package/dist/language/shell-source-code.d.ts +77 -77
  28. package/dist/language/shell-source-code.js +107 -98
  29. package/dist/language/source-coordinates.d.ts +2 -0
  30. package/dist/language/source-coordinates.js +8 -4
  31. package/dist/language/syntax-view.d.ts +1 -1
  32. package/dist/language/syntax-view.js +19 -7
  33. package/dist/language/word-resolution.d.ts +4 -3
  34. package/dist/language/word-resolution.js +10 -5
  35. package/dist/rules/compat/declaration-options.js +2 -2
  36. package/dist/rules/compat/no-brace-sequence-padding-step.js +1 -1
  37. package/dist/rules/compat/no-mapfile.js +2 -2
  38. package/dist/rules/compat/no-negative-array-index.js +2 -2
  39. package/dist/rules/compat/no-printf-time-format.js +2 -2
  40. package/dist/rules/compat/no-test-v.js +2 -2
  41. package/dist/rules/compat/no-wait-n.js +2 -2
  42. package/dist/rules/compat/posix-absent-command.js +2 -2
  43. package/dist/rules/compat/shopt-options.js +2 -2
  44. package/dist/rules/create-wrapper-rule.d.ts +4 -4
  45. package/dist/rules/create-wrapper-rule.js +19 -13
  46. package/dist/rules/define-shell-rule.js +1 -1
  47. package/dist/rules/no-dynamic-invocation.d.ts +1 -1
  48. package/dist/rules/no-dynamic-invocation.js +12 -4
  49. package/dist/rules/no-eval.js +6 -2
  50. package/dist/rules/no-masked-exit-status.d.ts +4 -3
  51. package/dist/rules/no-masked-exit-status.js +4 -3
  52. package/dist/rules/no-secret-env-reads.d.ts +2 -0
  53. package/dist/rules/no-secret-env-reads.js +14 -3
  54. package/dist/rules/no-secret-flags.d.ts +2 -0
  55. package/dist/rules/no-secret-flags.js +14 -3
  56. package/dist/rules/no-unchecked-cd.js +4 -3
  57. package/dist/rules/no-undeclared-commands.js +10 -4
  58. package/dist/rules/no-unused-declarations.js +13 -4
  59. package/dist/rules/prefer-local.d.ts +3 -2
  60. package/dist/rules/prefer-local.js +4 -2
  61. package/dist/rules/quote-expansions.js +1 -1
  62. package/dist/rules/require-network-wrapper.d.ts +2 -2
  63. package/dist/rules/require-network-wrapper.js +21 -11
  64. package/dist/rules/require-strict-mode.d.ts +5 -46
  65. package/dist/rules/require-strict-mode.js +17 -107
  66. package/dist/rules/require-tty-guard.d.ts +2 -0
  67. package/dist/rules/require-tty-guard.js +9 -2
  68. package/dist/rules/resolve-declaration-convention.d.ts +9 -88
  69. package/dist/rules/resolve-declaration-convention.js +19 -71
  70. package/dist/rules/resolve-network-wrapper.d.ts +3 -4
  71. package/dist/rules/resolve-network-wrapper.js +23 -19
  72. package/dist/rules/resolve-transparent-wrappers.d.ts +3 -8
  73. package/dist/rules/resolve-transparent-wrappers.js +21 -11
  74. package/dist/rules/set-options.d.ts +1 -1
  75. package/dist/rules/set-options.js +1 -1
  76. package/dist/rules/strict-mode-prologue.d.ts +43 -0
  77. package/dist/rules/strict-mode-prologue.js +91 -0
  78. package/dist/rules/transparent-wrappers.d.ts +3 -3
  79. package/dist/rules/transparent-wrappers.js +1 -1
  80. package/dist/rules/user-pattern.d.ts +4 -3
  81. package/dist/rules/user-pattern.js +10 -8
  82. package/dist/shell-dialect.d.ts +8 -0
  83. package/dist/shell-dialect.js +22 -0
  84. package/dist/version.js +2 -1
  85. package/docs/compat.md +5 -6
  86. package/docs/custom-rule-tutorial.md +55 -51
  87. package/docs/declaration-conventions.md +20 -23
  88. package/docs/error-codes.md +94 -0
  89. package/docs/examples/no-backticks-rule.mjs +1 -1
  90. package/docs/examples/no-curl-in-functions-rule.mjs +2 -2
  91. package/docs/examples/no-listed-commands-rule.ts +1 -1
  92. package/docs/examples/no-rm-rf-rule.mjs +8 -10
  93. package/docs/examples/sorted-declarations-rule.mjs +6 -9
  94. package/docs/examples/tsconfig.json +10 -0
  95. package/docs/rules/README.md +12 -4
  96. package/docs/rules/compat/no-nounset-empty-array.md +1 -1
  97. package/docs/rules/no-dynamic-invocation.md +5 -0
  98. package/docs/rules/no-masked-exit-status.md +2 -2
  99. package/docs/rules/no-secret-env-reads.md +13 -3
  100. package/docs/rules/no-secret-flags.md +14 -5
  101. package/docs/rules/no-unchecked-cd.md +15 -2
  102. package/docs/rules/no-undeclared-commands.md +4 -0
  103. package/docs/rules/no-unused-declarations.md +4 -0
  104. package/docs/rules/require-network-wrapper.md +6 -6
  105. package/docs/rules/require-strict-mode.md +25 -23
  106. package/docs/rules/require-tty-guard.md +12 -3
  107. package/docs/selectors.md +7 -2
  108. package/docs/wrapper-rules.md +3 -1
  109. package/package.json +9 -20
  110. package/dist/declaration-conventions/read-declared-commands.d.ts +0 -70
  111. package/dist/eslint-plugin-syntax-analyze.d.ts +0 -23
  112. package/dist/eslint-plugin-syntax.d.ts +0 -31
  113. package/dist/syntax/analyze.d.ts +0 -19
  114. package/dist/syntax/analyze.js +0 -21
  115. package/dist/syntax/index.d.ts +0 -27
  116. package/dist/syntax/index.js +0 -29
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * @internal
5
5
  */
6
- export interface PreferLocalOptions {
6
+ interface PreferLocalOptions {
7
7
  /** Variable names that may be assigned in a function without `local`. */
8
8
  readonly allow?: readonly string[];
9
9
  /**
@@ -13,4 +13,5 @@ export interface PreferLocalOptions {
13
13
  readonly allowPattern?: string;
14
14
  }
15
15
  /** Built-in rule `sh/prefer-local`. @internal */
16
- export declare const preferLocal: import("./define-shell-rule.js").ShellRule<[PreferLocalOptions], "preferLocal">;
16
+ declare const preferLocal: import("./define-shell-rule.js").ShellRule<[PreferLocalOptions], "preferLocal">;
17
+ export { preferLocal };
@@ -140,7 +140,7 @@ function scopeBindings(root, sourceCode, lastpipe) {
140
140
  return found.sort((a, b) => a.node.range[0] - b.node.range[0]);
141
141
  }
142
142
  /** Built-in rule `sh/prefer-local`. @internal */
143
- export const preferLocal = createRule({
143
+ const preferLocal = createRule({
144
144
  name: 'prefer-local',
145
145
  meta: {
146
146
  type: 'suggestion',
@@ -167,7 +167,8 @@ export const preferLocal = createRule({
167
167
  const { sourceCode } = context;
168
168
  const [options] = context.options;
169
169
  const allowed = new Set(options.allow ?? []);
170
- const allowPattern = compileUserPattern('sh/prefer-local', 'allowPattern', options.allowPattern ?? DEFAULT_ALLOW_PATTERN, 'u');
170
+ // The configured ID owns option paths, independently of the rule's registry name.
171
+ const allowPattern = compileUserPattern(context.id, 'allowPattern', options.allowPattern ?? DEFAULT_ALLOW_PATTERN, 'u');
171
172
  // Validate configuration in every dialect, even where the rule is inert.
172
173
  // `local` is not POSIX: under `posix` there is nothing to declare with.
173
174
  if (sourceCode.dialect === 'posix')
@@ -248,3 +249,4 @@ export const preferLocal = createRule({
248
249
  };
249
250
  },
250
251
  });
252
+ export { preferLocal };
@@ -38,7 +38,7 @@
38
38
  * autofix, because a script may rely on the splitting (for example
39
39
  * `$CFLAGS` holding several flags), and only its author can say so.
40
40
  */
41
- import { DashHdoc, Hdoc } from 'sh-ast/analyze';
41
+ import { DashHdoc, Hdoc } from 'sh-ast';
42
42
  import { createRule } from './create-rule.js';
43
43
  import { isBashIntegerVariable } from './bash-variable-semantics.js';
44
44
  import { messageExcerpt } from '../language/line-breaks.js';
@@ -1,4 +1,4 @@
1
- import type { WrapperSpec } from 'sh-ast/analyze';
1
+ import type { WrapperSpec } from 'sh-analysis';
2
2
  /**
3
3
  * The options of `sh/require-network-wrapper`.
4
4
  *
@@ -15,7 +15,7 @@ export interface RequireNetworkWrapperOptions {
15
15
  */
16
16
  readonly wrapper?: string | WrapperSpec;
17
17
  /** Commands checked in addition to `commands` (or its default). */
18
- readonly alsoTreatAsNetwork?: readonly string[];
18
+ readonly additionalCommands?: readonly string[];
19
19
  }
20
20
  /**
21
21
  * The `sh/require-network-wrapper` rule module.
@@ -13,8 +13,13 @@
13
13
  * `git` counts only for the subcommands that talk to a remote (`fetch`,
14
14
  * `clone`, `pull`, `push`), found after git's own global options
15
15
  * (`git -C dir fetch`).
16
+ *
17
+ * This policy checks represented, statically identified commands. Opaque executable
18
+ * syntax is outside that named-command scope; no-dynamic-invocation reports those
19
+ * inventory limits when a project requires execution completeness.
16
20
  */
17
- import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-ast/analyze';
21
+ import { configurationMessage } from '../configuration-message.js';
22
+ import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
18
23
  import { createRule } from './create-rule.js';
19
24
  import { WRAPPER_RULE_MESSAGES, buildWrapperRule } from './create-wrapper-rule.js';
20
25
  import { networkWrapperSpec, readNetworkWrapperSetting, sameWrapperSpec, } from './resolve-network-wrapper.js';
@@ -88,7 +93,7 @@ const GIT_NETWORK_SUBCOMMANDS = {
88
93
  /**
89
94
  * The subcommand restrictions this rule always applies: `git` counts only for
90
95
  * its network subcommands, whether it comes from the default `commands`, a
91
- * configured `commands`, or `alsoTreatAsNetwork`.
96
+ * configured `commands`, or `additionalCommands`.
92
97
  */
93
98
  const NETWORK_SUBCOMMANDS = {
94
99
  git: GIT_NETWORK_SUBCOMMANDS,
@@ -185,9 +190,11 @@ const STRING_LIST_SCHEMA = {
185
190
  };
186
191
  /**
187
192
  * The JSON-expressible form of a `WrapperSpec`, for the `wrapper` option.
188
- * `noArgFlagPattern` (a `RegExp`) and the legacy `skipAssignmentOperands` are
189
- * left out; a rule pack that needs them binds its wrapper with
190
- * `createWrapperRule` instead.
193
+ * Assignment-like operands are skipped only under an explicit
194
+ * `assignmentOperands` grammar (`shell-identifier`, `env`, or `sudo`);
195
+ * omission leaves them available as command candidates. `noArgFlagPattern`
196
+ * is a `RegExp`, so a rule pack needing a flag pattern binds its wrapper
197
+ * with `createWrapperRule` instead of JSON configuration.
191
198
  */
192
199
  const WRAPPER_SPEC_SCHEMA = {
193
200
  type: 'object',
@@ -206,9 +213,10 @@ const WRAPPER_SPEC_SCHEMA = {
206
213
  };
207
214
  /**
208
215
  * Resolves the factory config this rule enforces for one set of options, or
209
- * `null` when no wrapper is configured.
216
+ * `null` when no wrapper is configured. The configured rule ID names local
217
+ * options; shared project facts always retain the canonical settings.sh path.
210
218
  */
211
- function wrapperRuleConfig(options, settings) {
219
+ function wrapperRuleConfig(options, settings, ruleId) {
212
220
  const shared = readNetworkWrapperSetting(settings);
213
221
  if (options?.wrapper !== undefined && shared !== undefined) {
214
222
  const configured = options.wrapper;
@@ -219,16 +227,18 @@ function wrapperRuleConfig(options, settings) {
219
227
  : configured;
220
228
  const network = networkWrapperSpec(settings);
221
229
  if (network !== null && !sameWrapperSpec(option, network)) {
222
- throw new Error('sh/require-network-wrapper: `wrapper` conflicts with the shared networkWrapper; configure one shared network policy.');
230
+ throw Object.assign(new Error(configurationMessage(`rules[${JSON.stringify(ruleId)}].wrapper`, 'conflicts with settings.sh.networkWrapper; configure one shared network policy', configured)), { code: 'ESLINT_SH_WRAPPER_CONFLICT' });
223
231
  }
224
232
  }
225
233
  const wrapper = shared ?? options?.wrapper;
226
234
  if (wrapper === undefined)
227
235
  return null;
228
236
  return {
237
+ // An explicit replacement (even []) selects the base; additions extend it.
238
+ // The factory normalizes names to a set, so overlap never multiplies reports.
229
239
  commands: [
230
240
  ...(options?.commands ?? DEFAULT_NETWORK_COMMANDS),
231
- ...(options?.alsoTreatAsNetwork ?? []),
241
+ ...(options?.additionalCommands ?? []),
232
242
  ],
233
243
  wrapper,
234
244
  subcommands: NETWORK_SUBCOMMANDS,
@@ -253,7 +263,7 @@ export const requireNetworkWrapper = createRule({
253
263
  properties: {
254
264
  commands: STRING_LIST_SCHEMA,
255
265
  wrapper: { oneOf: [{ type: 'string', minLength: 1 }, WRAPPER_SPEC_SCHEMA] },
256
- alsoTreatAsNetwork: STRING_LIST_SCHEMA,
266
+ additionalCommands: STRING_LIST_SCHEMA,
257
267
  },
258
268
  additionalProperties: false,
259
269
  },
@@ -261,7 +271,7 @@ export const requireNetworkWrapper = createRule({
261
271
  messages: WRAPPER_RULE_MESSAGES,
262
272
  },
263
273
  create(context) {
264
- const config = wrapperRuleConfig(context.options[0], context.settings);
274
+ const config = wrapperRuleConfig(context.options[0], context.settings, context.id);
265
275
  if (config === null)
266
276
  return {};
267
277
  // The check itself is the rule `createWrapperRule` makes for this config
@@ -1,52 +1,11 @@
1
- import type { ShellFile, ShellNodeOf } from '../language/syntax-view.js';
2
- import type { ShellSourceCode } from '../language/shell-source-code.js';
3
- import type { SetOptionChange } from './set-options.js';
4
- /**
5
- * The rule's single options object.
6
- *
7
- * @internal
8
- */
1
+ /** The policy's required options; prologue recognition is a shared project fact. @internal */
9
2
  export interface RequireStrictModeOptions {
10
3
  /**
11
- * The required prologue: either a `set` command (`"set -euo pipefail"`),
12
- * whose enabled options become the requirement and whose text is what the
13
- * autofix inserts, or the list of required long option names
14
- * (`["errexit", "nounset"]`), for which the autofix inserts a `set` command
15
- * spelled from that list. When omitted, it is `"set -eu"` for a file
16
- * whose dialect is `posix` and `"set -euo pipefail"` for every other
17
- * dialect.
4
+ * Nonempty, unique long option names from the existing `set -o` domain.
5
+ * When absent, POSIX requires errexit/nounset and other dialects also require
6
+ * pipefail. The formatter, rather than consumer text, owns autofix spelling.
18
7
  */
19
- readonly mode?: string | readonly string[];
20
- /**
21
- * When `true`, options passed to the shell on the shebang line
22
- * (`#!/bin/bash -e`, `#!/usr/bin/env -S bash -euo pipefail`) count as
23
- * enabled, so a shebang alone can satisfy the rule. Off by default, because
24
- * those options are ignored when the script is run as `bash script.sh`.
25
- */
26
- readonly allowShebangOnly?: boolean;
27
- /** How many top-level statements, from the top, the prologue may take to appear. */
28
- readonly withinStatements?: number;
8
+ readonly requiredOptions?: readonly string[];
29
9
  }
30
- /**
31
- * Whether `stmt` is a plain, foreground, top-level `set` command, and if so
32
- * the option changes its arguments make (read through `sourceCode`, so a
33
- * non-static argument ends the reading).
34
- *
35
- * @internal
36
- */
37
- export declare function setStatementChanges(stmt: ShellNodeOf<'Stmt'>, sourceCode: ShellSourceCode): readonly SetOptionChange[];
38
- /**
39
- * The options a file's prologue leaves enabled: the state after the first
40
- * `withinStatements` top-level statements of `file`, plus the shebang's
41
- * options when `allowShebangOnly` is set. This is the single definition of
42
- * "what the prologue enables", shared with other rules (such as
43
- * `no-unchecked-cd`) that need to know whether strict mode is in force.
44
- *
45
- * @internal
46
- */
47
- export declare function prologueEnabledOptions(file: ShellFile, sourceCode: ShellSourceCode, config?: {
48
- readonly allowShebangOnly?: boolean;
49
- readonly withinStatements?: number;
50
- }): ReadonlySet<string>;
51
10
  /** Built-in rule `sh/require-strict-mode`. @internal */
52
11
  export declare const requireStrictMode: import("./define-shell-rule.js").ShellRule<[RequireStrictModeOptions], "missingStrictMode">;
@@ -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';
@@ -30,7 +30,7 @@
30
30
  * that here-document's terminator and would carry the other command into the
31
31
  * guard.
32
32
  */
33
- import { DashHdoc, Hdoc } from 'sh-ast/analyze';
33
+ import { DashHdoc, Hdoc } from 'sh-ast';
34
34
  import { createRule } from './create-rule.js';
35
35
  import { lineBreakOf } from '../language/line-breaks.js';
36
36
  /** Registry name of this rule. */
@@ -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,95 +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: convention } }`, else `null`
56
- * (the rule is inert).
57
- *
58
- * Throws an `Error` naming the offending setting when the configured value is
59
- * present but does not implement `declaredCommands` (or has a non-function
60
- * `removeDeclaration`). The message names where the value came from and what
61
- * it was, including the expected convention shape and the received value.
62
- * Call it from `create()`, so the error surfaces as ESLint's configuration
63
- * 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
- * ```
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.
92
10
  *
11
+ * @throws Error with `ESLINT_SH_DECLARATION_CONVENTION` for malformed bindings or optional hooks.
93
12
  * @public
94
13
  */
95
- 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,64 +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: convention } }`, else `null`
55
- * (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.
56
40
  *
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, including the expected convention shape and the received value.
61
- * Call it from `create()`, so the error surfaces as ESLint's configuration
62
- * message for the file being linted.
63
- *
64
- * A rule that receives `null` should register no listeners: with no
65
- * convention bound, a convention consumer has nothing to check.
66
- *
67
- * @example
68
- * ```ts
69
- * import {
70
- * defineShellRule,
71
- * readDeclaredCommands,
72
- * resolveDeclarationConvention,
73
- * } from '@eslint-sh/eslint-plugin';
74
- *
75
- * export const maxDeclaredCommands = defineShellRule({
76
- * meta: { schema: [], messages: { tooMany: 'Declare at most 5 commands.' } },
77
- * create(context) {
78
- * const convention = resolveDeclarationConvention(context);
79
- * if (convention === null) return {};
80
- * return {
81
- * File(node) {
82
- * // Validated declarations for the file `context` is linting.
83
- * if (readDeclaredCommands(convention, context).length > 5) {
84
- * context.report({ node, messageId: 'tooMany' });
85
- * }
86
- * },
87
- * };
88
- * },
89
- * });
90
- * ```
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.
91
44
  *
45
+ * @throws Error with `ESLINT_SH_DECLARATION_CONVENTION` for malformed bindings or optional hooks.
92
46
  * @public
93
47
  */
94
48
  export function resolveDeclarationConvention(context) {
95
- const ruleOptions = context.options[0];
96
- if (isObjectLike(ruleOptions) && ruleOptions[DECLARATION_CONVENTION_KEY] !== undefined) {
97
- const fromOption = ruleOptions[DECLARATION_CONVENTION_KEY];
98
- assertDeclarationConvention(fromOption, `option \`${DECLARATION_CONVENTION_KEY}\` of rule "${context.id}"`);
99
- return fromOption;
100
- }
101
49
  const shSettings = context.settings.sh;
102
50
  if (isObjectLike(shSettings) && shSettings[DECLARATION_CONVENTION_KEY] !== undefined) {
103
51
  const fromSettings = shSettings[DECLARATION_CONVENTION_KEY];