@nokout/big-dill-core 0.0.1

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 (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +202 -0
  3. package/dist/completion/complete.d.ts +40 -0
  4. package/dist/completion/complete.d.ts.map +1 -0
  5. package/dist/completion/complete.js +134 -0
  6. package/dist/completion/complete.js.map +1 -0
  7. package/dist/format/tables.d.ts +7 -0
  8. package/dist/format/tables.d.ts.map +1 -0
  9. package/dist/format/tables.js +87 -0
  10. package/dist/format/tables.js.map +1 -0
  11. package/dist/gherkin/parser.d.ts +28 -0
  12. package/dist/gherkin/parser.d.ts.map +1 -0
  13. package/dist/gherkin/parser.js +44 -0
  14. package/dist/gherkin/parser.js.map +1 -0
  15. package/dist/index.d.ts +25 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +92 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/ipc/server.d.ts +13 -0
  20. package/dist/ipc/server.d.ts.map +1 -0
  21. package/dist/ipc/server.js +106 -0
  22. package/dist/ipc/server.js.map +1 -0
  23. package/dist/lint/rules.d.ts +46 -0
  24. package/dist/lint/rules.d.ts.map +1 -0
  25. package/dist/lint/rules.js +387 -0
  26. package/dist/lint/rules.js.map +1 -0
  27. package/dist/protocol/types.d.ts +97 -0
  28. package/dist/protocol/types.d.ts.map +1 -0
  29. package/dist/protocol/types.js +5 -0
  30. package/dist/protocol/types.js.map +1 -0
  31. package/dist/pytest/runner.d.ts +29 -0
  32. package/dist/pytest/runner.d.ts.map +1 -0
  33. package/dist/pytest/runner.js +225 -0
  34. package/dist/pytest/runner.js.map +1 -0
  35. package/dist/results/outcomes.d.ts +36 -0
  36. package/dist/results/outcomes.d.ts.map +1 -0
  37. package/dist/results/outcomes.js +69 -0
  38. package/dist/results/outcomes.js.map +1 -0
  39. package/dist/steps/browser.d.ts +42 -0
  40. package/dist/steps/browser.d.ts.map +1 -0
  41. package/dist/steps/browser.js +110 -0
  42. package/dist/steps/browser.js.map +1 -0
  43. package/dist/steps/documentation.d.ts +10 -0
  44. package/dist/steps/documentation.d.ts.map +1 -0
  45. package/dist/steps/documentation.js +39 -0
  46. package/dist/steps/documentation.js.map +1 -0
  47. package/dist/steps/references.d.ts +10 -0
  48. package/dist/steps/references.d.ts.map +1 -0
  49. package/dist/steps/references.js +34 -0
  50. package/dist/steps/references.js.map +1 -0
  51. package/dist/steps/stepCache.d.ts +50 -0
  52. package/dist/steps/stepCache.d.ts.map +1 -0
  53. package/dist/steps/stepCache.js +149 -0
  54. package/dist/steps/stepCache.js.map +1 -0
  55. package/dist/steps/stubs.d.ts +10 -0
  56. package/dist/steps/stubs.d.ts.map +1 -0
  57. package/dist/steps/stubs.js +46 -0
  58. package/dist/steps/stubs.js.map +1 -0
  59. package/dist/steps/unimplemented.d.ts +10 -0
  60. package/dist/steps/unimplemented.d.ts.map +1 -0
  61. package/dist/steps/unimplemented.js +26 -0
  62. package/dist/steps/unimplemented.js.map +1 -0
  63. package/dist/symbols/outline.d.ts +13 -0
  64. package/dist/symbols/outline.d.ts.map +1 -0
  65. package/dist/symbols/outline.js +38 -0
  66. package/dist/symbols/outline.js.map +1 -0
  67. package/dist/tokens/semanticTokens.d.ts +13 -0
  68. package/dist/tokens/semanticTokens.d.ts.map +1 -0
  69. package/dist/tokens/semanticTokens.js +77 -0
  70. package/dist/tokens/semanticTokens.js.map +1 -0
  71. package/dist/tree/builder.d.ts +40 -0
  72. package/dist/tree/builder.d.ts.map +1 -0
  73. package/dist/tree/builder.js +178 -0
  74. package/dist/tree/builder.js.map +1 -0
  75. package/package.json +58 -0
  76. package/src/completion/complete.ts +165 -0
  77. package/src/format/tables.ts +108 -0
  78. package/src/gherkin/parser.ts +69 -0
  79. package/src/index.ts +136 -0
  80. package/src/ipc/server.ts +84 -0
  81. package/src/lint/rules.ts +425 -0
  82. package/src/protocol/types.ts +114 -0
  83. package/src/pytest/runner.ts +249 -0
  84. package/src/results/outcomes.ts +102 -0
  85. package/src/steps/browser.ts +105 -0
  86. package/src/steps/documentation.ts +43 -0
  87. package/src/steps/references.ts +33 -0
  88. package/src/steps/stepCache.ts +168 -0
  89. package/src/steps/stubs.ts +48 -0
  90. package/src/steps/unimplemented.ts +31 -0
  91. package/src/symbols/outline.ts +52 -0
  92. package/src/tokens/semanticTokens.ts +98 -0
  93. package/src/tree/builder.ts +187 -0
package/src/index.ts ADDED
@@ -0,0 +1,136 @@
1
+ // Copyright (c) 2026 Nigel O'Keefe. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ /**
5
+ * @nokout/big-dill-core — the headless engine behind Big Dill.
6
+ *
7
+ * Nothing exported here depends on an editor. Results are plain data; mapping
8
+ * them onto editor types is the host's responsibility. See the "Building a
9
+ * host" section of README.md for what a host must provide.
10
+ */
11
+
12
+ // ── Gherkin parsing ─────────────────────────────────────────────────────────
13
+ export {
14
+ parseSource,
15
+ GherkinParseCache,
16
+ type ParseResult,
17
+ type CacheableDocument,
18
+ } from './gherkin/parser';
19
+
20
+ // ── Structural linting ──────────────────────────────────────────────────────
21
+ export {
22
+ lintDocument,
23
+ graduatePhrasingSeverity,
24
+ RULES,
25
+ checkEmptyComments,
26
+ checkDuplicateExampleRows,
27
+ checkOversizedExampleTable,
28
+ checkOutlineMissingExamples,
29
+ checkEmptyExamplesBody,
30
+ checkTagAllowlist,
31
+ checkScenarioShouldBeOutline,
32
+ checkScenarioHasExamplesNotOutline,
33
+ checkUndefinedExampleColumn,
34
+ checkUnusedExampleColumn,
35
+ checkDuplicateScenarioName,
36
+ checkDuplicateExamplesColumn,
37
+ checkEmptyScenario,
38
+ checkOutlineSingleRow,
39
+ checkPhrasingRules,
40
+ type DiagnosticEntry,
41
+ type PhrasingRule,
42
+ type LintConfig,
43
+ } from './lint/rules';
44
+
45
+ // ── Completion ──────────────────────────────────────────────────────────────
46
+ export {
47
+ completeAt,
48
+ completeStepPatterns,
49
+ completeParameterValues,
50
+ extractStepText,
51
+ type CompletionEntry,
52
+ type CompletionKind,
53
+ type KeywordAndText,
54
+ } from './completion/complete';
55
+
56
+ // ── Document outline ────────────────────────────────────────────────────────
57
+ export { buildSymbolTree, type SymbolNode, type SymbolNodeKind } from './symbols/outline';
58
+
59
+ // ── Semantic tokens ─────────────────────────────────────────────────────────
60
+ export {
61
+ buildTableTokens,
62
+ TOKEN_TYPES,
63
+ TYPE_INDEX,
64
+ type TokenType,
65
+ type TokenEntry,
66
+ } from './tokens/semanticTokens';
67
+
68
+ // ── Table formatting ────────────────────────────────────────────────────────
69
+ export { formatTables, type TextEditEntry } from './format/tables';
70
+
71
+ // ── Step documentation, stubs, references ───────────────────────────────────
72
+ export { renderStepMarkdown } from './steps/documentation';
73
+ export { buildStepStub, patternToFunctionName } from './steps/stubs';
74
+ export { findReferencesInLines } from './steps/references';
75
+ export { findUnimplementedSteps, type UnimplementedStep } from './steps/unimplemented';
76
+
77
+ // ── Step browser model ──────────────────────────────────────────────────────
78
+ export {
79
+ browseSteps,
80
+ filterSteps,
81
+ groupLabels,
82
+ stepsInGroup,
83
+ UNKNOWN_FILE,
84
+ NO_TYPE,
85
+ UNTAGGED,
86
+ type GroupingMode,
87
+ type StepBrowserNode,
88
+ type BrowseOptions,
89
+ } from './steps/browser';
90
+
91
+ // ── Step indexing ───────────────────────────────────────────────────────────
92
+ export { StepCache, patternToRegex, type LineMatch, type ParamAtPosition } from './steps/stepCache';
93
+
94
+ // ── pytest IPC ──────────────────────────────────────────────────────────────
95
+ export { createIpcServer, type IIpcServer, type IpcMessageHandler } from './ipc/server';
96
+
97
+ // ── Test tree shape ─────────────────────────────────────────────────────────
98
+ export {
99
+ buildTestTree,
100
+ type TreeNode,
101
+ type TreeNodeUri,
102
+ type TreeNodeRange,
103
+ type BuiltTree,
104
+ } from './tree/builder';
105
+
106
+ // ── Execution outcomes ──────────────────────────────────────────────────────
107
+ export {
108
+ resolveExecutionOutcomes,
109
+ WAITING_PREFIX,
110
+ type RunState,
111
+ type OutcomeDecision,
112
+ } from './results/outcomes';
113
+
114
+ // ── Running pytest ──────────────────────────────────────────────────────────
115
+ export {
116
+ discoverTests,
117
+ runTests,
118
+ runBddLint,
119
+ type PytestOptions,
120
+ type DiscoveryResult,
121
+ } from './pytest/runner';
122
+
123
+ // ── Wire protocol ───────────────────────────────────────────────────────────
124
+ export type {
125
+ DiscoveredTestType,
126
+ DiscoveredTestCommon,
127
+ DiscoveredTestItem,
128
+ DiscoveredTestNode,
129
+ DiscoveredTestPayload,
130
+ ExecutionTestPayload,
131
+ StepParameter,
132
+ StepDefinition,
133
+ StepDefinitionPayload,
134
+ LintDiagnosticEntry,
135
+ LintDiagnosticPayload,
136
+ } from './protocol/types';
@@ -0,0 +1,84 @@
1
+ // Copyright (c) 2026 Nigel O'Keefe. All rights reserved.
2
+ // Licensed under the MIT License.
3
+ // BIG-DILL: Named-pipe IPC server — receives JSON-RPC messages from vscode_pytest.
4
+ // Protocol mirrors ms-python: content-length framing over a named pipe.
5
+
6
+ import * as net from 'net';
7
+ import * as os from 'os';
8
+ import * as path from 'path';
9
+ import * as crypto from 'crypto';
10
+
11
+ export type IpcMessageHandler = (data: Record<string, unknown>) => void;
12
+
13
+ export interface IIpcServer {
14
+ readonly pipeName: string;
15
+ onMessage(handler: IpcMessageHandler): void;
16
+ dispose(): void;
17
+ }
18
+
19
+ /**
20
+ * Start a named-pipe server. Returns a promise that resolves once the server
21
+ * is listening. The caller should pass `server.pipeName` to the subprocess as
22
+ * the `TEST_RUN_PIPE` env var.
23
+ */
24
+ export async function createIpcServer(): Promise<IIpcServer> {
25
+ const pipeName = os.platform() === 'win32'
26
+ ? `\\\\.\\pipe\\pytest-bdd-${crypto.randomUUID()}`
27
+ : path.join(os.tmpdir(), `pytest-bdd-${crypto.randomUUID()}.sock`);
28
+
29
+ const handlers: IpcMessageHandler[] = [];
30
+ const server = net.createServer((socket) => {
31
+ let buffer = '';
32
+ socket.on('data', (chunk) => {
33
+ buffer += chunk.toString('utf-8');
34
+ // Parse all complete content-length framed messages from buffer
35
+ while (true) {
36
+ const headerEnd = buffer.indexOf('\r\n\r\n');
37
+ if (headerEnd === -1) break;
38
+
39
+ const header = buffer.substring(0, headerEnd);
40
+ const lengthMatch = header.match(/content-length:\s*(\d+)/i);
41
+ if (!lengthMatch) {
42
+ // Malformed frame — discard up to the double-CRLF
43
+ buffer = buffer.substring(headerEnd + 4);
44
+ break;
45
+ }
46
+
47
+ const contentLength = parseInt(lengthMatch[1], 10);
48
+ const bodyStart = headerEnd + 4;
49
+ if (buffer.length < bodyStart + contentLength) {
50
+ break; // need more data
51
+ }
52
+
53
+ const body = buffer.substring(bodyStart, bodyStart + contentLength);
54
+ buffer = buffer.substring(bodyStart + contentLength);
55
+
56
+ try {
57
+ const rpc = JSON.parse(body) as { params?: Record<string, unknown> };
58
+ const payload = rpc.params ?? rpc;
59
+ for (const handler of handlers) {
60
+ handler(payload);
61
+ }
62
+ } catch {
63
+ // ignore malformed JSON
64
+ }
65
+ }
66
+ });
67
+ socket.on('error', () => { /* ignore socket errors */ });
68
+ });
69
+
70
+ await new Promise<void>((resolve, reject) => {
71
+ server.listen(pipeName, resolve);
72
+ server.once('error', reject);
73
+ });
74
+
75
+ return {
76
+ pipeName,
77
+ onMessage(handler: IpcMessageHandler) {
78
+ handlers.push(handler);
79
+ },
80
+ dispose() {
81
+ server.close();
82
+ },
83
+ };
84
+ }
@@ -0,0 +1,425 @@
1
+ // Copyright (c) 2026 Nigel O'Keefe. All rights reserved.
2
+ // Licensed under the MIT License.
3
+ //
4
+ // Structural lint rules for Gherkin documents.
5
+ //
6
+ // Every rule is a pure function of (document, lines) returning plain
7
+ // DiagnosticEntry objects. Nothing here knows what an editor is — mapping to
8
+ // editor diagnostics is the host's job.
9
+
10
+ import type { GherkinDocument } from '@cucumber/messages';
11
+ import type { StepCache } from '../steps/stepCache';
12
+
13
+ export interface DiagnosticEntry {
14
+ line: number; // 0-indexed
15
+ message: string;
16
+ severity: 'error' | 'warning' | 'info';
17
+ }
18
+
19
+ export function checkEmptyComments(doc: GherkinDocument, _lines: string[]): DiagnosticEntry[] {
20
+ return (doc.comments ?? [])
21
+ .filter((c) => c.text.trim() === '#')
22
+ .map((c) => ({
23
+ line: (c.location?.line ?? 1) - 1,
24
+ message: 'Empty comment not allowed',
25
+ severity: 'warning' as const,
26
+ }));
27
+ }
28
+
29
+ export function checkDuplicateExampleRows(doc: GherkinDocument, _lines: string[]): DiagnosticEntry[] {
30
+ const diags: DiagnosticEntry[] = [];
31
+ for (const child of doc.feature?.children ?? []) {
32
+ for (const examples of child.scenario?.examples ?? []) {
33
+ const seen = new Set<string>();
34
+ for (const row of examples.tableBody) {
35
+ const key = row.cells.map((c) => c.value).join('\0');
36
+ if (seen.has(key)) {
37
+ diags.push({
38
+ line: (row.location?.line ?? 1) - 1,
39
+ message: `Duplicate example row: ${row.cells.map((c) => c.value).join(', ')}`,
40
+ severity: 'warning',
41
+ });
42
+ }
43
+ seen.add(key);
44
+ }
45
+ }
46
+ }
47
+ return diags;
48
+ }
49
+
50
+ export function checkOversizedExampleTable(doc: GherkinDocument, _lines: string[]): DiagnosticEntry[] {
51
+ const diags: DiagnosticEntry[] = [];
52
+ for (const child of doc.feature?.children ?? []) {
53
+ for (const examples of child.scenario?.examples ?? []) {
54
+ if (examples.tableBody.length > 20) {
55
+ diags.push({
56
+ line: (examples.location?.line ?? 1) - 1,
57
+ message: `Examples table has ${examples.tableBody.length} rows — consider splitting (limit: 20)`,
58
+ severity: 'warning',
59
+ });
60
+ }
61
+ }
62
+ }
63
+ return diags;
64
+ }
65
+
66
+ export function checkOutlineMissingExamples(doc: GherkinDocument, _lines: string[]): DiagnosticEntry[] {
67
+ const diags: DiagnosticEntry[] = [];
68
+ for (const child of doc.feature?.children ?? []) {
69
+ const scenario = child.scenario;
70
+ if (!scenario) continue;
71
+ if (scenario.keyword.trim().toLowerCase().includes('outline') && scenario.examples.length === 0) {
72
+ diags.push({
73
+ line: (scenario.location?.line ?? 1) - 1,
74
+ message: `Scenario Outline '${scenario.name}' has no Examples block`,
75
+ severity: 'error',
76
+ });
77
+ }
78
+ }
79
+ return diags;
80
+ }
81
+
82
+ export function checkEmptyExamplesBody(doc: GherkinDocument, _lines: string[]): DiagnosticEntry[] {
83
+ const diags: DiagnosticEntry[] = [];
84
+ for (const child of doc.feature?.children ?? []) {
85
+ for (const examples of child.scenario?.examples ?? []) {
86
+ if (examples.tableHeader && examples.tableBody.length === 0) {
87
+ diags.push({
88
+ line: (examples.location?.line ?? 1) - 1,
89
+ message: 'Examples block has no data rows',
90
+ severity: 'error',
91
+ });
92
+ }
93
+ }
94
+ }
95
+ return diags;
96
+ }
97
+
98
+ export function checkTagAllowlist(
99
+ doc: GherkinDocument,
100
+ _lines: string[],
101
+ allowedTags: string[],
102
+ ): DiagnosticEntry[] {
103
+ if (allowedTags.length === 0) return [];
104
+
105
+ const allowed = new Set(allowedTags.map((t) => t.startsWith('@') ? t : `@${t}`));
106
+ const diags: DiagnosticEntry[] = [];
107
+
108
+ function checkTags(tags: ReadonlyArray<{ name: string; location?: { line?: number } }>) {
109
+ for (const tag of tags) {
110
+ if (!allowed.has(tag.name)) {
111
+ diags.push({
112
+ line: (tag.location?.line ?? 1) - 1,
113
+ message: `Tag ${tag.name} is not in the allowed tags list`,
114
+ severity: 'warning',
115
+ });
116
+ }
117
+ }
118
+ }
119
+
120
+ checkTags(doc.feature?.tags ?? []);
121
+ for (const child of doc.feature?.children ?? []) {
122
+ checkTags(child.scenario?.tags ?? []);
123
+ }
124
+
125
+ return diags;
126
+ }
127
+
128
+ // Bounded quantifier: /<[^>]+>/ is quadratic on a long run of unclosed '<',
129
+ // because the engine retries the inner scan from every one of them. The linter
130
+ // runs on every keystroke, so a pasted malformed line could stall the editor.
131
+ // No real Examples placeholder approaches 200 characters.
132
+ const EXAMPLE_PARAM_RE = /<[^>]{1,200}>/;
133
+
134
+ export function checkScenarioShouldBeOutline(doc: GherkinDocument, _lines: string[]): DiagnosticEntry[] {
135
+ const diags: DiagnosticEntry[] = [];
136
+ for (const child of doc.feature?.children ?? []) {
137
+ const scenario = child.scenario;
138
+ if (!scenario) continue;
139
+ if (scenario.keyword.trim().toLowerCase().includes('outline')) continue;
140
+ for (const step of scenario.steps) {
141
+ if (EXAMPLE_PARAM_RE.test(step.text ?? '')) {
142
+ diags.push({
143
+ line: (scenario.location?.line ?? 1) - 1,
144
+ message: `Scenario '${scenario.name}' uses <param> syntax — use Scenario Outline`,
145
+ severity: 'warning',
146
+ });
147
+ break;
148
+ }
149
+ }
150
+ }
151
+ return diags;
152
+ }
153
+
154
+ export function checkScenarioHasExamplesNotOutline(doc: GherkinDocument, _lines: string[]): DiagnosticEntry[] {
155
+ const diags: DiagnosticEntry[] = [];
156
+ for (const child of doc.feature?.children ?? []) {
157
+ const scenario = child.scenario;
158
+ if (!scenario) continue;
159
+ if (scenario.keyword.trim().toLowerCase().includes('outline')) continue;
160
+ if (scenario.examples.length > 0) {
161
+ diags.push({
162
+ line: (scenario.examples[0].location?.line ?? scenario.location?.line ?? 1) - 1,
163
+ message: `Examples table found under Scenario '${scenario.name}' — change keyword to Scenario Outline`,
164
+ severity: 'error',
165
+ });
166
+ }
167
+ }
168
+ return diags;
169
+ }
170
+
171
+ const PLACEHOLDER_RE = /<([^<>]+)>/g;
172
+
173
+ type Scenario = NonNullable<NonNullable<GherkinDocument['feature']>['children'][number]['scenario']>;
174
+ type Step = Scenario['steps'][number];
175
+
176
+ /** All scenarios in the document, including those nested inside Rule blocks. */
177
+ function allScenarios(doc: GherkinDocument): Scenario[] {
178
+ return (doc.feature?.children ?? []).flatMap((child) =>
179
+ child.scenario ? [child.scenario]
180
+ : (child.rule?.children ?? []).flatMap((rc) => rc.scenario ? [rc.scenario] : []),
181
+ );
182
+ }
183
+
184
+ function isOutline(scenario: Scenario): boolean {
185
+ return scenario.keyword.trim().toLowerCase().includes('outline');
186
+ }
187
+
188
+ /**
189
+ * Texts in which Example placeholders are substituted: step text, datatable
190
+ * cells, and docstring content (pytest-bdd ≥8) — each with its 0-indexed line.
191
+ */
192
+ function placeholderSources(step: Step): Array<{ text: string; line: number }> {
193
+ const sources = [{ text: step.text ?? '', line: (step.location?.line ?? 1) - 1 }];
194
+ for (const row of step.dataTable?.rows ?? []) {
195
+ sources.push({
196
+ text: row.cells.map((c) => c.value).join(' '),
197
+ line: (row.location?.line ?? step.location?.line ?? 1) - 1,
198
+ });
199
+ }
200
+ if (step.docString) {
201
+ const startLine = step.docString.location?.line ?? step.location?.line ?? 1;
202
+ step.docString.content.split('\n').forEach((text, i) => {
203
+ sources.push({ text, line: startLine + i }); // content starts after the opening """
204
+ });
205
+ }
206
+ return sources;
207
+ }
208
+
209
+ export function checkUndefinedExampleColumn(doc: GherkinDocument, _lines: string[]): DiagnosticEntry[] {
210
+ const diags: DiagnosticEntry[] = [];
211
+ for (const scenario of allScenarios(doc)) {
212
+ if (!isOutline(scenario)) continue;
213
+
214
+ const headers = scenario.examples.filter((e) => e.tableHeader);
215
+ if (headers.length === 0) continue;
216
+ const columns = new Set(headers.flatMap((e) => e.tableHeader!.cells.map((c) => c.value)));
217
+
218
+ for (const step of scenario.steps) {
219
+ const missing = new Map<string, number>();
220
+ for (const { text, line } of placeholderSources(step)) {
221
+ for (const match of text.matchAll(PLACEHOLDER_RE)) {
222
+ if (!columns.has(match[1]) && !missing.has(match[1])) missing.set(match[1], line);
223
+ }
224
+ }
225
+ for (const [name, line] of missing) {
226
+ diags.push({
227
+ line,
228
+ message: `Step references <${name}> but no Examples column '${name}' exists`,
229
+ severity: 'error',
230
+ });
231
+ }
232
+ }
233
+ }
234
+ return diags;
235
+ }
236
+
237
+ export function checkUnusedExampleColumn(doc: GherkinDocument, _lines: string[]): DiagnosticEntry[] {
238
+ const diags: DiagnosticEntry[] = [];
239
+ for (const scenario of allScenarios(doc)) {
240
+ if (!isOutline(scenario)) continue;
241
+
242
+ const referenced = new Set<string>();
243
+ for (const step of scenario.steps) {
244
+ for (const { text } of placeholderSources(step)) {
245
+ for (const match of text.matchAll(PLACEHOLDER_RE)) referenced.add(match[1]);
246
+ }
247
+ }
248
+
249
+ // An undefined reference is usually the other half of the same typo —
250
+ // leave that outline to checkUndefinedExampleColumn and re-evaluate
251
+ // unused columns once the reference is fixed.
252
+ const columns = new Set(
253
+ scenario.examples.flatMap((e) => e.tableHeader?.cells.map((c) => c.value) ?? []),
254
+ );
255
+ if ([...referenced].some((name) => !columns.has(name))) continue;
256
+
257
+ for (const examples of scenario.examples) {
258
+ for (const cell of examples.tableHeader?.cells ?? []) {
259
+ if (!referenced.has(cell.value)) {
260
+ diags.push({
261
+ line: (cell.location?.line ?? examples.location?.line ?? 1) - 1,
262
+ message: `Examples column '${cell.value}' is never referenced by any step`,
263
+ severity: 'warning',
264
+ });
265
+ }
266
+ }
267
+ }
268
+ }
269
+ return diags;
270
+ }
271
+
272
+ export function checkDuplicateScenarioName(doc: GherkinDocument, _lines: string[]): DiagnosticEntry[] {
273
+ const diags: DiagnosticEntry[] = [];
274
+ const firstSeen = new Map<string, number>();
275
+ for (const scenario of allScenarios(doc)) {
276
+ const name = scenario.name.trim();
277
+ if (!name) continue;
278
+ const line = scenario.location?.line ?? 1;
279
+ const first = firstSeen.get(name);
280
+ if (first !== undefined) {
281
+ diags.push({
282
+ line: line - 1,
283
+ message: `Duplicate scenario name '${name}' (first used on line ${first})`,
284
+ severity: 'warning',
285
+ });
286
+ } else {
287
+ firstSeen.set(name, line);
288
+ }
289
+ }
290
+ return diags;
291
+ }
292
+
293
+ export function checkDuplicateExamplesColumn(doc: GherkinDocument, _lines: string[]): DiagnosticEntry[] {
294
+ const diags: DiagnosticEntry[] = [];
295
+ for (const scenario of allScenarios(doc)) {
296
+ for (const examples of scenario.examples) {
297
+ const seen = new Set<string>();
298
+ const reported = new Set<string>();
299
+ for (const cell of examples.tableHeader?.cells ?? []) {
300
+ if (seen.has(cell.value) && !reported.has(cell.value)) {
301
+ diags.push({
302
+ line: (cell.location?.line ?? examples.location?.line ?? 1) - 1,
303
+ message: `Duplicate Examples column '${cell.value}'`,
304
+ severity: 'error',
305
+ });
306
+ reported.add(cell.value);
307
+ }
308
+ seen.add(cell.value);
309
+ }
310
+ }
311
+ }
312
+ return diags;
313
+ }
314
+
315
+ export function checkEmptyScenario(doc: GherkinDocument, _lines: string[]): DiagnosticEntry[] {
316
+ return allScenarios(doc)
317
+ .filter((scenario) => scenario.steps.length === 0)
318
+ .map((scenario) => ({
319
+ line: (scenario.location?.line ?? 1) - 1,
320
+ message: `Scenario '${scenario.name}' has no steps`,
321
+ severity: 'error' as const,
322
+ }));
323
+ }
324
+
325
+ export function checkOutlineSingleRow(doc: GherkinDocument, _lines: string[]): DiagnosticEntry[] {
326
+ const diags: DiagnosticEntry[] = [];
327
+ for (const scenario of allScenarios(doc)) {
328
+ if (!isOutline(scenario)) continue;
329
+ if (scenario.examples.length !== 1) continue;
330
+ if (scenario.examples[0].tableBody.length === 1) {
331
+ diags.push({
332
+ line: (scenario.location?.line ?? 1) - 1,
333
+ message: `Scenario Outline '${scenario.name}' has a single example row — consider a plain Scenario`,
334
+ severity: 'info',
335
+ });
336
+ }
337
+ }
338
+ return diags;
339
+ }
340
+
341
+ export interface PhrasingRule {
342
+ pattern: string;
343
+ message: string;
344
+ }
345
+
346
+ export function checkPhrasingRules(
347
+ doc: GherkinDocument,
348
+ _lines: string[],
349
+ rules: PhrasingRule[],
350
+ ): DiagnosticEntry[] {
351
+ if (rules.length === 0) return [];
352
+
353
+ const compiled = rules.map((r) => ({ re: new RegExp(r.pattern, 'i'), message: r.message }));
354
+ const diags: DiagnosticEntry[] = [];
355
+
356
+ for (const child of doc.feature?.children ?? []) {
357
+ const steps = child.scenario?.steps ?? child.background?.steps ?? [];
358
+ for (const step of steps) {
359
+ const text = step.text ?? '';
360
+ for (const { re, message } of compiled) {
361
+ if (re.test(text)) {
362
+ diags.push({
363
+ line: (step.location?.line ?? 1) - 1,
364
+ message,
365
+ severity: 'warning',
366
+ });
367
+ break; // one diagnostic per step per pass
368
+ }
369
+ }
370
+ }
371
+ }
372
+
373
+ return diags;
374
+ }
375
+
376
+ export const RULES = [
377
+ checkEmptyComments,
378
+ checkDuplicateExampleRows,
379
+ checkOversizedExampleTable,
380
+ checkOutlineMissingExamples,
381
+ checkEmptyExamplesBody,
382
+ checkScenarioShouldBeOutline,
383
+ checkScenarioHasExamplesNotOutline,
384
+ checkUndefinedExampleColumn,
385
+ checkUnusedExampleColumn,
386
+ checkDuplicateScenarioName,
387
+ checkDuplicateExamplesColumn,
388
+ checkEmptyScenario,
389
+ checkOutlineSingleRow,
390
+ ];
391
+ /**
392
+ * Return the appropriate diagnostic severity for a phrasing violation on *stepText*.
393
+ * - 'warning' if the step has no matching implementation (proposing new wording)
394
+ * - 'information' if the step matches a known implementation (existing convention violation)
395
+ */
396
+ export function graduatePhrasingSeverity(
397
+ stepText: string,
398
+ cache: StepCache,
399
+ ): 'warning' | 'information' {
400
+ return cache.matchPattern(stepText) ? 'information' : 'warning';
401
+ }
402
+
403
+ /** Configuration consumed by the lint pass, as plain data. */
404
+ export interface LintConfig {
405
+ allowedTags?: string[];
406
+ phrasingRules?: PhrasingRule[];
407
+ }
408
+
409
+ /**
410
+ * Run every structural rule plus the configurable checks over a parsed document.
411
+ *
412
+ * This is the entry point a host should call; it replaces the dispatch that
413
+ * previously lived inside the VS Code linter class.
414
+ */
415
+ export function lintDocument(
416
+ doc: GherkinDocument,
417
+ lines: string[],
418
+ config: LintConfig = {},
419
+ ): DiagnosticEntry[] {
420
+ return [
421
+ ...RULES.flatMap((rule) => rule(doc, lines)),
422
+ ...checkTagAllowlist(doc, lines, config.allowedTags ?? []),
423
+ ...checkPhrasingRules(doc, lines, config.phrasingRules ?? []),
424
+ ];
425
+ }