@eslint-sh/eslint-plugin 0.8.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 (91) hide show
  1. package/README.md +41 -34
  2. package/dist/api.d.ts +92 -0
  3. package/dist/api.js +83 -0
  4. package/dist/command-harvest/harvest-commands.d.ts +2 -2
  5. package/dist/command-harvest/harvest-commands.js +2 -2
  6. package/dist/configs/posix-portable.d.ts +6 -10
  7. package/dist/configs/posix-portable.js +4 -6
  8. package/dist/configuration-message.d.ts +14 -0
  9. package/dist/configuration-message.js +33 -0
  10. package/dist/declaration-conventions/get-declared-commands.d.ts +41 -0
  11. package/dist/declaration-conventions/{read-declared-commands.js → get-declared-commands.js} +43 -43
  12. package/dist/eslint-plugin-api.d.ts +1506 -0
  13. package/dist/eslint-plugin-syntax-analyze.d.ts +3 -3
  14. package/dist/eslint-plugin-syntax.d.ts +3 -4
  15. package/dist/eslint-plugin.d.ts +16 -1560
  16. package/dist/index.d.ts +14 -81
  17. package/dist/index.js +22 -76
  18. package/dist/language/command-resolution.d.ts +5 -5
  19. package/dist/language/command-resolution.js +11 -7
  20. package/dist/language/selector-classes.d.ts +7 -3
  21. package/dist/language/selector-classes.js +13 -4
  22. package/dist/language/shell-language-options.d.ts +3 -3
  23. package/dist/language/shell-language-options.js +12 -17
  24. package/dist/language/shell-language.d.ts +3 -1
  25. package/dist/language/shell-language.js +6 -11
  26. package/dist/language/shell-source-code.d.ts +59 -42
  27. package/dist/language/shell-source-code.js +86 -60
  28. package/dist/language/source-coordinates.d.ts +2 -0
  29. package/dist/language/source-coordinates.js +8 -4
  30. package/dist/language/syntax-view.js +19 -7
  31. package/dist/language/word-resolution.d.ts +2 -1
  32. package/dist/language/word-resolution.js +8 -3
  33. package/dist/rules/create-wrapper-rule.d.ts +1 -1
  34. package/dist/rules/create-wrapper-rule.js +11 -9
  35. package/dist/rules/define-shell-rule.js +1 -1
  36. package/dist/rules/no-masked-exit-status.d.ts +4 -3
  37. package/dist/rules/no-masked-exit-status.js +3 -2
  38. package/dist/rules/no-secret-env-reads.d.ts +2 -0
  39. package/dist/rules/no-secret-env-reads.js +13 -2
  40. package/dist/rules/no-secret-flags.d.ts +2 -0
  41. package/dist/rules/no-secret-flags.js +14 -3
  42. package/dist/rules/no-unchecked-cd.js +3 -2
  43. package/dist/rules/no-undeclared-commands.js +8 -3
  44. package/dist/rules/no-unused-declarations.js +6 -2
  45. package/dist/rules/prefer-local.d.ts +3 -2
  46. package/dist/rules/prefer-local.js +4 -2
  47. package/dist/rules/require-network-wrapper.d.ts +1 -1
  48. package/dist/rules/require-network-wrapper.js +11 -7
  49. package/dist/rules/require-strict-mode.d.ts +5 -46
  50. package/dist/rules/require-strict-mode.js +17 -107
  51. package/dist/rules/require-tty-guard.d.ts +2 -0
  52. package/dist/rules/require-tty-guard.js +8 -1
  53. package/dist/rules/resolve-declaration-convention.d.ts +9 -88
  54. package/dist/rules/resolve-declaration-convention.js +19 -71
  55. package/dist/rules/resolve-network-wrapper.d.ts +1 -2
  56. package/dist/rules/resolve-network-wrapper.js +18 -14
  57. package/dist/rules/resolve-transparent-wrappers.d.ts +2 -7
  58. package/dist/rules/resolve-transparent-wrappers.js +19 -9
  59. package/dist/rules/set-options.d.ts +1 -1
  60. package/dist/rules/set-options.js +1 -1
  61. package/dist/rules/strict-mode-prologue.d.ts +43 -0
  62. package/dist/rules/strict-mode-prologue.js +91 -0
  63. package/dist/rules/user-pattern.d.ts +4 -3
  64. package/dist/rules/user-pattern.js +10 -8
  65. package/dist/shell-dialect.d.ts +8 -0
  66. package/dist/shell-dialect.js +22 -0
  67. package/dist/syntax/analyze.d.ts +3 -3
  68. package/dist/syntax/analyze.js +3 -3
  69. package/dist/syntax/index.d.ts +3 -4
  70. package/dist/syntax/index.js +3 -4
  71. package/dist/version.js +2 -1
  72. package/docs/compat.md +5 -6
  73. package/docs/custom-rule-tutorial.md +22 -18
  74. package/docs/declaration-conventions.md +20 -23
  75. package/docs/error-codes.md +93 -0
  76. package/docs/examples/no-rm-rf-rule.mjs +8 -10
  77. package/docs/examples/sorted-declarations-rule.mjs +6 -9
  78. package/docs/examples/tsconfig.json +10 -0
  79. package/docs/rules/README.md +12 -4
  80. package/docs/rules/compat/no-nounset-empty-array.md +1 -1
  81. package/docs/rules/no-masked-exit-status.md +2 -2
  82. package/docs/rules/no-secret-env-reads.md +13 -3
  83. package/docs/rules/no-secret-flags.md +14 -5
  84. package/docs/rules/no-unchecked-cd.md +15 -2
  85. package/docs/rules/require-network-wrapper.md +5 -5
  86. package/docs/rules/require-strict-mode.md +25 -23
  87. package/docs/rules/require-tty-guard.md +12 -3
  88. package/docs/selectors.md +7 -2
  89. package/docs/wrapper-rules.md +2 -0
  90. package/package.json +3 -3
  91. package/dist/declaration-conventions/read-declared-commands.d.ts +0 -70
