@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
@@ -1,1560 +1,16 @@
1
- import { Argv0Resolution } from 'sh-ast/analyze';
2
- import { CommandContext } from 'sh-ast/analyze';
3
- import type { ConfigObject } from '@eslint/core';
4
- import type { Directive } from '@eslint/core';
5
- import type { Expansion } from 'sh-ast';
6
- import type { File as File_2 } from '@eslint/core';
7
- import type { FileProblem } from '@eslint/core';
8
- import type { Language } from '@eslint/core';
9
- import type { Node } from 'sh-ast';
10
- import type { OkParseResult } from '@eslint/core';
11
- import type { ParseResult } from '@eslint/core';
12
- import type { PrintOptions } from 'sh-ast';
13
- import type { Replace } from 'sh-ast';
14
- import { ResolveArgv0Options } from 'sh-ast/analyze';
15
- import type { ResolveWordOptions } from 'sh-ast/analyze';
16
- import type { RuleContext } from '@eslint/core';
17
- import { RuleDefinition } from '@eslint/core';
18
- import { RuleDefinitionTypeOptions } from '@eslint/core';
19
- import type { RulesConfig } from '@eslint/core';
20
- import type { RulesMeta } from '@eslint/core';
21
- import type { RuleTextEdit } from '@eslint/core';
22
- import type { RuleTextEditor } from '@eslint/core';
23
- import type { SettingsConfig } from '@eslint/core';
24
- import type { Slice } from 'sh-ast';
25
- import type { SourceLocation } from '@eslint/core';
26
- import type { SyntaxPos } from 'sh-ast';
27
- import { TextSourceCodeBase } from '@eslint/plugin-kit';
28
- import type { TraversalStep } from '@eslint/core';
29
- import { WordResolution } from 'sh-ast/analyze';
30
- import { WrapperSpec } from 'sh-ast/analyze';
31
-
32
- export { Argv0Resolution }
33
-
34
- export { CommandContext }
35
-
36
- /**
37
- * The reference {@link DeclarationConvention}: a script declares the external
38
- * commands it uses in `# uses:` comments in its header.
39
- *
40
- * ```sh
41
- * #!/usr/bin/env bash
42
- * # uses: jq curl
43
- * # uses: git
44
- * set -euo pipefail
45
- * ```
46
- *
47
- * declares `jq`, `curl`, and `git`. The header is the run of blank and
48
- * comment-only lines at the top of the file; a `# uses:` comment after the
49
- * first command is not a declaration. Several pragma lines accumulate, names
50
- * are whitespace-separated, and each declaration is `kind: 'script'` with a
51
- * `range` that covers exactly that name. A word starting with `#` ends the list and begins a trailing
52
- * remark: `# uses: jq # for json` declares only `jq`.
53
- *
54
- * Its `removeDeclaration` hook deletes one name and the whitespace that
55
- * separated it, or the whole pragma line (with its `\n` or `\r\n`) when that
56
- * name was the line's last.
57
- *
58
- * Its `declarationHint` hook tells a person exactly what to add: the line
59
- * `# uses: curl`, on a line below the shebang, or as the first line of the
60
- * file when there is no shebang. A name a pragma cannot express (one with
61
- * whitespace, or starting with `#`) gets no hint.
62
- *
63
- * Bind it with `settings: { sh: { declarationConvention: commentPragma } }`.
64
- *
65
- * @public
66
- */
67
- export declare const commentPragma: Readonly<Required<DeclarationConvention>>;
68
-
69
- /**
70
- * Creates a rule that reports every listed command that is not run through
71
- * `config.wrapper`, for a rule pack's "must be wrapped by X" policies:
72
- *
73
- * ```js
74
- * import { createWrapperRule } from '@eslint-sh/eslint-plugin';
75
- *
76
- * export const requireAudit = createWrapperRule({
77
- * commands: ['kubectl', 'terraform'],
78
- * wrapper: 'audit-run',
79
- * });
80
- * ```
81
- *
82
- * The rule declares `meta.languages: ["sh/sh"]`, takes no options (the
83
- * config is bound here), and reports with message id `unwrappedCommand`,
84
- * naming the command and the wrapper. Its `meta.docs.url` and
85
- * `meta.docs.description` default to this package's wrapper-rules page and a
86
- * sentence naming the policy; `config.docs` overrides either. A listed
87
- * command is wrapped when the wrapper encloses it in `sh-ast/analyze`'s
88
- * transparent-wrapper chain, so `audit-run sudo kubectl apply` is wrapped.
89
- * Command and wrapper words written as paths match by basename
90
- * (`/usr/bin/kubectl`). Commands inside `$(…)`, functions, and pipelines are
91
- * checked; a command whose name or subcommand is not static is not reported.
92
- *
93
- * @param config - The commands, the wrapper they must be run through, any
94
- * subcommand restrictions, and optional `meta.docs` overrides.
95
- * @returns A {@link ShellRule}: an ESLint rule for the `sh/sh` language,
96
- * typed so a pack's own declarations need no `@eslint/core` import to name it.
97
- * @throws TypeError when `config` is malformed (no `commands` array, an empty
98
- * wrapper name, a subcommand restriction without `names`, or an empty or
99
- * non-string `docs.url` / `docs.description`).
100
- *
101
- * @public
102
- */
103
- export declare function createWrapperRule(config: WrapperRuleConfig): ShellRule<[], 'unwrappedCommand'>;
104
-
105
- /**
106
- * How a project declares the external commands its shell scripts depend on.
107
- *
108
- * Implement this to teach the plugin a project's own declaration syntax, then
109
- * bind it with `settings: { sh: { declarationConvention: myConvention } }`.
110
- * Until a convention is bound, rules that consume one report nothing.
111
- *
112
- * Bind it through `settings`, not through a rule's options: ESLint copies
113
- * rule options with `structuredClone`, which cannot copy functions. Define it
114
- * as a plain object whose methods are its own properties, and bind it in one
115
- * config entry: when two matching config entries both set it, ESLint merges
116
- * the two objects property by property, which drops methods inherited from a
117
- * class prototype and can mix methods from two different conventions.
118
- *
119
- * One convention object serves every file its config entry matches, so its
120
- * answer must depend only on its arguments and on data it holds, never on
121
- * which file it saw before. ESLint's `--cache` sees a convention's own
122
- * enumerable data properties (they are part of the config it hashes) but not
123
- * files the convention reads while linting.
124
- *
125
- * {@link commentPragma} is the reference implementation.
126
- *
127
- * @public
128
- */
129
- export declare interface DeclarationConvention {
130
- /**
131
- * Returns every command the linted file declares, in source order. A name
132
- * declared twice appears twice, each with its own source. `file` names the
133
- * file being linted, for a convention whose declarations live beside it;
134
- * a convention that reads only `sourceCode` can leave it out.
135
- */
136
- declaredCommands(sourceCode: ShellSourceCode, file: LintedFile): DeclaredCommand[];
137
- /**
138
- * Optional edit hook: returns the fix that deletes the single stale
139
- * declaration `declared` (an in-script entry previously returned by
140
- * {@link DeclarationConvention.declaredCommands} for the same
141
- * `sourceCode`), built with the rule's `fixer`. Returns `null` when that
142
- * declaration cannot be removed safely.
143
- *
144
- * It is only ever called with a {@link ScriptDeclaredCommand}: a fix edits
145
- * only the linted script, and no edit to the script removes a declaration
146
- * kept anywhere else.
147
- *
148
- * A convention without this hook still reports stale declarations; those
149
- * reports simply carry no autofix.
150
- */
151
- removeDeclaration?(sourceCode: ShellSourceCode, declared: ScriptDeclaredCommand, fixer: RuleTextEditor): RuleTextEdit | RuleTextEdit[] | null;
152
- /**
153
- * Optional hint hook: returns one short sentence that tells a person how to
154
- * declare `command`, with text they can copy. {@link commentPragma}'s hint says to
155
- * add `# uses: curl` on a line below the shebang.
156
- * `sh/no-undeclared-commands` appends it to its report. Following the
157
- * sentence literally must make that report go away.
158
- *
159
- * Return `null` when this convention cannot declare `command` as written
160
- * (for example, a name its syntax cannot express). The report then falls
161
- * back to a generic sentence, as it does for a convention without this
162
- * hook. Anything other than `null` must be a non-empty single-line string.
163
- */
164
- declarationHint?(command: string, sourceCode: ShellSourceCode, file: LintedFile): string | null;
165
- }
166
-
167
- /**
168
- * The slice of an ESLint rule context that binding resolution reads: the rule
169
- * id (for error messages), its configured options, and the shared settings.
170
- * Any rule `context` satisfies it, so a rule passes its own `context`.
171
- *
172
- * @public
173
- */
174
- export declare interface DeclarationConventionBindingContext {
175
- /** The rule id as configured (`pack/my-rule`), named in an option-binding error. */
176
- readonly id: string;
177
- /** The rule's configured options; the first may carry `declarationConvention`. */
178
- readonly options: readonly unknown[];
179
- /** The shared settings; `settings.sh.declarationConvention` is the usual binding. */
180
- readonly settings: SettingsConfig;
181
- }
182
-
183
- /**
184
- * What {@link readDeclaredCommands} reads from a rule's context: the linted
185
- * file and its source code. Any shell rule's `context` satisfies it.
186
- *
187
- * @public
188
- */
189
- export declare interface DeclarationReadContext extends LintedFile {
190
- /** The source code of the file being linted. */
191
- readonly sourceCode: ShellSourceCode;
192
- }
193
-
194
- /**
195
- * One command a script declares it depends on, as reported by a
196
- * {@link DeclarationConvention}. Where the declaration lives is part of what
197
- * it is, so it is one of three kinds, told apart by the required `kind`:
198
- * written in the script ({@link ScriptDeclaredCommand}), in another file
199
- * ({@link FileDeclaredCommand}), or in a source that can only be described in
200
- * words ({@link DescribedDeclaredCommand}). Only the script kind has a `range`, so
201
- * narrow on `kind` before reading it.
202
- *
203
- * @public
204
- */
205
- export declare type DeclaredCommand = ScriptDeclaredCommand | FileDeclaredCommand | DescribedDeclaredCommand;
206
-
207
- /**
208
- * Builds a shell rule from its spec, setting `meta.languages` to
209
- * exactly `["sh/sh"]` so ESLint refuses to run the rule on any other language.
210
- * Everything else in `meta`, and `create`, is kept as written; message ids
211
- * and option types are inferred from `meta` or may be given explicitly
212
- * (`defineShellRule<[], 'found'>(…)`).
213
- *
214
- * The language fields are written last, so a JavaScript caller that bypasses
215
- * the types and supplies its own `languages` or `language` still gets
216
- * exactly `["sh/sh"]` (and no `language`). A JavaScript caller that omits
217
- * `meta`, which ESLint allows for a rule, is treated as having written
218
- * `meta: {}`.
219
- *
220
- * @example
221
- * ```ts
222
- * import { defineShellRule } from '@eslint-sh/eslint-plugin';
223
- *
224
- * export const noEval = defineShellRule({
225
- * meta: { type: 'problem', schema: [], messages: { evalUsed: 'Avoid eval.' } },
226
- * create(context) {
227
- * return {
228
- * CallExpr(node) {
229
- * if (context.sourceCode.getCommandName(node) === 'eval') {
230
- * context.report({ node, messageId: 'evalUsed' });
231
- * }
232
- * },
233
- * };
234
- * },
235
- * });
236
- * ```
237
- *
238
- * @public
239
- */
240
- export declare function defineShellRule<RuleOptions extends unknown[] = [], MessageIds extends string = string>(spec: ShellRuleSpec<RuleOptions, MessageIds>): ShellRule<RuleOptions, MessageIds>;
241
-
242
- /**
243
- * A declaration whose source can only be described in words: there is no
244
- * range in the script and no path to point at, only a phrase that tells a
245
- * person where it comes from, such as a list written in the ESLint config, a
246
- * convention's own constant, or a snapshot of a tool registry. A report about
247
- * it names the source by `description` and carries no fix.
248
- *
249
- * @public
250
- */
251
- export declare interface DescribedDeclaredCommand {
252
- /** Says the declaration's source is described in words, by `description`. */
253
- readonly kind: 'described';
254
- /** The declared command name, exactly as it would be invoked. */
255
- readonly name: string;
256
- /**
257
- * Names the source for a person who wants to change the declaration, as a
258
- * phrase that reads after "declared in": "the web image list in
259
- * eslint.config.js", "the tool registry snapshot of 2026-11-01". It must be a
260
- * non-empty single line.
261
- */
262
- readonly description: string;
263
- }
264
-
265
- /**
266
- * A declaration written in a file other than the linted script: a per-script
267
- * sidecar, or a manifest several scripts share. A report about it names the
268
- * file, and carries no fix, since a fix can only edit the linted script.
269
- *
270
- * @public
271
- */
272
- export declare interface FileDeclaredCommand {
273
- /** Says the declaration is in another file. */
274
- readonly kind: 'file';
275
- /** The declared command name, exactly as it would be invoked. */
276
- readonly name: string;
277
- /**
278
- * Where a person or a tool should look for the declaration: a path
279
- * relative to {@link LintedFile.cwd}, or an absolute path. It must be a
280
- * non-empty single line. Rules name it in their reports as given; they never
281
- * read it.
282
- */
283
- readonly path: string;
284
- /** The 1-based line of `path` that declares the command, when the convention knows it. */
285
- readonly line?: number;
286
- }
287
-
288
- /**
289
- * The file ESLint is linting, as its rule context names it. A
290
- * {@link DeclarationConvention} receives it so it can find declarations kept
291
- * outside the script, such as a per-script sidecar file next to it.
292
- *
293
- * A rule's own `context` is a `LintedFile`, so a rule that calls
294
- * `declaredCommands` passes `context`.
295
- *
296
- * @public
297
- */
298
- export declare interface LintedFile {
299
- /**
300
- * The name ESLint lints the code under (`context.filename`). For a code
301
- * block a processor extracts from another file it is virtual
302
- * (`README.md/0_0.sh`).
303
- */
304
- readonly filename: string;
305
- /**
306
- * The path on disk ESLint associates with the code
307
- * (`context.physicalFilename`): the file it read, or the file a
308
- * processor's code block came from. With `--stdin --stdin-filename`, it is
309
- * the name given on the command line; the code came from standard input,
310
- * and that file may not exist. Resolve sidecar paths from this one, and
311
- * treat a missing sidecar as a normal case.
312
- */
313
- readonly physicalFilename: string;
314
- /**
315
- * ESLint's working directory (`context.cwd`). A relative
316
- * {@link FileDeclaredCommand.path} is relative to it.
317
- */
318
- readonly cwd: string;
319
- }
320
-
321
- /**
322
- * The result of {@link ShellLanguage.normalizeLanguageOptions}: `dialect` and
323
- * `directivePrefix` are always resolved to concrete values (defaulted when
324
- * the caller didn't specify them), and `toJSON()` provides the "custom
325
- * serialization" ESLint's languages guide recommends
326
- * (https://eslint.org/docs/latest/extend/languages, "normalizeLanguageOptions")
327
- * so that config caching keyed off `JSON.stringify(languageOptions)` is
328
- * stable irrespective of the input object's own key order — `JSON.stringify`
329
- * calls `toJSON()` automatically when present.
330
- *
331
- * @public
332
- */
333
- export declare interface NormalizedShellLanguageOptions extends Record<string, unknown> {
334
- readonly dialect: ShellDialect;
335
- readonly directivePrefix: string;
336
- readonly minBashVersion?: string;
337
- toJSON(): ShellLanguageOptionsJSON;
338
- }
339
-
340
- /**
341
- * The `@eslint-sh/eslint-plugin` plugin object, this package's default
342
- * export (`import sh from '@eslint-sh/eslint-plugin'`). `languages.sh` provides
343
- * `ShellLanguage` / `ShellSourceCode`, selected in a flat config via
344
- * `language: "sh/sh"` (`namespace: "sh"`). `meta.version` is read from this
345
- * package's own `package.json` at runtime — never hardcoded (see
346
- * `version.ts`).
347
- *
348
- * `rules` holds the plugin's built-in rules, each built with
349
- * `defineShellRule` (so each declares `meta.languages: ["sh/sh"]`) and
350
- * linking its docs page from `meta.docs.url`. Consumers can also supply their
351
- * own rules, built with the same `defineShellRule`, while sharing parsing,
352
- * selectors, source coordinates, and directive semantics.
353
- *
354
- * `configs.recommended` is the `sh/recommended` preset: a single config
355
- * object carrying `plugins: { sh }` and `language: "sh/sh"` but no `files`,
356
- * so it inherits the globs of the entry that extends it:
357
- * `{ files: [...], extends: [sh.configs.recommended] }`. It enables the
358
- * convention-free policy rules. The rules index at
359
- * https://github.com/mike-north/eslint-sh/blob/main/packages/eslint-plugin/docs/rules/README.md
360
- * describes preset membership and available autofixes.
361
- * `configs['agent-authored']` is the strict `sh/agent-authored` preset for
362
- * machine-written, human-reviewed scripts:
363
- * every `recommended` rule plus the contract rules, all at `error`.
364
- * `configs['bash-3.2']` and `configs['posix-portable']` are deployment-target
365
- * packs: the first sets `languageOptions.minBashVersion: "3.2"` and enables
366
- * the version-gated `compat/*` rules except the opt-in
367
- * `compat/no-nounset-empty-array`; the second sets
368
- * `languageOptions.dialect: "posix"`, enables the `compat/*` rules and the
369
- * shebang/dialect check, and requires `set -eu`; it reports named constructs
370
- * that fail on dash, not every non-POSIX construct, and leaves `local`,
371
- * `echo -e` and the rest of shellcheck's SC3xxx catalog to shellcheck. Every
372
- * shipped config is a
373
- * single object with no `files`; the two packs also carry `languageOptions`,
374
- * because the target they name is their meaning.
375
- *
376
- * Re-exported, unchanged, as the default export of the `eslint-sh` umbrella
377
- * package: importing this package or the umbrella package both yield the
378
- * same plugin object.
379
- *
380
- * @public
381
- */
382
- declare const plugin: {
383
- meta: {
384
- name: string;
385
- version: string;
386
- namespace: string;
387
- };
388
- languages: {
389
- sh: ShellLanguage;
390
- };
391
- rules: Record<string, RuleDefinition<RuleDefinitionTypeOptions>>;
392
- configs: {
393
- recommended: ConfigObject;
394
- "agent-authored": ConfigObject;
395
- "bash-3.2": ConfigObject;
396
- "posix-portable": ConfigObject;
397
- };
398
- };
399
- export default plugin;
400
-
401
- /**
402
- * Returns the declarations `convention` makes for the file `context` is
403
- * linting, after checking each one against its kind. Call it from a rule's
404
- * listener with the convention `resolveDeclarationConvention` returned and
405
- * the rule's own `context`.
406
- *
407
- * The convention receives a frozen {@link LintedFile} holding only
408
- * `filename`, `physicalFilename` and `cwd`, never the whole context, so it
409
- * sees which file it is reading and nothing it could report through.
410
- *
411
- * Throws an `Error` naming the declaration-convention setting and showing the
412
- * offending value when
413
- * `declaredCommands` does not return an array, or returns a declaration with
414
- * a missing or unknown `kind`, without its kind's fields, or with a `range`
415
- * outside the linted text.
416
- *
417
- * @example
418
- * ```ts
419
- * const convention = resolveDeclarationConvention(context);
420
- * if (convention === null) return {};
421
- * return {
422
- * File() {
423
- * for (const declared of readDeclaredCommands(convention, context)) {
424
- * if (declared.kind === 'script') {
425
- * // declared.range is an offset pair into context.sourceCode.text
426
- * }
427
- * }
428
- * },
429
- * };
430
- * ```
431
- *
432
- * @public
433
- */
434
- export declare function readDeclaredCommands(convention: DeclarationConvention, context: DeclarationReadContext): DeclaredCommand[];
435
-
436
- export { ResolveArgv0Options }
437
-
438
- /**
439
- * Resolves the declaration convention bound for the rule running in
440
- * `context`: the rule's `declarationConvention` option, else
441
- * `settings: { sh: { declarationConvention: convention } }`, else `null`
442
- * (the rule is inert).
443
- *
444
- * Throws an `Error` naming the offending setting when the configured value is
445
- * present but does not implement `declaredCommands` (or has a non-function
446
- * `removeDeclaration`). The message names where the value came from and what
447
- * it was, including the expected convention shape and the received value.
448
- * Call it from `create()`, so the error surfaces as ESLint's configuration
449
- * message for the file being linted.
450
- *
451
- * A rule that receives `null` should register no listeners: with no
452
- * convention bound, a convention consumer has nothing to check.
453
- *
454
- * @example
455
- * ```ts
456
- * import {
457
- * defineShellRule,
458
- * readDeclaredCommands,
459
- * resolveDeclarationConvention,
460
- * } from '@eslint-sh/eslint-plugin';
461
- *
462
- * export const maxDeclaredCommands = defineShellRule({
463
- * meta: { schema: [], messages: { tooMany: 'Declare at most 5 commands.' } },
464
- * create(context) {
465
- * const convention = resolveDeclarationConvention(context);
466
- * if (convention === null) return {};
467
- * return {
468
- * File(node) {
469
- * // Validated declarations for the file `context` is linting.
470
- * if (readDeclaredCommands(convention, context).length > 5) {
471
- * context.report({ node, messageId: 'tooMany' });
472
- * }
473
- * },
474
- * };
475
- * },
476
- * });
477
- * ```
478
- *
479
- * @public
480
- */
481
- export declare function resolveDeclarationConvention(context: DeclarationConventionBindingContext): DeclarationConvention | null;
482
-
483
- /**
484
- * Returns the shared project wrappers followed by `builtIns` (defaults when
485
- * omitted). Entries accept command names or JSON-expressible `WrapperSpec`s
486
- * in `settings: { sh: { transparentWrappers: [...] } }`. The shared network
487
- * wrapper is also transparent; conflicting specs for the same project name
488
- * throw rather than allowing policies to disagree. Shared specs compare effective
489
- * grammars for overlapping names, normalizing matcher defaults and retaining
490
- * expanded built-in flag patterns; an extra transparent alias does not acquire
491
- * network approval. Explicit specs remain complete replacements. Duplicate project
492
- * names are rejected so list order cannot silently choose their meaning.
493
- *
494
- * Utility wrappers match absolute and relative paths by basename. Path words
495
- * remain unchanged in analysis results. `shellBuiltin: true` entries match
496
- * exact names only: an executable path cannot acquire in-process semantics.
497
- * An explicit path spec takes precedence over a basename fallback regardless
498
- * of configuration order.
499
- * Aliases are built even when only `builtIns` are supplied. Overridden names
500
- * are removed from lower-priority entries, preserving their unrelated aliases
501
- * and preventing a utility entry from undoing an exact-name builtin override.
502
- * The input tables are never mutated.
503
- *
504
- * @param context - The consuming rule's context.
505
- * @param builtIns - The rule's own built-in wrapper scope.
506
- * @throws Error when a configured wrapper is malformed or contradictory.
507
- * @public
508
- */
509
- export declare function resolveTransparentWrappers(context: TransparentWrappersBindingContext, builtIns?: readonly WrapperSpec[]): readonly WrapperSpec[];
510
-
511
- /**
512
- * Resolves a parsed lint Word using the upstream-shaped syntax associated with it.
513
- * The view supplies locations and selector fields; sh-ast/analyze owns the word
514
- * interpretation. Fabricated or synthetic view nodes have no source syntax and
515
- * are rejected instead of being treated as known or unknown shell values.
516
- * A static word that ends a line of a CRLF file resolves without the line
517
- * terminator's carriage return, as it would on LF input.
518
- * @public
519
- */
520
- export declare function resolveWord(word: ShellNodeOf<'Word'>, options?: ResolveWordOptions): WordResolution;
521
-
522
- /**
523
- * A declaration written in the linted script's own text: the only kind an
524
- * ESLint fix can edit, because a fix edits only the file being linted.
525
- *
526
- * @public
527
- */
528
- export declare interface ScriptDeclaredCommand {
529
- /** Says the declaration is in the script. */
530
- readonly kind: 'script';
531
- /** The declared command name, exactly as it would be invoked (`jq`, `docker-compose`). */
532
- readonly name: string;
533
- /**
534
- * The `[start, end)` source range of this declaration, as UTF-16 offsets
535
- * into `sourceCode.text` (the same coordinates as every node's `range`),
536
- * with `0 <= start <= end <= sourceCode.text.length`. Rules report a
537
- * declaration at this range, so it should cover the text that declares
538
- * this one name and nothing else.
539
- */
540
- readonly range: readonly [number, number];
541
- }
542
-
543
- /**
544
- * One command invocation in a linted shell file, in lint-view terms: an
545
- * `sh-ast/analyze` `CommandSite` whose `node` is the `CallExpr` view node
546
- * ESLint passes to rule visitors, so a rule can `context.report()` on it.
547
- *
548
- * The data comes from `sh-ast/analyze`'s `enumerateCommands` and is facts
549
- * only: how the command is reached and what its words resolve to, never a
550
- * verdict on whether running it is safe. A dynamic (`static: false`) `argv0`
551
- * is a normal result.
552
- *
553
- * Read one through `ShellSourceCode.getCommandSites()`.
554
- *
555
- * Every rule linting a file sees the same sites, so each one is deeply
556
- * frozen: the entry, its `context` array and every frame in it, its `argv`
557
- * array, and every `WordResolution` in `argv` (`argv0` included). Writing to
558
- * any of them throws in strict-mode code and is ignored otherwise, so one rule
559
- * cannot change what another rule reads. The `node` is the shared lint view
560
- * node, which, like every node ESLint passes to rules, is not frozen and must
561
- * not be modified.
562
- *
563
- * @public
564
- */
565
- export declare interface ShellCommandSite {
566
- /**
567
- * The `CallExpr` view node for this command: the same object (`===`)
568
- * ESLint passes to a `CallExpr` visitor, with `range` and `loc` in this
569
- * file's UTF-16 coordinates.
570
- */
571
- readonly node: ShellNodeOf<'CallExpr'>;
572
- /**
573
- * The path from the file root to this command, outermost frame first,
574
- * exactly as `sh-ast/analyze` reports it. For example, `date` in
575
- * `f() { echo "$(date)"; }` has
576
- * `[{ kind: 'function', name: 'f' }, { kind: 'cmdSubst' }]`.
577
- */
578
- readonly context: readonly CommandContext[];
579
- /** The command word (`argv[0]`) resolved with `{ context: 'command-argument' }`. */
580
- readonly argv0: WordResolution;
581
- /**
582
- * Every word of the command, `argv0` included, in argument order, each
583
- * resolved with `{ context: 'command-argument' }`. Leading `VAR=val`
584
- * assignments are not part of argv.
585
- */
586
- readonly argv: readonly WordResolution[];
587
- /**
588
- * Follows this command's argv0 through transparent wrappers (`env`, `sudo`,
589
- * `nohup`, `exec`, …) and returns `sh-ast/analyze`'s `resolveArgv0`
590
- * result. Same answer as
591
- * `ShellSourceCode.resolveInvokedCommand(node, options)`; both read the
592
- * same per-file index.
593
- *
594
- * @param options - Forwarded to `resolveArgv0` unchanged.
595
- * `transparentWrappers` replaces `sh-ast/analyze`'s
596
- * `DEFAULT_TRANSPARENT_WRAPPERS`; spread the defaults into the array to
597
- * extend them instead.
598
- * @returns A new result on every call. Its `chain` and `chainIndices`
599
- * arrays belong to the caller. `chainIndices` gives each chain entry's
600
- * position in this site's `argv`.
601
- * @throws `ShAnalyzeInvalidWrapperSpecError` (from `sh-ast/analyze`) when
602
- * `options.transparentWrappers` contains a malformed entry.
603
- */
604
- resolveInvokedCommand(options?: ResolveArgv0Options): Argv0Resolution;
605
- }
606
-
607
- /** Directive processing uses the comment text without its leading shell hash. @public */
608
- export declare type ShellComment = ShellNodeOf<'Comment'>;
609
-
610
- /** Owns ESLint configuration labels and validates their consumer-facing meaning before parsing. */
611
- /** The dialect labels understood by ESLint configuration, mapped to upstream numeric variants when parsing. @public */
612
- export declare type ShellDialect = 'bash' | 'posix' | 'mksh' | 'bats' | 'zsh';
613
-
614
- /** The lint root has a statement collection even when upstream represents it as nil. @public */
615
- export declare type ShellFile = ShellNodeOf<'File'>;
616
-
617
- /**
618
- * `ShellLanguage` — the `@eslint/core` `Language` implementation for shell
619
- * scripts. Registered by the plugin as `languages.sh`, so consumers select
620
- * it via `language: "sh/sh"`.
621
- *
622
- * Implements `matchesSelectorClass` (the six launch esquery selector
623
- * classes — see `./selector-classes.js`), so rules and end users can write
624
- * class-based selectors (`:command`, `:loop`, `:conditional`, `:expansion`,
625
- * `:quoted`, `:function`) against shell trees. The `SourceCode` directive
626
- * members (`getDisableDirectives`, `getInlineConfigNodes`,
627
- * `applyInlineConfig`) are implemented on `ShellSourceCode` itself; see
628
- * shell-source-code.ts.
629
- *
630
- * @public
631
- */
632
- export declare class ShellLanguage implements Language {
633
- readonly fileType: "text";
634
- readonly lineStart: 1;
635
- readonly columnStart: 1;
636
- readonly nodeTypeKey: string;
637
- readonly visitorKeys: Record<string, string[]>;
638
- readonly defaultLanguageOptions: ShellLanguageOptions;
639
- /**
640
- * Validates `languageOptions.dialect` (must be one of the five supported
641
- * dialects, if present), `languageOptions.minBashVersion` (must be a
642
- * string matching the `MAJOR[.MINOR]` numeric shape, if present, and
643
- * applies only to `bash` and `bats`), and
644
- * `languageOptions.directivePrefix` (must be a valid directive-comment
645
- * label, if present). The removed `shellVersion` key throws with
646
- * migration guidance; other unknown keys are silently ignored. See `shell-language-options.ts`'s
647
- * `validateShellLanguageOptions` for the full rationale.
648
- */
649
- validateLanguageOptions(languageOptions: ShellLanguageOptions): void;
650
- /**
651
- * Resolves `dialect` to its default (`"bash"`) when unset and attaches a
652
- * `toJSON()` method with a fixed key order, so that ESLint's config
653
- * caching (keyed off serializing `languageOptions`) is stable regardless
654
- * of the key order a user's config happened to use. See
655
- * `shell-language-options.ts`'s `normalizeShellLanguageOptions`.
656
- */
657
- normalizeLanguageOptions(languageOptions: ShellLanguageOptions): NormalizedShellLanguageOptions;
658
- /**
659
- * `@eslint/core`'s esquery hook: lets a selector's leading `:` "class"
660
- * (e.g. `:command` in `CallExpr[args.0.parts.0.value='jq']` isn't even
661
- * needed there, but `:loop :command` is) match a whole family of node
662
- * types instead of one literal type name. Delegates to
663
- * `./selector-classes.js`'s `SELECTOR_CLASS_NODE_TYPES` table for the six
664
- * launch classes; `ancestry` is unused today because none of the six launch
665
- * classes need ancestor context, but the parameter is accepted to match
666
- * `Language.matchesSelectorClass`'s signature exactly.
667
- */
668
- matchesSelectorClass(className: string, node: ShellNode, _ancestry: ShellNode[]): boolean;
669
- /**
670
- * Parses `file.body` (guaranteed to be a `string`, since `fileType` is
671
- * `"text"`) with one synchronous parse and its original-position snapshot,
672
- * mapping the result to
673
- * the `{ok: true, ast}` / `{ok: false, errors}` shape `Language.parse` is
674
- * required to return. Never throws — parse failures are reported as
675
- * fatal lint messages, per the `Language` contract.
676
- *
677
- * A file whose extension marks it as a known non-shell source type (for
678
- * example `.js` or `.json`) is never shell-parsed: it fails with a single
679
- * diagnostic explaining that a `language: 'sh/sh'` config entry without
680
- * `files` reached it, and how to scope that entry. Unicode characters remain
681
- * source text. A native nesting-budget refusal returns no partial tree and
682
- * becomes a fatal resource diagnostic at 1:1.
683
- */
684
- parse(file: File_2, context: {
685
- languageOptions: ShellLanguageOptions;
686
- }): ParseResult<ShellFile>;
687
- /**
688
- * Creates the `ShellSourceCode` ESLint uses to run rules against `ast`.
689
- * `context.languageOptions` is ESLint's already-normalized copy (see
690
- * `packages/eslint-plugin/test/language-options.test.ts` and
691
- * `eslint`'s `Config#finalize`, which replaces `languageOptions` with
692
- * `normalizeLanguageOptions`'s return value before either `parse` or
693
- * `createSourceCode` is called) — `directivePrefix` is therefore always
694
- * present, but `?? 'eslint'` stays as an explicit, honest fallback for
695
- * direct construction (e.g. tests that skip the `Language` normalization
696
- * step), mirroring `parse()`'s `dialect` default above. `dialect` and
697
- * `minBashVersion` are forwarded so rules read the same normalized values
698
- * through `sourceCode.dialect` / `sourceCode.minBashVersion`.
699
- */
700
- createSourceCode(file: File_2, parseResult: OkParseResult<ShellFile>, context: {
701
- languageOptions: ShellLanguageOptions;
702
- }): ShellSourceCode;
703
- }
704
-
705
- /**
706
- * `languageOptions` accepted by {@link ShellLanguage}: `dialect` selects
707
- * mvdan/sh's `LangVariant` through a consumer-owned mapping (default `"bash"`); `minBashVersion`
708
- * is consumed by the rule layer (e.g. the bash-3.2 compatibility pack),
709
- * never by the parser itself.
710
- *
711
- * Extends `Record<string, unknown>` (rather than a bare interface) so this
712
- * type satisfies the `@eslint/core` package's `LanguageOptions` bound
713
- * (itself `Record<string, unknown>`) wherever it is used as a
714
- * `Language`/`SourceCode` type parameter — ESLint's own contract for
715
- * language options is that they are arbitrary user-supplied records, not a
716
- * closed shape.
717
- *
718
- * @public
719
- */
720
- export declare interface ShellLanguageOptions extends Record<string, unknown> {
721
- readonly dialect?: ShellDialect;
722
- /**
723
- * The minimum Bash version (`MAJOR[.MINOR]`, such as `"3.2"`) the
724
- * script must support, including every newer Bash. Only valid with the
725
- * `bash` or `bats` dialect (the default is `bash`). The parser ignores
726
- * it; `compat/*` rules report features unavailable at this floor. Unset
727
- * means no Bash version constraint. Versions compare numerically by
728
- * major then minor, with no upper version limit.
729
- */
730
- readonly minBashVersion?: string;
731
- /**
732
- * The prefix directive/inline-config comments must start with — e.g. the
733
- * default `"eslint"` recognizes `# eslint-disable-next-line ...` and
734
- * `# eslint <rule-config>`. Consumers who embed shell-linting inside a
735
- * larger toolchain that already overloads `#eslint-*` comments for
736
- * something else can configure a different prefix.
737
- * @defaultValue `"eslint"`
738
- */
739
- readonly directivePrefix?: string;
740
- }
741
-
742
- /**
743
- * The plain-data shape {@link NormalizedShellLanguageOptions.toJSON} returns:
744
- * `dialect` and `directivePrefix` always present (both defaulted), `minBashVersion`
745
- * present only when the caller supplied one. Keys are always emitted in this
746
- * fixed order so that two logically-identical inputs serialize identically
747
- * regardless of the key order the caller happened to use — the property this
748
- * type exists to guarantee for cache-key stability (see
749
- * {@link NormalizedShellLanguageOptions}). `directivePrefix` is included
750
- * unconditionally (like `dialect`, unlike `minBashVersion`) because — like
751
- * `dialect` and unlike `minBashVersion` — it always has a concrete effect on
752
- * linting results (which comments the `SourceCode` recognizes as directives)
753
- * whether or not the caller supplied one, so two configs that differ only in
754
- * an *implicit* default vs. an *explicit* `directivePrefix: "eslint"` must
755
- * still cache-key identically.
756
- *
757
- * @public
758
- */
759
- export declare interface ShellLanguageOptionsJSON {
760
- readonly dialect: ShellDialect;
761
- readonly directivePrefix: string;
762
- readonly minBashVersion?: string;
763
- }
764
-
765
- /**
766
- * A listener for a node of type `Node`. It is declared with method syntax on
767
- * purpose: method parameters are checked bivariantly, which lets a listener
768
- * for one node type sit alongside the union-typed listener every other
769
- * selector key gets (see {@link ShellRuleVisitor}) without a type error.
770
- *
771
- * Exported so a helper that builds listeners for several rules can name the
772
- * type it returns; `node` is the matched node and `parent` its parent
773
- * (`undefined` for the root `File`).
774
- *
775
- * @public
776
- */
777
- export declare type ShellListener<Node extends ShellNode = ShellNode> = {
778
- listener(node: Node, parent: ShellNode | undefined): void;
779
- }['listener'];
780
-
781
- /**
782
- * A node in the consumer's lint view: the union of every node type, so
783
- * narrowing on `type` gives that node's fields with no cast. Scalar/child fields
784
- * use lowercase upstream spellings; syntax fidelity belongs to the associated
785
- * upstream tree. Auxiliary view nodes may have spans derived from children and
786
- * are not upstream Nodes.
787
- * @public
788
- */
789
- export declare type ShellNode = ShellNodeMap[ShellNodeType];
790
-
791
- /**
792
- * The lint-view type of one upstream field value `Value`: a record becomes the
793
- * node type of that record (a union of records, a union of node types), a slice
794
- * becomes a read-only array of such nodes with its nil elements removed, a Go
795
- * string becomes a JavaScript `string`, and booleans and operator values stay
796
- * as they are. Upstream nil (`null`) and typed nils never reach a view, so
797
- * neither appears in the result.
798
- *
799
- * It is the type of every field of every {@link ShellNodeMap} entry, exported
800
- * so a helper that takes or returns a node's field value can name it.
801
- *
802
- * @public
803
- */
804
- export declare type ShellNodeField<Value> = Exclude<Value, null | {
805
- readonly Type: 'TypedNil';
806
- }> extends infer Present ? Present extends readonly (infer Element)[] ? readonly ShellNodeField<Element>[] : Present extends {
807
- readonly Type: infer Type extends ShellNodeType;
808
- } ? ShellNodeMap[Type] : Present extends string | Uint8Array ? string : Present : never;
809
-
810
- /**
811
- * Lint-view node types by their `type` discriminator, one entry per upstream
812
- * syntax record. It is computed from `sh-ast`'s generated interfaces, so it
813
- * follows the pinned mvdan/sh version.
814
- *
815
- * A node has `type`, `range` and `loc`, plus a lowercase field for each
816
- * non-position upstream field. A field that is a single child that may be nil
817
- * upstream is optional, because the view omits the key when the child is
818
- * absent; a slice is always present.
819
- *
820
- * `range` is a half-open UTF-16 span of the source text and `loc` its ESLint
821
- * line/column form; both describe the view, not the upstream byte positions. A
822
- * node whose line ends in CRLF ends before the `\r` (and a text field such as
823
- * `value` loses that one trailing `\r`), so a CRLF file reads like its LF
824
- * twin. Auxiliary records (`Expansion`, `Replace`, `Slice`) take their span
825
- * from their children.
826
- *
827
- * @public
828
- */
829
- export declare type ShellNodeMap = {
830
- [Record in Exclude<Node, {
831
- readonly Type: 'TypedNil';
832
- }> | Expansion | Replace | Slice as Record['Type']]: {
833
- /** Syntax kind of this node; the discriminator to narrow a ShellNode by. */
834
- readonly type: Record['Type'];
835
- /**
836
- * Half-open UTF-16 span of the node in the source text. Its type is the
837
- * mutable tuple ESLint's `fixer` methods take, so `node.range` can be passed
838
- * to `fixer.insertTextBeforeRange` and the others without a cast; treat it
839
- * as read-only.
840
- */
841
- range: [number, number];
842
- /** ESLint line and column of the span's two ends. */
843
- readonly loc: {
844
- readonly start: ShellPosition;
845
- readonly end: ShellPosition;
846
- };
847
- } & {
848
- readonly [Name in keyof Record & string as Name extends 'Type' ? never : [Record[Name]] extends [SyntaxPos] ? never : null extends Record[Name] ? Exclude<Record[Name], null | {
849
- readonly Type: 'TypedNil';
850
- }> extends {
851
- readonly Type: string;
852
- } ? never : Lowercase<Name> : Lowercase<Name>]: ShellNodeField<Record[Name]>;
853
- } & {
854
- readonly [Name in keyof Record & string as null extends Record[Name] ? Exclude<Record[Name], null | {
855
- readonly Type: 'TypedNil';
856
- }> extends {
857
- readonly Type: string;
858
- } ? Lowercase<Name> : never : never]?: ShellNodeField<Record[Name]>;
859
- };
860
- };
861
-
862
- /** The lint-view node whose `type` is `Type`, for example `ShellNodeOf<'Stmt'>`. @public */
863
- export declare type ShellNodeOf<Type extends ShellNodeType> = ShellNodeMap[Type];
864
-
865
- /** Every value a lint-view node's `type` can hold. @public */
866
- export declare type ShellNodeType = keyof ShellNodeMap;
867
-
868
- /** An ESLint location counts UTF-16 units, with both line and column starting at one. @public */
869
- export declare interface ShellPosition {
870
- /** One-based source line, with CRLF treated as one line break. */
871
- readonly line: number;
872
- /** One-based UTF-16 column; tabs and grapheme widths are not expanded. */
873
- readonly column: number;
874
- }
875
-
876
- /**
877
- * A finished shell rule, as {@link defineShellRule} returns it: an ordinary
878
- * ESLint rule definition (it goes in a plugin's `rules` like any other)
879
- * specialized to the shell language, whose `meta.languages` is always exactly
880
- * `["sh/sh"]`. The `meta.languages` requirement is part of the type, so a
881
- * hand-written object that omits it, or names another language, is not a
882
- * `ShellRule`.
883
- *
884
- * @public
885
- */
886
- export declare type ShellRule<RuleOptions extends unknown[] = [], MessageIds extends string = string> = Omit<RuleDefinition<{
887
- LangOptions: NormalizedShellLanguageOptions;
888
- Code: ShellSourceCode;
889
- RuleOptions: RuleOptions;
890
- Visitor: ShellRuleVisitor;
891
- Node: ShellNode;
892
- MessageIds: MessageIds;
893
- ExtRuleDocs: unknown;
894
- }>, 'meta'> & {
895
- readonly meta: Omit<RulesMeta<MessageIds, RuleOptions>, 'languages'> & {
896
- languages: ['sh/sh'];
897
- };
898
- };
899
-
900
- /**
901
- * The `context` a shell rule's `create()` receives: ESLint's rule context
902
- * specialized to the shell language, so `context.sourceCode` is
903
- * {@link ShellSourceCode}, `context.languageOptions` is
904
- * {@link NormalizedShellLanguageOptions}, `context.options` is `RuleOptions`,
905
- * and `context.report` takes {@link ShellNode}s and only the `MessageIds` the
906
- * rule declares. Name it when a helper outside `create()` needs the context.
907
- *
908
- * `context.languageOptions` is the object `ShellLanguage.normalizeLanguageOptions`
909
- * returned, not the user's config input, so `dialect` is always set (`"bash"`
910
- * by default) and needs no fallback. `context.sourceCode.dialect` carries that
911
- * same normalized value; read whichever is closer to hand.
912
- *
913
- * @public
914
- */
915
- export declare type ShellRuleContext<RuleOptions extends unknown[] = [], MessageIds extends string = string> = RuleContext<{
916
- LangOptions: NormalizedShellLanguageOptions;
917
- Code: ShellSourceCode;
918
- RuleOptions: RuleOptions;
919
- Node: ShellNode;
920
- MessageIds: MessageIds;
921
- }>;
922
-
923
- /**
924
- * The `meta` a rule author writes: every field ESLint's rule `meta` accepts
925
- * (`type`, `docs`, `schema`, `messages`, `fixable`, `defaultOptions`, …)
926
- * except the language fields, which {@link defineShellRule} owns. `languages`
927
- * and its deprecated singular predecessor `language` are typed `never`, so
928
- * writing either — in particular a language other than `sh/sh` — is a
929
- * compile error rather than a value the helper silently replaces.
930
- *
931
- * @public
932
- */
933
- export declare type ShellRuleMeta<RuleOptions extends unknown[] = [], MessageIds extends string = string> = Omit<RulesMeta<MessageIds, RuleOptions>, 'languages' | 'language'> & {
934
- readonly languages?: never;
935
- readonly language?: never;
936
- };
937
-
938
- /**
939
- * What a rule author hands to {@link defineShellRule}: the rule's `meta` and
940
- * its `create()`, exactly as in any ESLint rule, minus `meta.languages`. It is
941
- * the rule before the helper finishes it; {@link ShellRule} is the finished
942
- * rule (ESLint's `RuleDefinition`), so the input is named a spec, not a
943
- * definition.
944
- *
945
- * @public
946
- */
947
- export declare interface ShellRuleSpec<RuleOptions extends unknown[] = [], MessageIds extends string = string> {
948
- /** The rule's metadata; see {@link ShellRuleMeta}. */
949
- readonly meta: ShellRuleMeta<RuleOptions, MessageIds>;
950
- /** Builds the rule's listeners for one file from the shell-typed context. */
951
- readonly create: (context: ShellRuleContext<RuleOptions, MessageIds>) => ShellRuleVisitor;
952
- }
953
-
954
- /**
955
- * The listener map a shell rule's `create()` returns. Keys are node types or
956
- * esquery selectors written against the lint view's spelling (for example
957
- * `CallExpr[args.0.parts.0.value='jq']` or the `:command` selector class),
958
- * optionally suffixed with `:exit`. ESLint calls each listener with the
959
- * matched node and its parent (the parent is `undefined` for the root
960
- * `File`).
961
- *
962
- * A key that is exactly a node type, with or without `:exit` (`CallExpr`,
963
- * `Word:exit`), types its listener's node as that node type, so
964
- * `CallExpr(node) { node.args }` reads `args` with no `type` check. Any other
965
- * selector string (`*`, `CallExpr[…]`, `:command`, `Stmt > CallExpr`) matches
966
- * nodes of more than one type, or of one type the key does not state, so its
967
- * listener receives the whole {@link ShellNode} union: narrow it on `type`.
968
- *
969
- * @public
970
- */
971
- export declare interface ShellRuleVisitor extends ShellTypedListeners {
972
- [selector: string]: ShellListener | undefined;
973
- }
974
-
975
- /**
976
- * `ShellSourceCode` — the `SourceCode` object ESLint uses to work with a
977
- * parsed shell file. Extends `@eslint/plugin-kit`'s `TextSourceCodeBase`, which
978
- * already implements `getLoc`/`getRange`/`getText`/`lines` (both by reading
979
- * the normalized node's own `loc`/`range` fields — see
980
- * the consumer's source-view contract), `getLocFromIndex`, and
981
- * `getIndexFromLoc`; this class adds the two members the base class
982
- * deliberately leaves unimplemented: `traverse()` (base throws "Not
983
- * implemented") and `getParent()` (base throws "Not implemented", and
984
- * `getAncestors()` — already implemented generically in terms of
985
- * `getParent()` — falls out for free).
986
- *
987
- * Directive support (`getDisableDirectives`, `getInlineConfigNodes`,
988
- * `applyInlineConfig`) recognizes all four disable-comment forms
989
- * (`<prefix>-disable`, `<prefix>-enable`, `<prefix>-disable-line`,
990
- * `<prefix>-disable-next-line`) plus whole-file inline rule config
991
- * (bare `<prefix> <rule-config>`), sourced from the tree's `Comment` nodes
992
- * and parsed with
993
- * `@eslint/plugin-kit`'s `ConfigCommentParser` — the same building blocks
994
- * `@eslint/json`'s `JSONSourceCode` uses, generalized so the `<prefix>` is
995
- * configurable (default `"eslint"`; see `ShellLanguageOptions.directivePrefix`)
996
- * rather than hardcoded to `"eslint"`.
997
- *
998
- * Selector-class support (`matchesSelectorClass`, the six launch esquery
999
- * classes) is implemented on `ShellLanguage` — see `shell-language.ts` and
1000
- * `selector-classes.ts`.
1001
- *
1002
- * Rule-author helpers (`resolveWordText`, `getCommandName`,
1003
- * `resolveInvokedCommand`, `getCommandSites`) answer "is this word statically
1004
- * the string `jq`?", "which command does this invocation run?", and "which
1005
- * commands does this file run, and where?" by delegating to
1006
- * `sh-ast/analyze`. They never reinterpret words themselves, so every rule
1007
- * gets the same answer for the same syntax. `dialect` and `minBashVersion`
1008
- * expose the file's normalized language options.
1009
- *
1010
- * Syntax access (`getSyntax`, `getViewNode`, `getIndexFromSyntaxPos`,
1011
- * `getLocFromSyntaxPos`) reaches behind the lint view to the sh-ast records
1012
- * this file was parsed into: from a view node to its record and back, and
1013
- * from a record's byte positions (such as `BinaryCmd.OpPos`, which the view
1014
- * leaves out) to ESLint coordinates in this file's text.
1015
- *
1016
- * Printed fixes (`getEditableSyntax`, `getPrintedReplacement`) edit an
1017
- * independent copy of a view node's record and print it with sh-ast's
1018
- * printer, returning the source range and text for `fixer.replaceTextRange`.
1019
- *
1020
- * @public
1021
- */
1022
- export declare class ShellSourceCode extends TextSourceCodeBase<{
1023
- LangOptions: ShellLanguageOptions;
1024
- RootNode: ShellFile;
1025
- SyntaxElementWithLoc: ShellNode;
1026
- ConfigNode: ShellComment;
1027
- }> {
1028
- #private;
1029
- constructor(options: {
1030
- text: string;
1031
- ast: ShellFile;
1032
- directivePrefix?: string;
1033
- dialect?: ShellDialect;
1034
- minBashVersion?: string;
1035
- });
1036
- /**
1037
- * The shell dialect this file was parsed as: the normalized
1038
- * `languageOptions.dialect`, which defaults to `"bash"` when the config
1039
- * leaves it unset. Rules use it to gate dialect-specific checks.
1040
- */
1041
- get dialect(): ShellDialect;
1042
- /**
1043
- * The configured `languageOptions.minBashVersion` (a `MAJOR[.MINOR]` string
1044
- * such as `"3.2"`), or `undefined` when the config does not set one. The
1045
- * script must support this Bash and every newer release. The parser never
1046
- * reads it; compatibility rules use it as a floor with no upper limit.
1047
- */
1048
- get minBashVersion(): string | undefined;
1049
- /**
1050
- * The one-based location of a UTF-16 `index` in this file's text, where
1051
- * `index` may be anywhere from 0 to `text.length`. CRLF counts as one line
1052
- * break.
1053
- *
1054
- * Overrides the base class, which measures every index from the root
1055
- * node's own start and so assumes the root spans the whole text. A shell
1056
- * file's root starts at its first statement or comment, so the base answer
1057
- * was shifted by any leading blank lines or indentation.
1058
- *
1059
- * @throws TypeError when `index` is not a number.
1060
- * @throws RangeError when `index` is not an integer from 0 to `text.length`.
1061
- */
1062
- getLocFromIndex(index: number): {
1063
- line: number;
1064
- column: number;
1065
- };
1066
- /**
1067
- * The UTF-16 index of a one-based `loc` in this file's text: the inverse of
1068
- * {@link ShellSourceCode.getLocFromIndex}. The column may name any position
1069
- * on its line up to and including the line break.
1070
- *
1071
- * Overrides the base class for the same reason as `getLocFromIndex`.
1072
- *
1073
- * @throws TypeError when `loc` is not an object with numeric `line` and `column`.
1074
- * @throws RangeError when `loc` is not inside the text.
1075
- */
1076
- getIndexFromLoc(loc: {
1077
- line: number;
1078
- column: number;
1079
- }): number;
1080
- /**
1081
- * Returns the literal text of `word` when `sh-ast/analyze`'s `resolveWord`
1082
- * reports it static, or `null` otherwise.
1083
- *
1084
- * Delegates to `resolveWord` (through this package's `resolveWord` export),
1085
- * which alone defines what "static" means: a word is static iff
1086
- * `resolveWord` reports `static: true`. Its non-static reasons are
1087
- * `expansion`, `tilde`, `glob`, `brace`, `locale`, and `unsupported`.
1088
- * Call the root `resolveWord` export instead when the reason matters.
1089
- *
1090
- * `options` is forwarded to `resolveWord` unchanged. When it is omitted, the
1091
- * word's grammar position picks the tilde context: a word in a `CallExpr`'s
1092
- * `args` uses `{ context: 'command-argument' }`, the context
1093
- * `enumerateCommands` uses for argv, so `resolveWordText(callExpr.args[0])`
1094
- * equals `getCommandName(callExpr)`. Any other word uses `resolveWord`'s
1095
- * conservative default, which also treats a `~` after an unquoted `:` as a
1096
- * tilde expansion, as assignment values do.
1097
- *
1098
- * @param word - A parsed `Word` node from this file's lint tree.
1099
- * @param options - Forwarded to `resolveWord` unchanged when supplied.
1100
- * @returns The resolved text, or `null` when the word is not static.
1101
- * @throws TypeError when `word` is not a parsed shell `Word`.
1102
- */
1103
- resolveWordText(word: ShellNodeOf<'Word'>, options?: ResolveWordOptions): string | null;
1104
- /**
1105
- * Returns the static text of `callExpr`'s command word (`argv[0]`) as
1106
- * written, or `null` when that word is dynamic or absent. Transparent
1107
- * wrappers are **not** followed: `sudo rm x` yields `"sudo"`. Use
1108
- * {@link ShellSourceCode.resolveInvokedCommand} for the command a wrapper
1109
- * chain actually runs.
1110
- *
1111
- * Delegates to `sh-ast/analyze`: the answer is the `argv0` resolution of the
1112
- * `CommandSite` that `enumerateCommands` reports for this `CallExpr` in this
1113
- * file. Leading `VAR=val` assignments are not part of argv, so
1114
- * `FOO=1 jq .` yields `"jq"`. An assignment-only statement (`FOO=1`) has no
1115
- * argv0 and no `CommandSite`, and yields `null`.
1116
- *
1117
- * @param callExpr - A parsed `CallExpr` node from this file's lint tree.
1118
- * @returns The command word's static text, or `null`.
1119
- * @throws TypeError when `callExpr` is not a parsed shell `CallExpr`.
1120
- * @throws `ShAnalyzeMaxDepthError` (from `sh-ast/analyze`) when this file's
1121
- * nesting exceeds analysis's recursion guard; see
1122
- * {@link ShellSourceCode.resolveInvokedCommand}.
1123
- */
1124
- getCommandName(callExpr: ShellNodeOf<'CallExpr'>): string | null;
1125
- /**
1126
- * Follows `callExpr`'s argv0 through transparent wrappers (`env`, `sudo`,
1127
- * `nohup`, `exec`, …) and returns `sh-ast/analyze`'s full `resolveArgv0`
1128
- * result, or `null` for a `CallExpr` that has no `CommandSite` (an
1129
- * assignment-only statement such as `FOO=1`).
1130
- *
1131
- * Delegates to `resolveArgv0` with the `CommandSite` that `enumerateCommands`
1132
- * reports for this `CallExpr` in this file, so it inherits that function's
1133
- * guarantee that an unknowable word is never guessed through. Read the
1134
- * effective command's name as
1135
- * `res.effective.static ? res.effective.text : null`.
1136
- * `sudo -u x "$prog"` and `exec "$@"` have a non-static `effective` with
1137
- * reason `expansion`; `env -S '…'` and `bash -c '…'` have reason
1138
- * `embedded-command`; `chain`
1139
- * lists every word resolved along the way, outermost wrapper first, and
1140
- * `chainIndices` gives each entry's position in the command's `argv` (as
1141
- * {@link ShellSourceCode.getCommandSites} reports it). When `effective` is
1142
- * static, the effective command's arguments are
1143
- * `argv.slice(chainIndices.at(-1)! + 1)`: every entry after the effective
1144
- * command's own index. For an interpreter command string the final chain
1145
- * index instead locates the selector flag; the interpreter is in `chain.at(-2)`.
1146
- * `embeddedCommandInterpreters: []` retains the interpreter as the static
1147
- * effective command when a policy needs program identity. Utility wrappers
1148
- * can match absolute-path basenames; `shellBuiltin: true` entries require
1149
- * exact names, so external paths do not acquire in-process semantics.
1150
- *
1151
- * Enumeration runs once per file, the first time any command helper is
1152
- * called. If the file's nesting exceeds `enumerateCommands`'s recursion
1153
- * guard, its `ShAnalyzeMaxDepthError` propagates unchanged and ESLint
1154
- * reports the rule as crashed for that file. That fails closed: a partial
1155
- * index would silently omit real commands.
1156
- *
1157
- * @param callExpr - A parsed `CallExpr` node from this file's lint tree.
1158
- * @param options - Forwarded to `resolveArgv0` unchanged.
1159
- * `transparentWrappers` replaces `sh-ast/analyze`'s
1160
- * `DEFAULT_TRANSPARENT_WRAPPERS`; spread the defaults into the array to
1161
- * extend them instead.
1162
- * @returns The resolution, or `null` when `callExpr` invokes no command.
1163
- * @throws TypeError when `callExpr` is not a parsed shell `CallExpr`.
1164
- * @throws `ShAnalyzeMaxDepthError` (from `sh-ast/analyze`) when this file's
1165
- * nesting exceeds analysis's recursion guard.
1166
- * @throws `ShAnalyzeInvalidWrapperSpecError` (from `sh-ast/analyze`) when
1167
- * `options.transparentWrappers` contains a malformed entry.
1168
- */
1169
- resolveInvokedCommand(callExpr: ShellNodeOf<'CallExpr'>, options?: ResolveArgv0Options): Argv0Resolution | null;
1170
- /**
1171
- * Returns every command invocation in this file, one entry per
1172
- * `sh-ast/analyze` `CommandSite`, in source order. Use it when a rule needs
1173
- * the whole file's commands with their structural context, such as every
1174
- * command inside a function or inside `$(…)`, instead of visiting
1175
- * `CallExpr` nodes one by one.
1176
- *
1177
- * The data comes from `sh-ast/analyze`'s `enumerateCommands`: facts about
1178
- * how each command is reached and what its words resolve to, never a
1179
- * verdict. Each entry's `context`, `argv0`, and `argv` are analysis's own
1180
- * values, unchanged; `context` lists frames outermost first, as in sh-ast.
1181
- * Each entry's `node` is the `CallExpr` view node (`===` the node ESLint
1182
- * passes to a `CallExpr` visitor), so it can be passed to
1183
- * `context.report()`.
1184
- *
1185
- * An assignment-only statement (`FOO=1`) runs no command and has no entry,
1186
- * although a command substitution in its value (`FOO=$(date)`) does.
1187
- *
1188
- * Enumeration runs at most once per file, shared with
1189
- * {@link ShellSourceCode.getCommandName} and
1190
- * {@link ShellSourceCode.resolveInvokedCommand}, and every call returns the
1191
- * same array. Because every rule shares it, the array and everything in each
1192
- * entry except `node` are deeply frozen (see `ShellCommandSite`): no rule can
1193
- * change what another rule reads. If the file's nesting exceeds `enumerateCommands`'s
1194
- * recursion guard, its `ShAnalyzeMaxDepthError` propagates unchanged, as it
1195
- * does for those helpers: a partial list would silently omit real commands.
1196
- *
1197
- * @returns This file's command sites, in source order.
1198
- * @throws `ShAnalyzeMaxDepthError` (from `sh-ast/analyze`) when this file's
1199
- * nesting exceeds analysis's recursion guard.
1200
- */
1201
- getCommandSites(): readonly ShellCommandSite[];
1202
- /**
1203
- * Returns the sh-ast record `node` was projected from: this file's original
1204
- * parse of `node`, with every field the lint view leaves out, including
1205
- * named token positions such as `BinaryCmd.OpPos`, `Stmt.Semicolon` and
1206
- * `Redirect.OpPos`. Pass those positions to
1207
- * {@link ShellSourceCode.getIndexFromSyntaxPos} or
1208
- * {@link ShellSourceCode.getLocFromSyntaxPos} to report on them, or pass the
1209
- * record to an `sh-ast/analyze` function.
1210
- *
1211
- * The returned record is read-only by contract. It is the language's
1212
- * original parse, shared by every rule and helper linting this file, and
1213
- * mutating it is unsupported: helpers such as
1214
- * {@link ShellSourceCode.resolveWordText} read the same record and would see
1215
- * the edit. It is not frozen, so a write does not throw. Make edits on an
1216
- * editable copy from {@link ShellSourceCode.getEditableSyntax} instead.
1217
- *
1218
- * @param node - A view node from this file's lint tree.
1219
- * @returns The original sh-ast record, or `undefined` when `node` has none
1220
- * in this file: an auxiliary view (a record whose type is not an sh-ast
1221
- * `Node`, such as the `Slice` of `${x:1:2}`), a view node from another
1222
- * file's tree, or an
1223
- * object that did not come from the parser.
1224
- */
1225
- getSyntax(node: ShellNode): Node | undefined;
1226
- /**
1227
- * Returns the lint view node projected from `syntax`: the inverse of
1228
- * {@link ShellSourceCode.getSyntax}. The result is the same object (`===`)
1229
- * ESLint passes to rule visitors, so it can be passed to
1230
- * `context.report()`. Use it to come back to the view after navigating the
1231
- * original records, for example from a `Stmt` record's `Cmd`.
1232
- *
1233
- * Lookup is by object identity, so only the parser's own records match.
1234
- * sh-ast's `walk` passes its callback a fresh copy of each comment stored
1235
- * on a `Stmt`, `CaseItem` or `ArrayElem`, as Go's `syntax.Walk` does, so
1236
- * those `Comment` copies have no view node. Read the stored comment from
1237
- * the record's `Comments` array instead.
1238
- *
1239
- * @param syntax - An sh-ast `Node` record from this file's original parse.
1240
- * @returns The view node, or `undefined` for any other record, including a
1241
- * copy of one of this file's records (such as a `structuredClone`) and a
1242
- * record from another parse.
1243
- */
1244
- getViewNode(syntax: Node): ShellNode | undefined;
1245
- /**
1246
- * Returns an independent, editable deep copy of the sh-ast record `node`
1247
- * was parsed from: the first half of a printed fix. Edit the copy, then pass
1248
- * it to {@link ShellSourceCode.getPrintedReplacement}.
1249
- *
1250
- * The copy is `structuredClone` of the record
1251
- * {@link ShellSourceCode.getSyntax} returns. sh-ast documents and tests
1252
- * ordinary `structuredClone` as the supported way to make an independent
1253
- * editable copy of a syntax subtree (sh-ast 0.7.0 README, "Editing and
1254
- * printing"), so no second parse is involved. The copy owns its records,
1255
- * arrays, positions and byte buffers. Editing it leaves this file's original
1256
- * syntax, its lint view, its cached traversal and the answers of view-aware
1257
- * helpers such as `resolveWord` and
1258
- * {@link ShellSourceCode.resolveWordText} unchanged. Each call returns a new
1259
- * copy.
1260
- *
1261
- * The copy's position fields keep their original values, and the copy has
1262
- * no view node: {@link ShellSourceCode.getViewNode},
1263
- * {@link ShellSourceCode.getIndexFromSyntaxPos} and the parse's position
1264
- * snapshot describe the original source, not the edit. Keep `node` to know
1265
- * which source range the fix replaces.
1266
- *
1267
- * @param node - A view node from this file's lint tree.
1268
- * @returns A deep copy of `node`'s original sh-ast record.
1269
- * @throws TypeError when `node` has no original record in this file: an
1270
- * auxiliary view (such as the `Slice` of `${x:1:2}`), a view node of another
1271
- * file, or an object that did not come from the parser.
1272
- */
1273
- getEditableSyntax(node: ShellNode): Node;
1274
- /**
1275
- * Prints `edited` with sh-ast's `printSync` and pairs the text with the
1276
- * source range it replaces, so a printed fix is
1277
- * `fix: (fixer) => fixer.replaceTextRange(r.range, r.text)`. `edited` is
1278
- * usually a copy from {@link ShellSourceCode.getEditableSyntax} of `node`
1279
- * or of one of its ancestors.
1280
- *
1281
- * The range is `node.range`, except that a `File` root replaces the whole
1282
- * text (`[0, text.length]`) whatever `node` is, which allows whole-file
1283
- * regeneration. `options` is passed to `printSync` unchanged.
1284
- *
1285
- * The printer formats; it does not replay the source. Its output starts at
1286
- * column 0 and indents nested lines with upstream's indentation (tabs by
1287
- * default, `Indent` spaces when `options.Indent` is set). Replacing a
1288
- * multi-line root nested inside other code, such as an `if` statement in a
1289
- * function body, therefore keeps the shell meaning but may change the
1290
- * formatting of its lines. Use a `Word` or `WordPart` root for a surgical
1291
- * fix that leaves the surrounding source as written.
1292
- *
1293
- * A `Stmt` root is adjusted so its text matches `node.range`. A statement's
1294
- * own leading and trailing comments lie outside its range, so they are not
1295
- * printed (the copy passed in is not modified). When `node` is a statement
1296
- * whose range ends in its `;` or `&` terminator, upstream prints the
1297
- * statement without a `;`, so a `;` is appended unless the edited statement
1298
- * prints its own `&`, `|&` or disown operator. Without this, replacing `a`
1299
- * in `a; b` would produce `a b`.
1300
- *
1301
- * @param node - A view node from this file's lint tree: the node the fix
1302
- * replaces.
1303
- * @param edited - The record to print: a `File`, `Stmt`, `Word`, `Assign`,
1304
- * `Command` or `WordPart`.
1305
- * @param options - Forwarded to `printSync` unchanged.
1306
- * @returns The range to replace and the printed text to put there.
1307
- * @throws TypeError when `node` has no original record in this file (see
1308
- * {@link ShellSourceCode.getEditableSyntax}), when `edited` is not a
1309
- * printable root (the message names its type), or when the printer's output
1310
- * is not valid UTF-8, or the edited syntax contains literal vertical tabs or
1311
- * form feeds that the printer cannot preserve. Non-UTF-8 output comes back
1312
- * from `printSync` as a `Uint8Array` and is never decoded lossily into a fix.
1313
- * @throws `PrintError` or `PrintPanicError` (from sh-ast) when upstream's
1314
- * printer fails for `edited` or `options`.
1315
- */
1316
- getPrintedReplacement(node: ShellNode, edited: Node, options?: PrintOptions): {
1317
- range: [number, number];
1318
- text: string;
1319
- };
1320
- /**
1321
- * Converts a byte position from this file's original parse into the
1322
- * UTF-16 index ESLint uses for `range` and `text.slice`. sh-ast positions
1323
- * count UTF-8 bytes, so a raw `Offset` is wrong for any source with
1324
- * non-ASCII text before it. For example, in `echo 🎉 && echo 中文`,
1325
- * `getIndexFromSyntaxPos(binaryCmd.OpPos)` is the index where `&&` starts.
1326
- *
1327
- * The conversion is only correct for positions of this file's original
1328
- * parse, as read from {@link ShellSourceCode.getSyntax}'s records. The live
1329
- * positions of an edited or copied tree describe that edit, not this
1330
- * source.
1331
- *
1332
- * @param pos - A `SyntaxPos` from one of this file's original records.
1333
- * @returns The UTF-16 index of `pos` in this file's text.
1334
- * @throws RangeError when `pos` is invalid (`IsValid === false`), recovered
1335
- * (`IsRecovered === true`), or overflowed (`OffsetOverflow === true`), or
1336
- * when its offset is not a UTF-8 character boundary of this source. Such a
1337
- * position is never rounded to a nearby boundary.
1338
- * @throws TypeError when `pos` is not a `SyntaxPos`, or when this source
1339
- * code's tree was not built by this language's parser.
1340
- */
1341
- getIndexFromSyntaxPos(pos: SyntaxPos): number;
1342
- /**
1343
- * Converts a byte position from this file's original parse into a one-based
1344
- * ESLint location, the shape `context.report({ loc })` takes. The column
1345
- * counts UTF-16 code units, not bytes, and CRLF counts as one line break.
1346
- * Same contract as {@link ShellSourceCode.getIndexFromSyntaxPos}.
1347
- *
1348
- * @param pos - A `SyntaxPos` from one of this file's original records.
1349
- * @returns The one-based line and UTF-16 column of `pos`.
1350
- * @throws RangeError when `pos` is invalid, recovered, or overflowed, or
1351
- * when its offset is not a UTF-8 character boundary of this source.
1352
- * @throws TypeError when `pos` is not a `SyntaxPos`, or when this source
1353
- * code's tree was not built by this language's parser.
1354
- */
1355
- getLocFromSyntaxPos(pos: SyntaxPos): {
1356
- line: number;
1357
- column: number;
1358
- };
1359
- /**
1360
- * Returns the parent of `node`, or `undefined` for the root `File` node
1361
- * (or any node visited before `traverse()` has run once). ESLint always
1362
- * calls `traverse()` before any rule can call `getParent`/`getAncestors`,
1363
- * so in practice the map is always populated by the time a rule observes
1364
- * it.
1365
- */
1366
- getParent(node: ShellNode): ShellNode | undefined;
1367
- /**
1368
- * Produces the enter/exit steps ESLint uses for selectors and ancestor lookup.
1369
- * Child keys describe the consumer view, including its auxiliary records.
1370
- * This callback protocol is ESLint's, independent of upstream syntax.Walk.
1371
- */
1372
- traverse(): Iterable<TraversalStep>;
1373
- /**
1374
- * Returns every `Comment` node whose text is a directive or inline-config
1375
- * candidate for this source code's `directivePrefix` — the pool both
1376
- * {@link ShellSourceCode.getDisableDirectives} and {@link ShellSourceCode.applyInlineConfig} draw from,
1377
- * and the array ESLint core itself asks for directly (to warn "has no
1378
- * effect" when `linterOptions.noInlineConfig` is set — see
1379
- * `eslint`'s `lib/linter/linter.js`, the `warnInlineConfig` branch).
1380
- */
1381
- getInlineConfigNodes(): ShellComment[];
1382
- /**
1383
- * Returns the disable/enable directives found among
1384
- * {@link ShellSourceCode.getInlineConfigNodes}'s comments, recognizing all four forms —
1385
- * `<prefix>-disable`, `<prefix>-enable`, `<prefix>-disable-line`,
1386
- * `<prefix>-disable-next-line` — with `-- justification` capture, per the
1387
- * `@eslint/core` `Directive` contract. Mirrors `@eslint/json`'s
1388
- * `JSONSourceCode.getDisableDirectives` (verified against its published
1389
- * source as the named ecosystem precedent), generalized to a configurable
1390
- * prefix instead of the hardcoded `"eslint"` label.
1391
- *
1392
- * Unlike `JSONSourceCode` (whose block comments can span multiple
1393
- * physical lines, making `<prefix>-disable-line` spanning lines a real,
1394
- * reportable problem), mvdan/sh's `#` line comments cannot contain an
1395
- * embedded newline — the parser always terminates a comment at end of
1396
- * line — so that particular problem can never arise here and is not
1397
- * checked for.
1398
- */
1399
- getDisableDirectives(): {
1400
- directives: Directive[];
1401
- problems: FileProblem[];
1402
- };
1403
- /**
1404
- * Returns the whole-file inline rule configuration found among
1405
- * {@link ShellSourceCode.getInlineConfigNodes}'s comments — a bare `<prefix> <rule-config>`
1406
- * comment (e.g. `# eslint sh/rule-a: "error"`), parsed with
1407
- * `ConfigCommentParser.parseJSONLikeConfig`. Mirrors `@eslint/json`'s
1408
- * `JSONSourceCode.applyInlineConfig`. This is the surface
1409
- * `linterOptions.noInlineConfig: true` suppresses (ESLint core skips
1410
- * calling this method — and `getDisableDirectives`, together, since both
1411
- * are gated by the same flag in `eslint`'s own `linter.js` — and instead
1412
- * calls `getInlineConfigNodes` to emit a "has no effect" warning per
1413
- * comment).
1414
- */
1415
- applyInlineConfig(): {
1416
- configs: {
1417
- config: {
1418
- rules: RulesConfig;
1419
- };
1420
- loc: SourceLocation;
1421
- }[];
1422
- problems: FileProblem[];
1423
- };
1424
- }
1425
-
1426
- /**
1427
- * The listeners whose key names one node type, or that node type with the
1428
- * `:exit` suffix, each receiving exactly that node type. The key is
1429
- * unambiguous in both forms (`CallExpr`, `CallExpr:exit`), so a listener
1430
- * needs no `node.type` guard. Wildcard (`*`, `*:exit`) and attribute or
1431
- * class selectors name no single type and fall under the index signature.
1432
- *
1433
- * Exported because {@link ShellRuleVisitor} extends it.
1434
- *
1435
- * @public
1436
- */
1437
- export declare type ShellTypedListeners = {
1438
- [Type in ShellNodeType as Type | `${Type}:exit`]?: ShellListener<ShellNodeOf<Type>>;
1439
- };
1440
-
1441
- /** The rule-context fields needed to resolve shared wrappers and their path spellings. @public */
1442
- export declare interface TransparentWrappersBindingContext {
1443
- /** Shared ESLint configuration containing the project's shell facts. */
1444
- readonly settings: SettingsConfig;
1445
- /** The current file supplies path spellings without filesystem inspection or execution. */
1446
- readonly sourceCode: ShellSourceCode;
1447
- }
1448
-
1449
- export { WordResolution }
1450
-
1451
- /**
1452
- * What a "must be run through a wrapper" rule enforces. Passed to
1453
- * {@link createWrapperRule}.
1454
- *
1455
- * @public
1456
- */
1457
- export declare interface WrapperRuleConfig {
1458
- /**
1459
- * The command names that must be run through the wrapper. A static command
1460
- * word matches a name when it equals it, or when it contains a slash and
1461
- * its basename equals it (`/usr/bin/curl` and `./bin/curl` match `curl`).
1462
- */
1463
- readonly commands: readonly string[];
1464
- /**
1465
- * The wrapper the commands must be run through. A string names a wrapper
1466
- * that takes no options of its own (`retry curl x`), unless it names one of
1467
- * `sh-ast/analyze`'s default transparent wrappers (`timeout`, `nice`, …),
1468
- * whose known option shape is used. A `WrapperSpec` declares the wrapper's
1469
- * option shape, so that `retry -n 3 curl x` is recognized as `curl` run
1470
- * through `retry`; any of its `names` counts as the wrapper. Like
1471
- * `commands`, a wrapper run by path matches by basename
1472
- * (`/usr/local/bin/retry curl x`).
1473
- */
1474
- readonly wrapper: string | WrapperSpec;
1475
- /**
1476
- * Listed commands that count only with some subcommands, keyed by command
1477
- * name. A listed command with no entry here counts with any arguments.
1478
- */
1479
- readonly subcommands?: Readonly<Record<string, WrapperRuleSubcommands>>;
1480
- /**
1481
- * Invocations of a listed command that only act locally and so are not
1482
- * reported, keyed by the command as the rule's message names it: the listed
1483
- * name (`curl`), or the name with its subcommand (`git clone`).
1484
- */
1485
- readonly localInvocations?: Readonly<Record<string, WrapperRuleLocalInvocation>>;
1486
- /**
1487
- * The rule's `meta.docs` fields a rule pack owns. `url` defaults to this
1488
- * package's wrapper-rules docs page, and `description` to a sentence naming
1489
- * the commands and the wrapper. Set them to point users at the pack's own
1490
- * documentation.
1491
- */
1492
- readonly docs?: {
1493
- readonly url?: string;
1494
- readonly description?: string;
1495
- };
1496
- }
1497
-
1498
- /**
1499
- * Ways to invoke one listed command that only act locally, so the policy has
1500
- * nothing to guard. An invocation matching either field is not reported.
1501
- *
1502
- * @public
1503
- */
1504
- export declare interface WrapperRuleLocalInvocation {
1505
- /**
1506
- * Complete argument lists, after the command (and its subcommand, if it has
1507
- * one), that make the invocation local. They match exactly: with
1508
- * `[['--version']]`, `curl --version` is local and
1509
- * `curl --version https://example.com` is not.
1510
- */
1511
- readonly argLists?: readonly (readonly string[])[];
1512
- /** Local when the command's source operand is a local path. */
1513
- readonly localOperand?: WrapperRuleLocalOperand;
1514
- }
1515
-
1516
- /**
1517
- * Names the operand of a listed command whose value decides whether the
1518
- * invocation can leave the machine, such as the source of `git clone`.
1519
- *
1520
- * The flags describe the options that may precede the operand, with the same
1521
- * meaning as {@link WrapperRuleSubcommands}'s: `noArgFlags` take no value and
1522
- * `argFlags` take one (as `--depth 1`, or `--depth=1` in one word). The
1523
- * operand is the first word after them, or after a `--`. A flag that is not
1524
- * declared leaves the operand unknown, and an unknown operand is never taken
1525
- * as local.
1526
- *
1527
- * @public
1528
- */
1529
- export declare interface WrapperRuleLocalOperand extends Pick<WrapperSpec, 'noArgFlags' | 'argFlags'> {
1530
- /**
1531
- * The operand counts as local when it is a static word starting with one
1532
- * of these, such as `['./', '../', '/', 'file://']`.
1533
- */
1534
- readonly localPrefixes: readonly string[];
1535
- }
1536
-
1537
- /**
1538
- * Restricts a listed command to some of its subcommands, for commands such as
1539
- * `git` where only some subcommands are in scope (`git fetch` is a network
1540
- * call, `git status` is not).
1541
- *
1542
- * The flag fields are `WrapperSpec`'s own, picked from it so the two cannot
1543
- * drift, and describe the command's options that may appear before the
1544
- * subcommand (`git -C dir fetch`): `noArgFlags` take no operand (`--bare`),
1545
- * `argFlags` take one (`-C <dir>`), and `stopsChainFlags` mean the command
1546
- * runs no subcommand at all (`git --version fetch` prints the version, and is
1547
- * never reported). The subcommand is found the way a wrapped command is:
1548
- * declared options are skipped, and a flag the command does not declare
1549
- * leaves the subcommand unknown, so the invocation is not reported.
1550
- *
1551
- * @public
1552
- */
1553
- export declare interface WrapperRuleSubcommands extends Pick<WrapperSpec, 'noArgFlags' | 'argFlags' | 'stopsChainFlags'> {
1554
- /** The subcommands that make an invocation of the command count, such as `['fetch', 'push']`. */
1555
- readonly names: readonly string[];
1556
- }
1557
-
1558
- export { WrapperSpec }
1559
-
1560
- export { }
1
+ /**
2
+ * Published types compose the generated public API with Node's require(ESM)
3
+ * result. The relative dist path resolves both here and in the copied dist entry.
4
+ * API Extractor cannot print the quoted export; installed-consumer
5
+ * tests cover this declaration separately. Runtime properties share identities
6
+ * with the ESM namespace and are non-enumerable, read-only plugin properties.
7
+ */
8
+ import plugin from '../dist/eslint-plugin-api.js';
9
+ import type * as api from '../dist/eslint-plugin-api.js';
10
+
11
+ export { default } from '../dist/eslint-plugin-api.js';
12
+ export * from '../dist/eslint-plugin-api.js';
13
+
14
+ /** The plugin plus its hidden namespace properties, as returned by require(). @public */
15
+ declare const commonJsModule: typeof plugin & Readonly<typeof api>;
16
+ export { commonJsModule as 'module.exports' };