@@ -0,0 +1,91 @@
1
+ /**
2
+ * The shared definition of where a script establishes shell options. Policy
3
+ * rules consume the same normalized project fact, without owning one another's
4
+ * requirements or retaining state across configs or files.
5
+ * ESLINT_SH_STRICT_MODE_SETTING identifies a malformed project prologue fact;
6
+ * rule-option schema failures remain ESLint responsibilities.
7
+ */
8
+ import { configurationMessage } from '../configuration-message.js';
9
+ import { applySetOptionChanges, parseSetArguments, shebangOptionChanges } from './set-options.js';
10
+ /** The user-written path of the shared project fact, extended with its offending field. */
11
+ const SETTING = 'settings.sh.strictModePrologue';
12
+ /**
13
+ * Normalizes the shared project fact at rule creation, following the other
14
+ * shared-settings resolvers: absence uses defaults, malformed explicit values
15
+ * throw a named configuration error. No cache can leak a file's configuration.
16
+ * @throws Error with `ESLINT_SH_STRICT_MODE_SETTING` for malformed shared project facts.
17
+ * @internal
18
+ */
19
+ export function resolveStrictModePrologue(settings) {
20
+ const sh = settings.sh;
21
+ const value = typeof sh === 'object' && sh !== null && 'strictModePrologue' in sh
22
+ ? sh.strictModePrologue
23
+ : undefined;
24
+ if (value === undefined) {
25
+ return { allowShebangOnly: false, withinStatements: 5 };
26
+ }
27
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
28
+ throw Object.assign(new Error(configurationMessage(SETTING, 'expected a prologue definition object', value)), { code: 'ESLINT_SH_STRICT_MODE_SETTING' });
29
+ }
30
+ for (const key of Object.keys(value)) {
31
+ if (key !== 'allowShebangOnly' && key !== 'withinStatements') {
32
+ throw Object.assign(new Error(configurationMessage(`${SETTING}.${key}`, 'unknown prologue definition field', value[key])), { code: 'ESLINT_SH_STRICT_MODE_SETTING' });
33
+ }
34
+ }
35
+ const allowShebangOnly = 'allowShebangOnly' in value ? value.allowShebangOnly : undefined;
36
+ const withinStatements = 'withinStatements' in value ? value.withinStatements : undefined;
37
+ if (allowShebangOnly !== undefined && typeof allowShebangOnly !== 'boolean') {
38
+ throw Object.assign(new Error(configurationMessage(`${SETTING}.allowShebangOnly`, 'must be a boolean', allowShebangOnly)), { code: 'ESLINT_SH_STRICT_MODE_SETTING' });
39
+ }
40
+ if (withinStatements !== undefined &&
41
+ (typeof withinStatements !== 'number' ||
42
+ !Number.isInteger(withinStatements) ||
43
+ withinStatements < 1)) {
44
+ throw Object.assign(new Error(configurationMessage(`${SETTING}.withinStatements`, 'must be a positive integer', withinStatements)), { code: 'ESLINT_SH_STRICT_MODE_SETTING' });
45
+ }
46
+ return { allowShebangOnly: allowShebangOnly ?? false, withinStatements: withinStatements ?? 5 };
47
+ }
48
+ /**
49
+ * Whether `stmt` is a plain, foreground, top-level `set` command, and if so
50
+ * the option changes its arguments make (read through `sourceCode`, so a
51
+ * non-static argument ends the reading).
52
+ *
53
+ * @internal
54
+ */
55
+ export function setStatementChanges(stmt, sourceCode) {
56
+ if (stmt.background) {
57
+ return [];
58
+ }
59
+ const { cmd } = stmt;
60
+ if (cmd?.type !== 'CallExpr' || sourceCode.getCommandName(cmd) !== 'set') {
61
+ return [];
62
+ }
63
+ const args = cmd.args.slice(1);
64
+ return parseSetArguments(args.map((word) => sourceCode.resolveWordText(word))).changes;
65
+ }
66
+ /**
67
+ * The options enabled after applying `seed`, then each statement's `set`
68
+ * changes in order.
69
+ * @internal
70
+ */
71
+ export function enabledAfter(seed, statementChanges) {
72
+ const enabled = applySetOptionChanges(new Set(), seed);
73
+ for (const changes of statementChanges) {
74
+ applySetOptionChanges(enabled, changes);
75
+ }
76
+ return enabled;
77
+ }
78
+ /**
79
+ * The options a file's prologue leaves enabled: the state after the first
80
+ * `withinStatements` top-level statements of `file`, plus the shebang's
81
+ * options when `allowShebangOnly` is set. This is the single definition of
82
+ * "what the prologue enables", shared with other rules (such as
83
+ * `no-unchecked-cd`) that need to know whether strict mode is in force.
84
+ *
85
+ * @internal
86
+ */
87
+ export function prologueEnabledOptions(file, sourceCode, config) {
88
+ const shebangChanges = config.allowShebangOnly ? shebangOptionChanges(sourceCode.text) : [];
89
+ const statements = file.stmts.slice(0, config.withinStatements);
90
+ return enabledAfter(shebangChanges, statements.map((stmt) => setStatementChanges(stmt, sourceCode)));
91
+ }
@@ -29,7 +29,7 @@
29
29
  *
30
30
  * @internal
31
31
  */
32
- export interface NestedRepetition {
32
+ interface NestedRepetition {
33
33
  /** The outer repeating quantifier as written, such as `*` or `{2,}`. */
34
34
  readonly outer: string;
35
35
  /** The text of the group the outer quantifier repeats, such as `([A-Z]+_?)`. */
@@ -45,7 +45,7 @@ export interface NestedRepetition {
45
45
  *
46
46
  * @internal
47
47
  */
48
- export declare function findNestedRepetition(source: string): NestedRepetition | undefined;
48
+ declare function findNestedRepetition(source: string): NestedRepetition | undefined;
49
49
  /**
50
50
  * Compiles a regular-expression source from a rule option that will be tested
51
51
  * against script-controlled text. Throws a `TypeError` naming the rule and the
@@ -54,7 +54,7 @@ export declare function findNestedRepetition(source: string): NestedRepetition |
54
54
  * the error from the rule's `create()`, so it surfaces on the first file linted
55
55
  * with the rule ("Occurred while linting <file>"), not when the config loads.
56
56
  *
57
- * @param rule - The rule's full name, such as `sh/prefer-local`.
57
+ * @param rule - The configured rule ID (context.id), including the caller's plugin namespace.
58
58
  * @param option - The option as the user wrote it, such as `patterns[0]`.
59
59
  * @param source - The regular-expression source.
60
60
  * @param flags - Rule-specific flags. Unicode semantics are always added;
@@ -63,3 +63,4 @@ export declare function findNestedRepetition(source: string): NestedRepetition |
63
63
  * @internal
64
64
  */
65
65
  export declare function compileUserPattern(rule: string, option: string, source: string, flags: string): RegExp;
66
+ export { findNestedRepetition };
@@ -24,6 +24,7 @@
24
24
  *
25
25
  * @see https://github.com/mike-north/eslint-sh/issues/221
26
26
  */
27
+ import { configurationMessage } from '../configuration-message.js';
27
28
  /** Matches a `{n}`, `{n,}` or `{n,m}` quantifier at the start of the string. */
28
29
  const BRACE_QUANTIFIER = /^\{\d+(?:,\d*)?\}/u;
29
30
  /**
@@ -103,7 +104,7 @@ function skipClass(source, i) {
103
104
  *
104
105
  * @internal
105
106
  */
106
- export function findNestedRepetition(source) {
107
+ function findNestedRepetition(source) {
107
108
  const stack = [{ start: 0, containsRepetition: false }];
108
109
  let i = 0;
109
110
  while (i < source.length) {
@@ -159,7 +160,7 @@ export function findNestedRepetition(source) {
159
160
  * the error from the rule's `create()`, so it surfaces on the first file linted
160
161
  * with the rule ("Occurred while linting <file>"), not when the config loads.
161
162
  *
162
- * @param rule - The rule's full name, such as `sh/prefer-local`.
163
+ * @param rule - The configured rule ID (context.id), including the caller's plugin namespace.
163
164
  * @param option - The option as the user wrote it, such as `patterns[0]`.
164
165
  * @param source - The regular-expression source.
165
166
  * @param flags - Rule-specific flags. Unicode semantics are always added;
@@ -172,15 +173,16 @@ export function compileUserPattern(rule, option, source, flags) {
172
173
  try {
173
174
  pattern = new RegExp(source, flags.includes('u') ? flags : `${flags}u`);
174
175
  }
175
- catch {
176
- throw new TypeError(`${rule}: \`${option}\` must be a valid regular expression; got ${JSON.stringify(source)}.`);
176
+ catch (cause) {
177
+ // Syntax and policy refusal are separate identities: only syntax has a compiler cause.
178
+ throw Object.assign(new TypeError(configurationMessage(`rules[${JSON.stringify(rule)}].${option}`, 'must be a valid regular expression', source), { cause }), { code: 'ESLINT_SH_PATTERN_SYNTAX' });
177
179
  }
178
180
  const nested = findNestedRepetition(source);
179
181
  if (nested !== undefined) {
180
- throw new TypeError(`${rule}: \`${option}\` (${JSON.stringify(source)}) repeats ${nested.group} with \`${nested.outer}\`, ` +
181
- 'and that group already repeats. The pattern runs against names the linted script chooses, ' +
182
- 'and a nested repetition can take exponential time on a long name. Rewrite it with one level ' +
183
- 'of repetition, for example `[A-Z0-9_]*` instead of `([A-Z]+_?)*`.');
182
+ throw Object.assign(new TypeError(configurationMessage(`rules[${JSON.stringify(rule)}].${option}`, `repeats ${nested.group} with \`${nested.outer}\`, and that group already repeats. ` +
183
+ 'The pattern runs against names the linted script chooses, and a nested repetition can take exponential time on a long name. ' +
184
+ 'Rewrite it with one level of repetition, for example `[A-Z0-9_]*` instead of `([A-Z]+_?)*`', source)), { code: 'ESLINT_SH_PATTERN_REPETITION' });
184
185
  }
185
186
  return pattern;
186
187
  }
188
+ export { findNestedRepetition };
@@ -0,0 +1,8 @@
1
+ /** Project names for the five supported shell grammars. @public */
2
+ export type ShellDialect = 'bash' | 'posix' | 'mksh' | 'bats' | 'zsh';
3
+ /** The single project-label translation to the pinned parser's grammar constants. @internal */
4
+ export declare const SHELL_VARIANTS: Readonly<Record<ShellDialect, number>>;
5
+ /** Stable diagnostic ordering follows the canonical mapping, without another hand-maintained list. @internal */
6
+ export declare const SUPPORTED_SHELL_DIALECTS: readonly string[];
7
+ /** Labels are own keys; object-prototype names never select a grammar. @internal */
8
+ export declare function isShellDialect(value: unknown): value is ShellDialect;
@@ -0,0 +1,22 @@
1
+ // Generated from shared/shell-dialect.ts; edit the canonical source.
2
+ /**
3
+ * Project shell vocabulary shared by linting and non-lint services. A label
4
+ * selects one definite grammar; parser constants are an implementation detail.
5
+ * This module is compiled into each consumer artifact, so shared semantics do
6
+ * not require a runtime dependency between separately released packages.
7
+ */
8
+ import { LangBash, LangBats, LangMirBSDKorn, LangPOSIX, LangZsh } from 'sh-ast';
9
+ /** The single project-label translation to the pinned parser's grammar constants. @internal */
10
+ export const SHELL_VARIANTS = {
11
+ bash: LangBash,
12
+ posix: LangPOSIX,
13
+ mksh: LangMirBSDKorn,
14
+ bats: LangBats,
15
+ zsh: LangZsh,
16
+ };
17
+ /** Stable diagnostic ordering follows the canonical mapping, without another hand-maintained list. @internal */
18
+ export const SUPPORTED_SHELL_DIALECTS = Object.keys(SHELL_VARIANTS);
19
+ /** Labels are own keys; object-prototype names never select a grammar. @internal */
20
+ export function isShellDialect(value) {
21
+ return typeof value === 'string' && Object.hasOwn(SHELL_VARIANTS, value);
22
+ }
@@ -7,9 +7,9 @@
7
7
  * arguments in its site's `argv`), `DEFAULT_TRANSPARENT_WRAPPERS`, `WrapperSpec`, the raw
8
8
  * `resolveWord(Node)`, and the named operator constants with `rawOperator` for comparing and
9
9
  * constructing the operator values those records carry. All of it works on the faithful records
10
- * from `@eslint-sh/eslint-plugin/syntax`. The plugin root's `resolveWord` takes a lint-view
11
- * `ShellNode` instead; the two share a name but not an input contract, so this subpath is kept
12
- * separate from the root.
10
+ * from `@eslint-sh/eslint-plugin/syntax`. For lint-view Word nodes, rules use
11
+ * `context.sourceCode.resolveWord(word)`, whose default policy comes from grammar position.
12
+ * This raw analyzer retains upstream defaults and never infers lint-view context.
13
13
  *
14
14
  * Like `@eslint-sh/eslint-plugin/syntax`, it tracks the plugin's pinned `sh-ast` minor and never
15
15
  * wraps or renames anything.
@@ -9,9 +9,9 @@
9
9
  * arguments in its site's `argv`), `DEFAULT_TRANSPARENT_WRAPPERS`, `WrapperSpec`, the raw
10
10
  * `resolveWord(Node)`, and the named operator constants with `rawOperator` for comparing and
11
11
  * constructing the operator values those records carry. All of it works on the faithful records
12
- * from `@eslint-sh/eslint-plugin/syntax`. The plugin root's `resolveWord` takes a lint-view
13
- * `ShellNode` instead; the two share a name but not an input contract, so this subpath is kept
14
- * separate from the root.
12
+ * from `@eslint-sh/eslint-plugin/syntax`. For lint-view Word nodes, rules use
13
+ * `context.sourceCode.resolveWord(word)`, whose default policy comes from grammar position.
14
+ * This raw analyzer retains upstream defaults and never infers lint-view context.
15
15
  *
16
16
  * Like `@eslint-sh/eslint-plugin/syntax`, it tracks the plugin's pinned `sh-ast` minor and never
17
17
  * wraps or renames anything.
@@ -13,10 +13,9 @@
13
13
  *
14
14
  * This entry point tracks the plugin's pinned `sh-ast` minor, so an `sh-ast` 0.x minor bump is a
15
15
  * minor release of this plugin. It never wraps or renames anything: every name has `sh-ast`'s
16
- * own contract. The plugin root (`@eslint-sh/eslint-plugin`) keeps the view-aware helpers such
17
- * as `resolveWord(ShellNode)`, which differ from the raw helpers of the same name in
18
- * `@eslint-sh/eslint-plugin/syntax/analyze`. That is why these names live on their own subpath
19
- * and are not merged into the root.
16
+ * own contract. Rules analyze lint-view words through `context.sourceCode.resolveWord(word)`,
17
+ * which supplies the word's grammar context. Raw syntax analysis lives in
18
+ * `@eslint-sh/eslint-plugin/syntax/analyze`, separate from the lint view.
20
19
  *
21
20
  * The low-level `printSync` keeps upstream behavior, including changes to literal vertical tabs
22
21
  * and form feeds. It does not apply the high-level content refusal used by `format` and
@@ -15,10 +15,9 @@
15
15
  *
16
16
  * This entry point tracks the plugin's pinned `sh-ast` minor, so an `sh-ast` 0.x minor bump is a
17
17
  * minor release of this plugin. It never wraps or renames anything: every name has `sh-ast`'s
18
- * own contract. The plugin root (`@eslint-sh/eslint-plugin`) keeps the view-aware helpers such
19
- * as `resolveWord(ShellNode)`, which differ from the raw helpers of the same name in
20
- * `@eslint-sh/eslint-plugin/syntax/analyze`. That is why these names live on their own subpath
21
- * and are not merged into the root.
18
+ * own contract. Rules analyze lint-view words through `context.sourceCode.resolveWord(word)`,
19
+ * which supplies the word's grammar context. Raw syntax analysis lives in
20
+ * `@eslint-sh/eslint-plugin/syntax/analyze`, separate from the lint view.
22
21
  *
23
22
  * The low-level `printSync` keeps upstream behavior, including changes to literal vertical tabs
24
23
  * and form feeds. It does not apply the high-level content refusal used by `format` and
package/dist/version.js CHANGED
@@ -1,3 +1,4 @@
1
+ /** Plugin version metadata comes from its own package; ESLINT_SH_PACKAGE_METADATA identifies an invalid package shape. Filesystem/JSON exceptions retain their native identity. */
1
2
  import { readFileSync } from 'node:fs';
2
3
  import { dirname, join } from 'node:path';
3
4
  import { fileURLToPath } from 'node:url';
@@ -24,5 +25,5 @@ export function readPackageVersion() {
24
25
  typeof parsed.version === 'string') {
25
26
  return parsed.version;
26
27
  }
27
- throw new Error(`@eslint-sh/eslint-plugin: package.json at ${packageJsonPath} is missing a string "version" field`);
28
+ throw Object.assign(new Error(`@eslint-sh/eslint-plugin: package.json at ${packageJsonPath} is missing a string "version" field`), { code: 'ESLINT_SH_PACKAGE_METADATA' });
28
29
  }
package/docs/compat.md CHANGED
@@ -67,7 +67,7 @@ instead of UTF-8. `sh/compat/no-nounset-empty-array` gates a behavior, not synta
67
67
  `dialect: "posix"` can lack it: those three are the POSIX-only gates, and the other twenty-two are
68
68
  the version gates. The `bash-3.2` preset enables twenty-one version gates, excluding the opt-in
69
69
  `sh/compat/no-nounset-empty-array`, and the `posix-portable` preset
70
- enables all twenty-five; see
70
+ enables twenty-four, omitting the Bash-only empty-array check that cannot fire there; see
71
71
  [Presets](#presets).
72
72
 
73
73
  ## Setting required shell support
@@ -154,11 +154,10 @@ an explicit opt-in for Bash:
154
154
  fail or read as unset on dash, but not `local`, `echo -e` or the others listed under
155
155
  [What `posix-portable` does not report](#what-posix-portable-does-not-report), so a clean run does
156
156
  not prove a script runs under every POSIX `sh`. It sets `languageOptions: { dialect: 'posix' }` and
157
- enables all twenty-five `compat/*` rules, `sh/shebang-matches-dialect`, and
158
- `sh/require-strict-mode` configured as `set -eu`, all at `error`. Strict mode is `set -eu` and not
159
- `set -euo pipefail` because `pipefail` joined POSIX only in POSIX.1-2024, and older `dash` and
160
- BusyBox `ash` reject it, so a `pipefail` requirement would make the autofix break a working
161
- `#!/bin/sh` script.
157
+ enables twenty-four effective `compat/*` rules and `sh/shebang-matches-dialect`, all at `error`.
158
+ The shebang check verifies that the declared interpreter agrees with the target dialect.
159
+ It excludes the Bash-only empty-array nounset rule and imposes no strict-mode policy.
160
+ Compose `recommended` to require its dialect-aware POSIX `set -eu` default.
162
161
 
163
162
  Both presets are single objects with no `files`; extend them from an entry that lists your
164
163
  scripts, after `recommended` if you want its rules too:
@@ -23,9 +23,12 @@ project's `"type"` field.
23
23
 
24
24
  ## 1. Pick a selector from the cookbook
25
25
 
26
- The cookbook's `:command` [launch class](./selectors.md#the-six-launch-classes) matches every
27
- `CallExpr` node — every shell command invocation. That's the selector this tutorial's rule listens
28
- on; `create()` then narrows further (is the command `rm`? does it pass recursive and force short
26
+ The cookbook's `:command` [launch class](./selectors.md#the-six-launch-classes) matches
27
+ `CallExpr` nodes with a command word, exactly the calls in `sourceCode.getCommandSites()`.
28
+ An assignment-only statement such as `FOO=1` does not match; `FOO=1 jq .`, `true`, `:`, and
29
+ dynamic invocations such as `"$tool" file` do. Select `CallExpr` directly to include
30
+ assignment-only calls. This tutorial's rule listens on `:command`; `create()` then narrows further
31
+ (is the command `rm`? does it pass recursive and force short
29
32
  flags, such as `-rf`, `-fr`, or `-r -f`?) the same way a hand-written rule narrows any other
30
33
  selector-first ESLint rule.
31
34
 
@@ -46,15 +49,15 @@ selector-first ESLint rule.
46
49
  * for it, so ESLint refuses to run the rule on a file of any other language.
47
50
  *
48
51
  * Built on the `:command` launch class from the selector cookbook
49
- * (`../selectors.md`) — `:command` matches every `CallExpr`, so `create()`
52
+ * (`../selectors.md`) — `:command` matches calls with a command word, so `create()`
50
53
  * narrows further by inspecting the command word and its flag arguments,
51
54
  * exactly the pattern the cookbook's intro describes ("writing a rule as a
52
55
  * selector string rather than a `create()` full of manual type checks" —
53
56
  * here the selector does the node-type narrowing, `create()` only does the
54
57
  * domain-specific check).
55
58
  *
56
- * Flag words are resolved with `@eslint-sh/eslint-plugin`'s view-aware
57
- * `resolveWord` (backed by `sh-ast/analyze`) rather than a
59
+ * Flag words are resolved with `context.sourceCode.resolveWord`
60
+ * (backed by `sh-ast/analyze`) rather than a
58
61
  * hand-rolled scan: a word is only treated as a short-option cluster
59
62
  * when it is *statically* that string (bare or
60
63
  * quoted literal concatenations). Recursive (`r`/`R`) and force (`f`)
@@ -64,16 +67,14 @@ selector-first ESLint rule.
64
67
  * A word containing a `ParamExp`/`CmdSubst`/`ArithmExp`/
65
68
  * `ProcSubst` resolves to `{ static: false, reason }` (`'expansion'`,
66
69
  * `'tilde'`, `'glob'`, …) rather than being silently erased into a static
67
- * match — see `resolveWord`'s API docs. Importing
68
- * it from the plugin package (rather than `sh-ast/analyze` directly) means
69
- * a project that installs only `@eslint-sh/eslint-plugin` has everything
70
- * this rule needs, with no separate `sh-ast` install or npm-hoisting
71
- * reliance.
70
+ * match — see `ShellSourceCode.resolveWord`'s API docs. The source instance
71
+ * comes from ESLint, so the rule needs no separate `sh-ast` install or
72
+ * dependency-hoisting reliance.
72
73
  *
73
74
  * @see ../custom-rule-tutorial.md — the tutorial this rule backs
74
75
  * @see ../selectors.md — the `:command` launch class
75
76
  */
76
- import { defineShellRule, resolveWord } from '@eslint-sh/eslint-plugin';
77
+ import { defineShellRule } from '@eslint-sh/eslint-plugin';
77
78
 
78
79
  const noRmRf = defineShellRule({
79
80
  meta: {
@@ -91,7 +92,7 @@ const noRmRf = defineShellRule({
91
92
  ':command'(node) {
92
93
  const args = node.args ?? [];
93
94
  const words = args.map((arg) => {
94
- const resolved = resolveWord(arg, { context: 'command-argument' });
95
+ const resolved = context.sourceCode.resolveWord(arg);
95
96
  return resolved.static ? resolved.text : null;
96
97
  });
97
98
 
@@ -138,14 +139,15 @@ compile error. Everything else in `meta`, including your own `docs.url`, is kept
138
139
 
139
140
  A few things worth calling out:
140
141
 
141
- - `defineShellRule` and `resolveWord` both come from `@eslint-sh/eslint-plugin` (or the umbrella
142
- `eslint-sh`). A rule needs no other package: not `sh-ast`, and not `@eslint/core`.
142
+ - `defineShellRule` comes from `@eslint-sh/eslint-plugin` (or the umbrella `eslint-sh`).
143
+ ESLint supplies `context.sourceCode`, including its word-resolution method. A rule needs no
144
+ separate `sh-ast` or `@eslint/core` dependency.
143
145
  - The listener key, `':command'`, is a selector string — one of the [six launch
144
146
  classes](./selectors.md#the-six-launch-classes) — not a bare node-type name. ESLint's
145
147
  `esquery`-based rule-listener matching (via `ShellLanguage.matchesSelectorClass`) treats it
146
148
  exactly like any other selector key such as `CallExpr` or `CallExpr[args.0.parts.0.value='jq']`.
147
- - `resolveWord(arg, { context: 'command-argument' })` — exported from `@eslint-sh/eslint-plugin`
148
- (using the raw Word associated with the lint view) — is the correct way to ask "is this word statically the string X":
149
+ - `context.sourceCode.resolveWord(arg)` uses the raw Word associated with the lint view and
150
+ defaults to command-argument context for `CallExpr.args`. It is the way to ask "is this word statically the string X":
149
151
  it returns `{ static: true, text }` for a bare or
150
152
  quoted literal (`rm`, `'r'm`, `"-rf"` all resolve), and `{ static: false, reason }` the moment any
151
153
  part of the word depends on a `ParamExp`/`CmdSubst`/`ArithmExp`/`ProcSubst` — never inventing a
@@ -436,7 +438,7 @@ into an ESLint fix:
436
438
  - `getEditableSyntax(node)` returns an independent copy of the sh-ast record `node` was parsed
437
439
  from. It is an ordinary `structuredClone` of that record, which sh-ast documents as the supported
438
440
  way to get an editable copy. Edit the copy freely: the original record that `getSyntax` returns,
439
- the lint view, and helpers such as `resolveWord` keep seeing the original source. It throws a
441
+ the lint view, and helpers such as `context.sourceCode.resolveWord` keep seeing the original source. It throws a
440
442
  `TypeError` for a node that has no record of its own, such as one you built yourself.
441
443
  - `getPrintedReplacement(node, edited, options)` prints `edited` with sh-ast's `printSync` and
442
444
  returns `{ range, text }`, ready for `fixer.replaceTextRange(range, text)`. The range is
@@ -930,3 +932,5 @@ TypeError: ESLint configuration in rule-tester is invalid: Key "language": Could
930
932
 
931
933
  Both appear when the test file runs, before any case is checked. A rule built with `defineShellRule`
932
934
  declares `meta.languages: ['sh/sh']`, so ESLint refuses to run it under any other language.
935
+
936
+ See [error codes](error-codes.md) for stable failure identities, source-helper argument boundaries, and dependency pass-through behavior.
@@ -395,20 +395,20 @@ cache and the snapshot that invalidates it, are tested in this package's test su
395
395
  ## Reading the convention in your own rule
396
396
 
397
397
  `sh/no-undeclared-commands` and `sh/no-unused-declarations` are the built-in rules that read the
398
- bound convention. A rule of your own reads it through the same two functions from
399
- `@eslint-sh/eslint-plugin`, so it gets the same behavior without re-implementing it:
400
-
401
- - **`resolveDeclarationConvention(context)`**, from `create()`, returns the convention from the
402
- rule's own `declarationConvention` option, else from `settings.sh.declarationConvention`, else
403
- `null`. With `null`, return no listeners: there is nothing to check. A bound value that isn't a
404
- convention throws the configuration error the built-in rules throw, naming the setting:
405
- `Invalid settings.sh.declarationConvention: expected a declaration convention`, and so on.
406
- - **`readDeclaredCommands(convention, context)`**, from a listener, returns the declarations for
407
- the file `context` is linting. It hands the convention the `LintedFile`, so a sidecar
408
- convention works in your rule too, and it checks every declaration exactly as the built-in
409
- rules do. A missing or unknown `kind`, a missing field, or a `range` outside the text throws
410
- `Invalid settings.sh.declarationConvention: …`. Don't call `convention.declaredCommands` directly: you would get unchecked
411
- values.
398
+ bound convention. A rule of your own calls **`getDeclaredCommands(context)`** from a listener.
399
+ It resolves `settings.sh.declarationConvention` and returns validated declarations, or `null`
400
+ when no convention is bound. A bound convention that declares nothing returns `[]`.
401
+
402
+ The convention receives a frozen `LintedFile` with only `filename`, `physicalFilename` and
403
+ `cwd`, so sidecar conventions work in custom rules too. Invalid bindings or declarations
404
+ (missing or unknown `kind`, missing fields, invalid provenance or a `range` outside the text)
405
+ throw `Invalid settings.sh.declarationConvention: …`. Calling `declaredCommands` directly
406
+ would bypass those checks.
407
+
408
+ A rule that also needs a hook such as `removeDeclaration` can call
409
+ `resolveDeclarationConvention({ settings: context.settings })` to get the validated convention
410
+ object. Shared settings are the only binding route; rule options do not bind conventions.
411
+
412
412
  - Only in-script declarations have a `range`. Check `kind` before reading it: a declaration with
413
413
  `kind` `'file'` or `'described'` lives somewhere your rule can't point at.
414
414
 
@@ -426,8 +426,7 @@ this package's test suite runs it in CI with both `commentPragma` and the
426
426
  */
427
427
  import {
428
428
  defineShellRule,
429
- readDeclaredCommands,
430
- resolveDeclarationConvention,
429
+ getDeclaredCommands,
431
430
  } from '@eslint-sh/eslint-plugin';
432
431
 
433
432
  const sortedDeclarations = defineShellRule({
@@ -437,18 +436,16 @@ const sortedDeclarations = defineShellRule({
437
436
  messages: { unsorted: 'Declare `{{name}}` before `{{previous}}`.' },
438
437
  },
439
438
  create(context) {
440
- // The bound convention, checked exactly as the built-in rules check it;
441
- // `null` when none is bound, and then the rule has nothing to check.
442
- const convention = resolveDeclarationConvention(context);
443
- if (convention === null) {
444
- return {};
445
- }
446
439
  return {
447
440
  File() {
448
441
  const { sourceCode } = context;
449
442
  // The file's declarations, checked as the built-in rules check them.
450
443
  // Only those written in the script have a range to report at.
451
- const declared = readDeclaredCommands(convention, context).filter(
444
+ const declarations = getDeclaredCommands(context);
445
+ if (declarations === null) {
446
+ return;
447
+ }
448
+ const declared = declarations.filter(
452
449
  (each) => each.kind === 'script',
453
450
  );
454
451
  for (let i = 1; i < declared.length; i++) {
@@ -0,0 +1,93 @@
1
+ # Error codes
2
+
3
+ Every deliberate project error has a stable `ESLINT_SH_` code. Match `code` to
4
+ identify a failure; human message text may change. Plain argument/configuration
5
+ errors retain their native `TypeError`, `RangeError` or `Error` prototype. Named
6
+ classes exist where callers need structured data, as listed below.
7
+
8
+ Configuration messages have the shape `<where>: <what is wrong>; received <value>.`
9
+ The path names the binding the caller wrote, including a list index when one
10
+ entry is wrong. Rule-option paths use the configured rule ID, including plugin
11
+ registration aliases; shared settings retain the canonical `settings.sh` namespace.
12
+ Nonfinite numbers are shown as `NaN`, `Infinity` or `-Infinity`, rather than `null`.
13
+ Other values use a short JSON-first rendering, with a fallback for
14
+ undefined, bigint, symbols, functions and values that cannot be serialized.
15
+ Messages are diagnostics, not a serialization format.
16
+
17
+ ```js
18
+ try {
19
+ // Configure the shell language or call a source helper.
20
+ } catch (error) {
21
+ if (error instanceof Error && 'code' in error) {
22
+ console.error(error.code, error.message);
23
+ } else {
24
+ throw error;
25
+ }
26
+ }
27
+ ```
28
+
29
+ ## Project codes
30
+
31
+ | Code | Base/class | Meaning and boundary |
32
+ | --- | --- | --- |
33
+ | `ESLINT_SH_LANGUAGE_OPTION` | `TypeError` | A `languageOptions` value or combination cannot be honored. |
34
+ | `ESLINT_SH_STRICT_MODE_SETTING` | `Error` | The shared `settings.sh.strictModePrologue` fact or one of its fields is malformed. |
35
+ | `ESLINT_SH_WRAPPER_CONFIG` | `TypeError` | A `createWrapperRule config` binding is malformed. |
36
+ | `ESLINT_SH_WRAPPER_SETTING` | `Error` | A shared wrapper binding or spec field is malformed. |
37
+ | `ESLINT_SH_WRAPPER_CONFLICT` | `Error` | Wrapper policies contradict each other or repeat a project name. |
38
+ | `ESLINT_SH_DECLARATION_CONVENTION` | `Error` | The declaration convention or an optional hook has the wrong shape. |
39
+ | `ESLINT_SH_DECLARATION_OUTPUT` | `Error` | A convention returns invalid declarations or a malformed hint. A hook's own exception propagates unchanged. |
40
+ | `ESLINT_SH_PATTERN_SYNTAX` | `TypeError` | A rule option is not a valid Unicode regular expression. `cause` preserves the JavaScript compiler's error. |
41
+ | `ESLINT_SH_PATTERN_REPETITION` | `TypeError` | A valid pattern nests repeating quantifiers and is refused by the documented pattern policy. |
42
+ | `ESLINT_SH_FILE_NODE` | `TypeError` | A helper requires a file associated with this adapter's parse. |
43
+ | `ESLINT_SH_CALL_NODE` | `TypeError` | A command helper requires a parsed `CallExpr` view. |
44
+ | `ESLINT_SH_WORD_NODE` | `TypeError` | A word helper requires a parsed `Word` view. A dynamic word is a normal resolution result. |
45
+ | `ESLINT_SH_COMMAND_SITE_VIEW` | `Error` | An analyzed command site has no corresponding view in the supplied file. |
46
+ | `ESLINT_SH_FOREIGN_VIEW_NODE` | `TypeError` | A printed-fix helper received a view with no original syntax in this file. |
47
+ | `ESLINT_SH_SYNTAX_POSITION` | `TypeError` | A position argument does not have the required `SyntaxPos` shape. |
48
+ | `ESLINT_SH_SOURCE_INDEX` | `TypeError` | A source index is not numeric. |
49
+ | `ESLINT_SH_SOURCE_LOCATION` | `TypeError` | A source location lacks numeric line/column fields. |
50
+ | `ESLINT_SH_SOURCE_RANGE` | `RangeError` | A position is inexact, outside the source, or inside a UTF-8 character. |
51
+ | `ESLINT_SH_SYNTAX_VIEW` | `TypeError` | Upstream records and their position snapshot cannot produce a faithful lint view. This is a projection invariant failure, not a syntax diagnostic. |
52
+ | `ESLINT_SH_PRINT_ROOT` | `TypeError` | Edited syntax is missing a record type or uses an unsupported printable root. |
53
+ | `ESLINT_SH_PRINT_ENCODING` | `TypeError` | Printed bytes cannot become a UTF-8 text fix without loss. |
54
+ | `ESLINT_SH_PRINT_UNSAFE_TEXT` | `TypeError` | Edited syntax contains literal vertical tabs or form feeds the printer changes. |
55
+ | `ESLINT_SH_PACKAGE_METADATA` | `Error` | The plugin package lacks a string version. Filesystem/JSON errors keep their native identity. |
56
+
57
+ Formatting/editor failures are documented by the independently maintained
58
+ [sh-codemod](https://github.com/mike-north/sh-codemod#readme) project and use its
59
+ `SH_CODEMOD_` namespace. They are not plugin errors.
60
+
61
+ ## Dependency boundaries
62
+
63
+ `./syntax` and `./syntax/analyze` faithfully re-export `sh-ast` and
64
+ `sh-ast/analyze`. They retain upstream errors and codes without aliases. The
65
+ plugin's source helpers also preserve analysis resource/invalid-wrapper failures,
66
+ and printed replacements preserve upstream printer errors. Returning a partial
67
+ command inventory on a depth refusal would silently omit real commands.
68
+
69
+ | Dependency code | Meaning |
70
+ | --- | --- |
71
+ | `SH_AST_SYNTAX_PARSE` | Invalid shell source. The language presents fatal diagnostics; raw syntax calls retain the error. |
72
+ | `SH_AST_SYNTAX_LANG` | Source is invalid in the selected dialect. Same boundary as parse errors. |
73
+ | `SH_AST_SYNTAX_INPUT` | The raw parser/printer rejects an input value. High-level project option validation happens before parsing; non-option input errors pass through. |
74
+ | `SH_AST_SYNTAX_PRINT` | Printer request cannot be honored. |
75
+ | `SH_AST_SYNTAX_PRINT_PANIC` | Upstream printer failure. |
76
+ | `SH_AST_WALK_PANIC` | Upstream syntax traversal failure. |
77
+ | `SH_AST_PARSE_MAX_DEPTH` | Parser resource limit; no partial tree is returned. |
78
+ | `SH_AST_ANALYZE_MAX_DEPTH` | Analysis resource limit; no partial inventory is returned. |
79
+ | `SH_AST_ANALYZE_INVALID_WRAPPER_SPEC` | A raw analysis wrapper spec is invalid. Shared JSON settings are validated at their own project boundary. |
80
+ | `SH_AST_INTERNAL` | Upstream bridge/internal failure. |
81
+
82
+ ESLint wraps errors from language-option validation in its own `TypeError`.
83
+ Direct calls to `plugin.languages.sh.validateLanguageOptions` expose the project
84
+ code on the thrown error; an ESLint configuration failure preserves that error
85
+ and its code on `cause`. Shared-setting and rule-factory errors propagate through
86
+ ESLint rule loading with their project codes intact.
87
+
88
+ The language's `parse` entry point returns ESLint fatal diagnostics rather than
89
+ throwing. Syntax diagnostics retain their source positions, resource refusals
90
+ remain resource diagnostics, and runtime failures remain distinguished from
91
+ invalid shell. ESLint's own schema errors, third-party hook exceptions and native
92
+ runtime failures are not project-owned intentional errors and keep their
93
+ existing contracts. Check each method's `@throws` for its precise boundary.
@@ -10,15 +10,15 @@
10
10
  * for it, so ESLint refuses to run the rule on a file of any other language.
11
11
  *
12
12
  * Built on the `:command` launch class from the selector cookbook
13
- * (`../selectors.md`) — `:command` matches every `CallExpr`, so `create()`
13
+ * (`../selectors.md`) — `:command` matches calls with a command word, so `create()`
14
14
  * narrows further by inspecting the command word and its flag arguments,
15
15
  * exactly the pattern the cookbook's intro describes ("writing a rule as a
16
16
  * selector string rather than a `create()` full of manual type checks" —
17
17
  * here the selector does the node-type narrowing, `create()` only does the
18
18
  * domain-specific check).
19
19
  *
20
- * Flag words are resolved with `@eslint-sh/eslint-plugin`'s view-aware
21
- * `resolveWord` (backed by `sh-ast/analyze`) rather than a
20
+ * Flag words are resolved with `context.sourceCode.resolveWord`
21
+ * (backed by `sh-ast/analyze`) rather than a
22
22
  * hand-rolled scan: a word is only treated as a short-option cluster
23
23
  * when it is *statically* that string (bare or
24
24
  * quoted literal concatenations). Recursive (`r`/`R`) and force (`f`)
@@ -28,16 +28,14 @@
28
28
  * A word containing a `ParamExp`/`CmdSubst`/`ArithmExp`/
29
29
  * `ProcSubst` resolves to `{ static: false, reason }` (`'expansion'`,
30
30
  * `'tilde'`, `'glob'`, …) rather than being silently erased into a static
31
- * match — see `resolveWord`'s API docs. Importing
32
- * it from the plugin package (rather than `sh-ast/analyze` directly) means
33
- * a project that installs only `@eslint-sh/eslint-plugin` has everything
34
- * this rule needs, with no separate `sh-ast` install or npm-hoisting
35
- * reliance.
31
+ * match — see `ShellSourceCode.resolveWord`'s API docs. The source instance
32
+ * comes from ESLint, so the rule needs no separate `sh-ast` install or
33
+ * dependency-hoisting reliance.
36
34
  *
37
35
  * @see ../custom-rule-tutorial.md — the tutorial this rule backs
38
36
  * @see ../selectors.md — the `:command` launch class
39
37
  */
40
- import { defineShellRule, resolveWord } from '@eslint-sh/eslint-plugin';
38
+ import { defineShellRule } from '@eslint-sh/eslint-plugin';
41
39
 
42
40
  const noRmRf = defineShellRule({
43
41
  meta: {
@@ -55,7 +53,7 @@ const noRmRf = defineShellRule({
55
53
  ':command'(node) {
56
54
  const args = node.args ?? [];
57
55
  const words = args.map((arg) => {
58
- const resolved = resolveWord(arg, { context: 'command-argument' });
56
+ const resolved = context.sourceCode.resolveWord(arg);
59
57
  return resolved.static ? resolved.text : null;
60
58
  });
61
59