@step-forge/step-forge 0.0.25-alpha.3 → 0.0.25-alpha.5

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.
@@ -1 +1 @@
1
- {"version":3,"file":"step-forge.cjs","names":["_","captureDefinitionSite"],"sources":["../../src/builderTypeUtils.ts","../../src/parsers.ts","../../src/utils.ts","../../src/common.ts","../../src/given.ts","../../src/when.ts","../../src/then.ts","../../src/init.ts","../../src/hooks.ts","../../src/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nexport type StepType = \"given\" | \"when\" | \"then\";\n\n/** A dependency declaration: each key of a phase's state marked required/optional. */\nexport type RequiredOrOptional<T> = {\n [K in keyof T]?: \"required\" | \"optional\";\n};\n\n/** The dependency map for a single phase, keyed by state property name. */\nexport type DepMap = Record<string, \"required\" | \"optional\">;\n\n/** The fully-resolved dependency declaration passed to `addStep` at runtime. */\nexport type FullDependencies = {\n given: DepMap;\n when: DepMap;\n then: DepMap;\n};\n\n/**\n * Narrows a phase's full state to only the keys named in a dependency map.\n * Optional dependencies widen to `| undefined`; keys not present in the state\n * are dropped. This is the shape a step function sees for `given`/`when`/`then`.\n */\nexport type Restrict<State, Deps extends RequiredOrOptional<State>> = {\n [K in keyof State as K extends keyof Deps\n ? K\n : never]: Deps[K] extends \"optional\" ? State[K] | undefined : State[K];\n};\n\nexport type GetFunctionArgs<T> = T extends (...args: infer A) => any\n ? A\n : never;\n\nexport const isString = (\n statement: string | ((...args: [...any]) => string)\n): statement is string => typeof statement === \"string\";\n","/**\n * A Parser is a typed cucumber-expression *parameter type*: it declares how a\n * value is recognised in a Gherkin step (`regexp`) and how the matched text is\n * turned into a TypeScript value (`parse`). The step expression uses `{name}`\n * as the placeholder.\n *\n * The engine folds each parser straight into the cucumber-expression matcher —\n * `parse` is the parameter type's transform, so coercion happens exactly once,\n * during matching (no second pass). This is also what lets a parser introduce a\n * brand-new placeholder like `{color}`: it is registered as a real parameter\n * type, so text that doesn't match `regexp` simply doesn't match the step.\n *\n * The four built-ins below reuse cucumber-expressions' own built-in parameter\n * types (`{int}`, `{float}`, `{string}`) — those names are already registered,\n * so the library performs the match + coercion and each parser's `regexp`/\n * `parse` serve to document intent and to drive TypeScript inference of the\n * variable type. `booleanParser` has no built-in equivalent, so it is a genuine\n * custom parameter type whose `parse` runs at match time.\n */\nexport type Parser<T> = {\n /** Parameter-type name; the step expression uses `{name}` as the placeholder. */\n name: string;\n /** How cucumber-expressions recognises the value in the step text. */\n regexp: RegExp | RegExp[];\n /** Transform the matched text into the typed value. */\n parse: (value: string) => T;\n};\n\n/** Matches a quoted string (`{string}`) and strips the surrounding quotes. */\nexport const stringParser: Parser<string> = {\n name: \"string\",\n regexp: [/\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\"/, /'([^'\\\\]*(\\\\.[^'\\\\]*)*)'/],\n parse: value => {\n const match = /^\"([\\s\\S]*)\"$/.exec(value) ?? /^'([\\s\\S]*)'$/.exec(value);\n return match ? match[1].replace(/\\\\([\"'])/g, \"$1\") : value;\n },\n};\n\n/** Matches an unquoted integer (`{int}`). */\nexport const intParser: Parser<number> = {\n name: \"int\",\n regexp: /-?\\d+/,\n parse: value => parseInt(value, 10),\n};\n\n/** Matches an unquoted floating point number (`{float}`). */\nexport const numberParser: Parser<number> = {\n name: \"float\",\n regexp: /-?\\d*\\.?\\d+/,\n parse: value => parseFloat(value),\n};\n\n/**\n * Matches an unquoted `true`/`false` word (`{boolean}`) and parses it to a\n * boolean. Unlike the others this is a genuine custom parameter type — cucumber\n * has no built-in `boolean` — so its `regexp`/`parse` are what the matcher uses.\n */\nexport const booleanParser: Parser<boolean> = {\n name: \"boolean\",\n regexp: /true|false/,\n parse: value => value === \"true\",\n};\n","import { MergeableWorld } from \"./world\";\n\nexport const requireFromGiven = <G>(\n keys: (keyof G)[],\n world: MergeableWorld<G, unknown, unknown>\n) => {\n keys.forEach(key => {\n if (!world.given[key]) {\n throw new Error(`Key ${String(key)} is required in given state`);\n }\n });\n return keys.reduce(\n (acc, key) => {\n return {\n ...acc,\n [key]: world.given[key],\n };\n },\n {} as { [key in keyof G]: G[key] }\n );\n};\nexport const requireFromWhen = <W>(\n keys: (keyof W)[],\n world: MergeableWorld<unknown, W, unknown>\n) => {\n keys.forEach(key => {\n if (!world.when[key]) {\n throw new Error(`Key ${String(key)} is required in when state`);\n }\n });\n return keys.reduce(\n (acc, key) => {\n return {\n ...acc,\n [key]: world.when[key],\n };\n },\n {} as { [key in keyof W]: W[key] }\n );\n};\nexport const requireFromThen = <T>(\n keys: (keyof T)[],\n world: MergeableWorld<unknown, unknown, T>\n) => {\n keys.forEach(key => {\n if (!world.then[key]) {\n throw new Error(`Key ${String(key)} is required in then state`);\n }\n });\n return keys.reduce(\n (acc, key) => {\n return {\n ...acc,\n [key]: world.then[key],\n };\n },\n {} as { [key in keyof T]: T[key] }\n );\n};\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport _ from \"lodash\";\n\nimport { DepMap, FullDependencies, StepType } from \"./builderTypeUtils\";\nimport { Parser, stringParser } from \"./parsers\";\nimport { globalRegistry } from \"./runtime/registry\";\nimport { captureDefinitionSite } from \"./sourceLocation\";\nimport { requireFromGiven, requireFromThen, requireFromWhen } from \"./utils\";\nimport { MergeableWorld } from \"./world\";\n\n/**\n * The runtime core of the builder chain. `addStep` is deliberately phase-agnostic:\n * the calling builder (given/when/then) has already computed the exact type of the\n * step function via its two type parameters:\n *\n * - `StepFnInput` — the `{ variables, given, when, then }` object the step receives,\n * with each phase already narrowed to its declared dependencies.\n * - `StepFnOutput` — the phase-appropriate return type (`Partial<State>`, or `void`).\n *\n * Everything else is plain runtime data (a statement function, the step type, the\n * dependency map, the parsers), so `addStep` carries no generics for them.\n */\nexport const addStep =\n <StepFnInput, StepFnOutput>(\n statement: (...args: any[]) => string,\n stepType: StepType,\n dependencies: FullDependencies = {\n given: {},\n when: {},\n then: {},\n },\n declaredParsers?: Parser<any>[]\n ) =>\n (stepFunction: (input: StepFnInput) => StepFnOutput) => {\n const {\n given: givenDependencies,\n when: whenDependencies,\n then: thenDependencies,\n } = dependencies;\n // Resolve the parsers up front, defaulting every variable to `stringParser`\n // (the `{string}` placeholder, value passed through unchanged) when none are\n // provided. Numeric/boolean values are opt-in via explicit parsers.\n const argCount = statement.length;\n const parsers =\n declaredParsers ?? Array.from({ length: argCount }, () => stringParser);\n const expression = statement(...parsers.map(parser => `{${parser.name}}`));\n // The fully-wired step body, decoupled from any test runner: takes an\n // explicit world plus the values captured from a Gherkin step, validates +\n // narrows dependencies, runs the user's step, and merges the result. The\n // captured values arrive already coerced — each parser is registered as the\n // cucumber-expression parameter type, so `parse` runs during matching, not\n // here.\n const execute = async (\n world: MergeableWorld<any, any, any>,\n capturedArgs: unknown[]\n ) => {\n const requiredKeys = (deps: DepMap) =>\n Object.entries(deps)\n .filter(([, value]) => value === \"required\")\n .map(([key]) => key);\n const narrowedGiven = {\n ..._.pick(world.given, Object.keys(givenDependencies)),\n ...requireFromGiven(requiredKeys(givenDependencies), world),\n };\n const narrowedWhen = {\n ..._.pick(world.when, Object.keys(whenDependencies)),\n ...requireFromWhen(requiredKeys(whenDependencies), world),\n };\n const narrowedThen = {\n ..._.pick(world.then, Object.keys(thenDependencies)),\n ...requireFromThen(requiredKeys(thenDependencies), world),\n };\n const result = await stepFunction({\n variables: capturedArgs,\n given: narrowedGiven,\n when: narrowedWhen,\n then: narrowedThen,\n } as StepFnInput);\n world[stepType].merge({\n ...(result as any),\n });\n };\n\n // Registration is the terminal action of the builder chain: calling\n // `.step(fn)` makes the step matchable and executable by the runtime. We\n // capture *this* call site (the user's `.step(...)` line) so reporters can\n // show where a failing step is defined, Cucumber-style.\n const source = captureDefinitionSite();\n globalRegistry.add({ stepType, expression, parsers, execute, source });\n\n return {\n statement,\n expression,\n dependencies,\n stepType,\n stepFunction,\n };\n };\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport {\n FullDependencies,\n GetFunctionArgs,\n isString,\n RequiredOrOptional,\n Restrict,\n StepType,\n} from \"./builderTypeUtils\";\nimport { addStep } from \"./common\";\nimport { Parser } from \"./parsers\";\n\nconst GIVEN: StepType = \"given\";\n\n// The `{ variables, given, when, then }` object a given step receives. Only\n// `given` is reachable — when/then are `never`, enforcing phase restriction.\n// `Given` is the state already narrowed to declared dependencies (`never` when\n// no dependencies were declared).\ntype GivenInput<Variables, Given> = {\n variables: Variables;\n given: Given;\n when: never;\n then: never;\n};\ntype GivenOutput<GivenState> =\n | Partial<GivenState>\n | Promise<Partial<GivenState>>;\n\nconst givenDependencies =\n <Variables, GivenState>(\n statement: (...args: any[]) => string,\n parsers?: Parser<any>[]\n ) =>\n <GivenDeps extends RequiredOrOptional<GivenState>>(dependencies: {\n given: GivenDeps;\n }) => ({\n step: addStep<\n GivenInput<Variables, Restrict<GivenState, GivenDeps>>,\n GivenOutput<GivenState>\n >(\n statement,\n GIVEN,\n { ...dependencies, when: {}, then: {} } as FullDependencies,\n parsers\n ),\n });\n\nconst givenParsers =\n <Variables extends any[], GivenState>(\n statement: (...args: any[]) => string\n ) =>\n <Parsers extends { [K in keyof Variables]: Parser<Variables[K]> }>(\n parsers: Parsers\n ) => ({\n dependencies: givenDependencies<Variables, GivenState>(\n statement,\n parsers as unknown as Parser<any>[]\n ),\n step: addStep<GivenInput<Variables, never>, GivenOutput<GivenState>>(\n statement,\n GIVEN,\n undefined,\n parsers as unknown as Parser<any>[]\n ),\n });\n\nconst givenStatement =\n <GivenState>() =>\n <Statement extends ((...args: [...any]) => string) | string>(\n statement: Statement\n ) => {\n const normalizedStatement: (...args: any[]) => string = isString(statement)\n ? () => statement\n : (statement as (...args: any[]) => string);\n\n type Variables = Statement extends string ? [] : GetFunctionArgs<Statement>;\n return {\n dependencies: givenDependencies<Variables, GivenState>(\n normalizedStatement\n ),\n parsers: givenParsers<Variables, GivenState>(normalizedStatement),\n step: addStep<GivenInput<Variables, never>, GivenOutput<GivenState>>(\n normalizedStatement,\n GIVEN\n ),\n };\n };\n\nexport const givenBuilder = <GivenState>() => ({\n statement: givenStatement<GivenState>(),\n});\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport {\n FullDependencies,\n GetFunctionArgs,\n isString,\n RequiredOrOptional,\n Restrict,\n StepType,\n} from \"./builderTypeUtils\";\nimport { addStep } from \"./common\";\nimport { Parser } from \"./parsers\";\n\nconst WHEN: StepType = \"when\";\n\n// The object a when step receives: `given` and `when` are reachable (narrowed to\n// declared dependencies, or `never` when none), `then` is always out of reach.\ntype WhenInput<Variables, Given, When> = {\n variables: Variables;\n given: Given;\n when: When;\n then: never;\n};\ntype WhenOutput<WhenState> = Partial<WhenState> | Promise<Partial<WhenState>>;\n\nconst whenDependencies =\n <Variables, GivenState, WhenState>(\n statement: (...args: any[]) => string,\n parsers?: Parser<any>[]\n ) =>\n <\n GivenDeps extends RequiredOrOptional<GivenState>,\n WhenDeps extends RequiredOrOptional<WhenState>,\n >(dependencies: {\n given?: GivenDeps;\n when?: WhenDeps;\n }) => ({\n step: addStep<\n WhenInput<\n Variables,\n Restrict<GivenState, GivenDeps>,\n Restrict<WhenState, WhenDeps>\n >,\n WhenOutput<WhenState>\n >(\n statement,\n WHEN,\n {\n given: dependencies.given ?? {},\n when: dependencies.when ?? {},\n then: {},\n } as FullDependencies,\n parsers\n ),\n });\n\nconst whenParsers =\n <Variables extends any[], GivenState, WhenState>(\n statement: (...args: any[]) => string\n ) =>\n <Parsers extends { [K in keyof Variables]: Parser<Variables[K]> }>(\n parsers: Parsers\n ) => ({\n dependencies: whenDependencies<Variables, GivenState, WhenState>(\n statement,\n parsers as unknown as Parser<any>[]\n ),\n step: addStep<WhenInput<Variables, never, never>, WhenOutput<WhenState>>(\n statement,\n WHEN,\n undefined,\n parsers as unknown as Parser<any>[]\n ),\n });\n\nconst whenStatement =\n <GivenState, WhenState>() =>\n <Statement extends ((...args: [...any]) => string) | string>(\n statement: Statement\n ) => {\n const normalizedStatement: (...args: any[]) => string = isString(statement)\n ? () => statement\n : (statement as (...args: any[]) => string);\n\n type Variables = Statement extends string ? [] : GetFunctionArgs<Statement>;\n return {\n dependencies: whenDependencies<Variables, GivenState, WhenState>(\n normalizedStatement\n ),\n parsers: whenParsers<Variables, GivenState, WhenState>(\n normalizedStatement\n ),\n step: addStep<WhenInput<Variables, never, never>, WhenOutput<WhenState>>(\n normalizedStatement,\n WHEN\n ),\n };\n };\n\nexport const whenBuilder = <GivenState, WhenState>() => ({\n statement: whenStatement<GivenState, WhenState>(),\n});\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport {\n FullDependencies,\n GetFunctionArgs,\n isString,\n RequiredOrOptional,\n Restrict,\n StepType,\n} from \"./builderTypeUtils\";\nimport { addStep } from \"./common\";\nimport { Parser } from \"./parsers\";\n\nconst THEN: StepType = \"then\";\n\n// The object a then step receives: all three phases are reachable (each narrowed\n// to declared dependencies, or `never` when none). Then steps may also return\n// nothing (assertion-only), hence the `void` in the output type.\ntype ThenInput<Variables, Given, When, Then> = {\n variables: Variables;\n given: Given;\n when: When;\n then: Then;\n};\ntype ThenOutput<ThenState> =\n | Partial<ThenState>\n | Promise<Partial<ThenState>>\n | void\n | Promise<void>;\n\nconst thenDependencies =\n <Variables, GivenState, WhenState, ThenState>(\n statement: (...args: any[]) => string,\n parsers?: Parser<any>[]\n ) =>\n <\n GivenDeps extends RequiredOrOptional<GivenState>,\n WhenDeps extends RequiredOrOptional<WhenState>,\n ThenDeps extends RequiredOrOptional<ThenState>,\n >(dependencies: {\n given?: GivenDeps;\n when?: WhenDeps;\n then?: ThenDeps;\n }) => ({\n step: addStep<\n ThenInput<\n Variables,\n Restrict<GivenState, GivenDeps>,\n Restrict<WhenState, WhenDeps>,\n Restrict<ThenState, ThenDeps>\n >,\n ThenOutput<ThenState>\n >(\n statement,\n THEN,\n {\n given: dependencies.given ?? {},\n when: dependencies.when ?? {},\n then: dependencies.then ?? {},\n } as FullDependencies,\n parsers\n ),\n });\n\nconst thenParsers =\n <Variables extends any[], GivenState, WhenState, ThenState>(\n statement: (...args: any[]) => string\n ) =>\n <Parsers extends { [K in keyof Variables]: Parser<Variables[K]> }>(\n parsers: Parsers\n ) => ({\n dependencies: thenDependencies<Variables, GivenState, WhenState, ThenState>(\n statement,\n parsers as unknown as Parser<any>[]\n ),\n step: addStep<\n ThenInput<Variables, never, never, never>,\n ThenOutput<ThenState>\n >(statement, THEN, undefined, parsers as unknown as Parser<any>[]),\n });\n\nconst thenStatement =\n <GivenState, WhenState, ThenState>() =>\n <Statement extends ((...args: [...any]) => string) | string>(\n statement: Statement\n ) => {\n const normalizedStatement: (...args: any[]) => string = isString(statement)\n ? () => statement\n : (statement as (...args: any[]) => string);\n\n type Variables = Statement extends string ? [] : GetFunctionArgs<Statement>;\n return {\n dependencies: thenDependencies<\n Variables,\n GivenState,\n WhenState,\n ThenState\n >(normalizedStatement),\n parsers: thenParsers<Variables, GivenState, WhenState, ThenState>(\n normalizedStatement\n ),\n step: addStep<\n ThenInput<Variables, never, never, never>,\n ThenOutput<ThenState>\n >(normalizedStatement, THEN),\n };\n };\n\nexport const thenBuilder = <GivenState, WhenState, ThenState>() => ({\n statement: thenStatement<GivenState, WhenState, ThenState>(),\n});\n","import { givenBuilder } from \"./given\";\nimport { thenBuilder } from \"./then\";\nimport { whenBuilder } from \"./when\";\n\nexport const createBuilders = <GivenState, WhenState, ThenState>() => {\n return {\n Given: givenBuilder<GivenState>().statement,\n When: whenBuilder<GivenState, WhenState>().statement,\n Then: thenBuilder<GivenState, WhenState, ThenState>().statement,\n };\n};\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n globalHookRegistry,\n PlainHookFn,\n ScenarioHookFn,\n ScenarioInfo,\n} from \"./runtime/hooks\";\nimport { MergeableWorld } from \"./world\";\n\n/**\n * Run before every scenario, with access to that scenario's fresh world. For\n * side effects only (reset a mock, seed an external system) — return values are\n * ignored; seed test *state* with given steps so the dependency graph stays the\n * single source of truth.\n */\nexport function beforeScenario<\n World extends MergeableWorld<any, any, any> = MergeableWorld<any, any, any>,\n>(\n fn: (context: {\n world: World;\n scenario: ScenarioInfo;\n }) => void | Promise<void>\n): void {\n globalHookRegistry.add({\n scope: \"scenario\",\n timing: \"before\",\n fn: fn as ScenarioHookFn,\n });\n}\n\n/**\n * Run after every scenario (even when a step failed), with access to that\n * scenario's world. Runs in reverse registration order so teardown unwinds\n * setup. For cleanup side effects only.\n */\nexport function afterScenario<\n World extends MergeableWorld<any, any, any> = MergeableWorld<any, any, any>,\n>(\n fn: (context: {\n world: World;\n scenario: ScenarioInfo;\n }) => void | Promise<void>\n): void {\n globalHookRegistry.add({\n scope: \"scenario\",\n timing: \"after\",\n fn: fn as ScenarioHookFn,\n });\n}\n\n/** Run once at the start of each feature file. No world exists at this boundary. */\nexport function beforeFeature(fn: PlainHookFn): void {\n globalHookRegistry.add({ scope: \"feature\", timing: \"before\", fn });\n}\n\n/** Run once at the end of each feature file (reverse registration order). */\nexport function afterFeature(fn: PlainHookFn): void {\n globalHookRegistry.add({ scope: \"feature\", timing: \"after\", fn });\n}\n\n/**\n * Run once before the entire run, ahead of any scenario (and before\n * concurrency starts). Multiple `beforeAll` hooks run **in parallel** with no\n * ordering between them — if a step of setup must precede another, sequence both\n * inside a single hook.\n */\nexport function beforeAll(fn: PlainHookFn): void {\n globalHookRegistry.add({ scope: \"global\", timing: \"before\", fn });\n}\n\n/**\n * Run once after the entire run, once every scenario is done. Multiple\n * `afterAll` hooks run **in parallel** with no ordering between them — sequence\n * dependent teardown inside a single hook.\n */\nexport function afterAll(fn: PlainHookFn): void {\n globalHookRegistry.add({ scope: \"global\", timing: \"after\", fn });\n}\n","import { givenBuilder } from \"./given\";\nimport { whenBuilder } from \"./when\";\nimport { thenBuilder } from \"./then\";\nimport { BasicWorld } from \"./world\";\nimport {\n stringParser,\n intParser,\n numberParser,\n booleanParser,\n} from \"./parsers\";\nimport type { Parser } from \"./parsers\";\nimport {\n analyze,\n extractStepDefinitions,\n parseFeatureFiles,\n parseFeatureContent,\n matchScenarioSteps,\n findMatchingDefinitions,\n defaultRules,\n} from \"./analyzer/index\";\nimport type {\n AnalyzerConfig,\n AnalyzeOptions,\n AnalysisRule,\n Diagnostic,\n StepDefinitionMeta,\n ParsedScenario,\n ParsedStep,\n MatchedStep,\n} from \"./analyzer/index\";\nimport { createBuilders } from \"./init\";\nimport {\n beforeScenario,\n afterScenario,\n beforeFeature,\n afterFeature,\n beforeAll,\n afterAll,\n} from \"./hooks\";\n\nexport {\n givenBuilder,\n whenBuilder,\n thenBuilder,\n BasicWorld,\n stringParser,\n intParser,\n numberParser,\n booleanParser,\n createBuilders,\n beforeScenario,\n afterScenario,\n beforeFeature,\n afterFeature,\n beforeAll,\n afterAll,\n};\n\nexport type { Parser };\nexport type {\n ScenarioInfo,\n PlainHookFn,\n ScenarioHookFn,\n} from \"./runtime/hooks\";\nexport type { StateFromDependencies } from \"./typeHelpers\";\n// Re-exported from the main entry so consumers can type their\n// `step-forge.config.ts` with a plain `@step-forge/step-forge` import.\nexport type { RunnerOptions } from \"./runtime/config\";\n\nexport const analyzer = {\n analyze,\n extractStepDefinitions,\n parseFeatureFiles,\n parseFeatureContent,\n matchScenarioSteps,\n findMatchingDefinitions,\n defaultRules,\n};\n\nexport type {\n AnalyzerConfig,\n AnalyzeOptions,\n AnalysisRule,\n Diagnostic,\n StepDefinitionMeta,\n ParsedScenario,\n ParsedStep,\n MatchedStep,\n};\n"],"mappings":";;;;;;;AAiCA,MAAa,YACX,cACwB,OAAO,cAAc;;;;ACN/C,MAAa,eAA+B;CAC1C,MAAM;CACN,QAAQ,CAAC,4BAA4B,0BAA0B;CAC/D,QAAO,UAAS;EACd,MAAM,QAAQ,gBAAgB,KAAK,KAAK,KAAK,gBAAgB,KAAK,KAAK;EACvE,OAAO,QAAQ,MAAM,EAAE,CAAC,QAAQ,aAAa,IAAI,IAAI;CACvD;AACF;;AAGA,MAAa,YAA4B;CACvC,MAAM;CACN,QAAQ;CACR,QAAO,UAAS,SAAS,O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D;CACpE,OAAO;EACL,OAAO,aAAyB,CAAC,CAAC;EAClC,MAAM,YAAmC,CAAC,CAAC;EAC3C,MAAM,YAA8C,CAAC,CAAC;CACxD;AACF;;;;;;;;;ACKA,SAAgB,eAGd,IAIM;CACN,cAAA,mBAAmB,IAAI;EACrB,OAAO;EACP,QAAQ;EACJ;CACN,CAAC;AACH;;;;;;AAOA,SAAgB,cAGd,IAIM;CACN,cAAA,mBAAmB,IAAI;EACrB,OAAO;EACP,QAAQ;EACJ;CACN,CAAC;AACH;;AAGA,SAAgB,cAAc,IAAuB;CACnD,cAAA,mBAAmB,IAAI;EAAE,OAAO;EAAW,QAAQ;EAAU;CAAG,CAAC;AACnE;;AAGA,SAAgB,aAAa,IAAuB;CAClD,cAAA,mBAAmB,IAAI;EAAE,OAAO;EAAW,QAAQ;EAAS;CAAG,CAAC;AAClE;;;;;;;AAQA,SAAgB,UAAU,IAAuB;CAC/C,cAAA,mBAAmB,IAAI;EAAE,OAAO;EAAU,QAAQ;EAAU;CAAG,CAAC;AAClE;;;;;;AAOA,SAAgB,SAAS,IAAuB;CAC9C,cAAA,mBAAmB,IAAI;EAAE,OAAO;EAAU,QAAQ;EAAS;CAAG,CAAC;AACjE;;;ACRA,MAAa,WAAW;CACtB,SAAA,iBAAA;CACA,wBAAA,iBAAA;CACA,mBAAA,sBAAA;CACA,qBAAA,sBAAA;CACA,oBAAA,iBAAA;CACA,yBAAA,iBAAA;CACA,cAAA,iBAAA;AACF"}
1
+ {"version":3,"file":"step-forge.cjs","names":["_","captureDefinitionSite","ts","globFiles","parseFeatureFiles"],"sources":["../../src/builderTypeUtils.ts","../../src/parsers.ts","../../src/utils.ts","../../src/common.ts","../../src/given.ts","../../src/when.ts","../../src/then.ts","../../src/analyzer/stepExtractor.ts","../../src/analyzer/stepMatcher.ts","../../src/analyzer/rules/ambiguousStepRule.ts","../../src/analyzer/rules/dependencyRule.ts","../../src/analyzer/rules/undefinedStepRule.ts","../../src/analyzer/rules/index.ts","../../src/analyzer/index.ts","../../src/init.ts","../../src/hooks.ts","../../src/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nexport type StepType = \"given\" | \"when\" | \"then\";\n\n/** A dependency declaration: each key of a phase's state marked required/optional. */\nexport type RequiredOrOptional<T> = {\n [K in keyof T]?: \"required\" | \"optional\";\n};\n\n/** The dependency map for a single phase, keyed by state property name. */\nexport type DepMap = Record<string, \"required\" | \"optional\">;\n\n/** The fully-resolved dependency declaration passed to `addStep` at runtime. */\nexport type FullDependencies = {\n given: DepMap;\n when: DepMap;\n then: DepMap;\n};\n\n/**\n * Narrows a phase's full state to only the keys named in a dependency map.\n * Optional dependencies widen to `| undefined`; keys not present in the state\n * are dropped. This is the shape a step function sees for `given`/`when`/`then`.\n */\nexport type Restrict<State, Deps extends RequiredOrOptional<State>> = {\n [\n K in keyof State as K extends keyof Deps ? K : never\n ]: Deps[K] extends \"optional\" ? State[K] | undefined : State[K];\n};\n\nexport type GetFunctionArgs<T> = T extends (...args: infer A) => any\n ? A\n : never;\n\nexport const isString = (\n statement: string | ((...args: [...any]) => string)\n): statement is string => typeof statement === \"string\";\n","/**\n * A Parser is a typed cucumber-expression *parameter type*: it declares how a\n * value is recognised in a Gherkin step (`regexp`) and how the matched text is\n * turned into a TypeScript value (`parse`). The step expression uses `{name}`\n * as the placeholder.\n *\n * The engine folds each parser straight into the cucumber-expression matcher —\n * `parse` is the parameter type's transform, so coercion happens exactly once,\n * during matching (no second pass). This is also what lets a parser introduce a\n * brand-new placeholder like `{color}`: it is registered as a real parameter\n * type, so text that doesn't match `regexp` simply doesn't match the step.\n *\n * The four built-ins below reuse cucumber-expressions' own built-in parameter\n * types (`{int}`, `{float}`, `{string}`) — those names are already registered,\n * so the library performs the match + coercion and each parser's `regexp`/\n * `parse` serve to document intent and to drive TypeScript inference of the\n * variable type. `booleanParser` has no built-in equivalent, so it is a genuine\n * custom parameter type whose `parse` runs at match time.\n */\nexport type Parser<T> = {\n /** Parameter-type name; the step expression uses `{name}` as the placeholder. */\n name: string;\n /** How cucumber-expressions recognises the value in the step text. */\n regexp: RegExp | RegExp[];\n /** Transform the matched text into the typed value. */\n parse: (value: string) => T;\n};\n\n/** Matches a quoted string (`{string}`) and strips the surrounding quotes. */\nexport const stringParser: Parser<string> = {\n name: \"string\",\n regexp: [/\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\"/, /'([^'\\\\]*(\\\\.[^'\\\\]*)*)'/],\n parse: value => {\n const match = /^\"([\\s\\S]*)\"$/.exec(value) ?? /^'([\\s\\S]*)'$/.exec(value);\n return match ? match[1].replace(/\\\\([\"'])/g, \"$1\") : value;\n },\n};\n\n/** Matches an unquoted integer (`{int}`). */\nexport const intParser: Parser<number> = {\n name: \"int\",\n regexp: /-?\\d+/,\n parse: value => parseInt(value, 10),\n};\n\n/** Matches an unquoted floating point number (`{float}`). */\nexport const numberParser: Parser<number> = {\n name: \"float\",\n regexp: /-?\\d*\\.?\\d+/,\n parse: value => parseFloat(value),\n};\n\n/**\n * Matches an unquoted `true`/`false` word (`{boolean}`) and parses it to a\n * boolean. Unlike the others this is a genuine custom parameter type — cucumber\n * has no built-in `boolean` — so its `regexp`/`parse` are what the matcher uses.\n */\nexport const booleanParser: Parser<boolean> = {\n name: \"boolean\",\n regexp: /true|false/,\n parse: value => value === \"true\",\n};\n","import { MergeableWorld } from \"./world\";\n\nexport const requireFromGiven = <G>(\n keys: (keyof G)[],\n world: MergeableWorld<G, unknown, unknown>\n) => {\n keys.forEach(key => {\n if (!world.given[key]) {\n throw new Error(`Key ${String(key)} is required in given state`);\n }\n });\n return keys.reduce(\n (acc, key) => {\n return {\n ...acc,\n [key]: world.given[key],\n };\n },\n {} as { [key in keyof G]: G[key] }\n );\n};\nexport const requireFromWhen = <W>(\n keys: (keyof W)[],\n world: MergeableWorld<unknown, W, unknown>\n) => {\n keys.forEach(key => {\n if (!world.when[key]) {\n throw new Error(`Key ${String(key)} is required in when state`);\n }\n });\n return keys.reduce(\n (acc, key) => {\n return {\n ...acc,\n [key]: world.when[key],\n };\n },\n {} as { [key in keyof W]: W[key] }\n );\n};\nexport const requireFromThen = <T>(\n keys: (keyof T)[],\n world: MergeableWorld<unknown, unknown, T>\n) => {\n keys.forEach(key => {\n if (!world.then[key]) {\n throw new Error(`Key ${String(key)} is required in then state`);\n }\n });\n return keys.reduce(\n (acc, key) => {\n return {\n ...acc,\n [key]: world.then[key],\n };\n },\n {} as { [key in keyof T]: T[key] }\n );\n};\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport _ from \"lodash\";\n\nimport { DepMap, FullDependencies, StepType } from \"./builderTypeUtils\";\nimport { Parser, stringParser } from \"./parsers\";\nimport { globalRegistry } from \"./runtime/registry\";\nimport { captureDefinitionSite } from \"./sourceLocation\";\nimport { requireFromGiven, requireFromThen, requireFromWhen } from \"./utils\";\nimport { MergeableWorld } from \"./world\";\n\n/**\n * The runtime core of the builder chain. `addStep` is deliberately phase-agnostic:\n * the calling builder (given/when/then) has already computed the exact type of the\n * step function via its two type parameters:\n *\n * - `StepFnInput` — the `{ variables, given, when, then }` object the step receives,\n * with each phase already narrowed to its declared dependencies.\n * - `StepFnOutput` — the phase-appropriate return type (`Partial<State>`, or `void`).\n *\n * Everything else is plain runtime data (a statement function, the step type, the\n * dependency map, the parsers), so `addStep` carries no generics for them.\n */\nexport const addStep =\n <StepFnInput, StepFnOutput>(\n statement: (...args: any[]) => string,\n stepType: StepType,\n dependencies: FullDependencies = {\n given: {},\n when: {},\n then: {},\n },\n declaredParsers?: Parser<any>[]\n ) =>\n (stepFunction: (input: StepFnInput) => StepFnOutput) => {\n const {\n given: givenDependencies,\n when: whenDependencies,\n then: thenDependencies,\n } = dependencies;\n // Resolve the parsers up front, defaulting every variable to `stringParser`\n // (the `{string}` placeholder, value passed through unchanged) when none are\n // provided. Numeric/boolean values are opt-in via explicit parsers.\n const argCount = statement.length;\n const parsers =\n declaredParsers ?? Array.from({ length: argCount }, () => stringParser);\n const expression = statement(...parsers.map(parser => `{${parser.name}}`));\n // The fully-wired step body, decoupled from any test runner: takes an\n // explicit world plus the values captured from a Gherkin step, validates +\n // narrows dependencies, runs the user's step, and merges the result. The\n // captured values arrive already coerced — each parser is registered as the\n // cucumber-expression parameter type, so `parse` runs during matching, not\n // here.\n const execute = async (\n world: MergeableWorld<any, any, any>,\n capturedArgs: unknown[]\n ) => {\n const requiredKeys = (deps: DepMap) =>\n Object.entries(deps)\n .filter(([, value]) => value === \"required\")\n .map(([key]) => key);\n const narrowedGiven = {\n ..._.pick(world.given, Object.keys(givenDependencies)),\n ...requireFromGiven(requiredKeys(givenDependencies), world),\n };\n const narrowedWhen = {\n ..._.pick(world.when, Object.keys(whenDependencies)),\n ...requireFromWhen(requiredKeys(whenDependencies), world),\n };\n const narrowedThen = {\n ..._.pick(world.then, Object.keys(thenDependencies)),\n ...requireFromThen(requiredKeys(thenDependencies), world),\n };\n const result = await stepFunction({\n variables: capturedArgs,\n given: narrowedGiven,\n when: narrowedWhen,\n then: narrowedThen,\n } as StepFnInput);\n world[stepType].merge({\n ...(result as any),\n });\n };\n\n // Registration is the terminal action of the builder chain: calling\n // `.step(fn)` makes the step matchable and executable by the runtime. We\n // capture *this* call site (the user's `.step(...)` line) so reporters can\n // show where a failing step is defined, Cucumber-style.\n const source = captureDefinitionSite();\n globalRegistry.add({ stepType, expression, parsers, execute, source });\n\n return {\n statement,\n expression,\n dependencies,\n stepType,\n stepFunction,\n };\n };\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport {\n FullDependencies,\n GetFunctionArgs,\n isString,\n RequiredOrOptional,\n Restrict,\n StepType,\n} from \"./builderTypeUtils\";\nimport { addStep } from \"./common\";\nimport { Parser } from \"./parsers\";\n\nconst GIVEN: StepType = \"given\";\n\n// The `{ variables, given, when, then }` object a given step receives. Only\n// `given` is reachable — when/then are `never`, enforcing phase restriction.\n// `Given` is the state already narrowed to declared dependencies (`never` when\n// no dependencies were declared).\ntype GivenInput<Variables, Given> = {\n variables: Variables;\n given: Given;\n when: never;\n then: never;\n};\ntype GivenOutput<GivenState> =\n Partial<GivenState> | Promise<Partial<GivenState>>;\n\nconst givenDependencies =\n <Variables, GivenState>(\n statement: (...args: any[]) => string,\n parsers?: Parser<any>[]\n ) =>\n <GivenDeps extends RequiredOrOptional<GivenState>>(dependencies: {\n given: GivenDeps;\n }) => ({\n step: addStep<\n GivenInput<Variables, Restrict<GivenState, GivenDeps>>,\n GivenOutput<GivenState>\n >(\n statement,\n GIVEN,\n { ...dependencies, when: {}, then: {} } as FullDependencies,\n parsers\n ),\n });\n\nconst givenParsers =\n <Variables extends any[], GivenState>(\n statement: (...args: any[]) => string\n ) =>\n <Parsers extends { [K in keyof Variables]: Parser<Variables[K]> }>(\n parsers: Parsers\n ) => ({\n dependencies: givenDependencies<Variables, GivenState>(\n statement,\n parsers as unknown as Parser<any>[]\n ),\n step: addStep<GivenInput<Variables, never>, GivenOutput<GivenState>>(\n statement,\n GIVEN,\n undefined,\n parsers as unknown as Parser<any>[]\n ),\n });\n\nconst givenStatement =\n <GivenState>() =>\n <Statement extends ((...args: [...any]) => string) | string>(\n statement: Statement\n ) => {\n const normalizedStatement: (...args: any[]) => string = isString(statement)\n ? () => statement\n : (statement as (...args: any[]) => string);\n\n type Variables = Statement extends string ? [] : GetFunctionArgs<Statement>;\n return {\n dependencies: givenDependencies<Variables, GivenState>(\n normalizedStatement\n ),\n parsers: givenParsers<Variables, GivenState>(normalizedStatement),\n step: addStep<GivenInput<Variables, never>, GivenOutput<GivenState>>(\n normalizedStatement,\n GIVEN\n ),\n };\n };\n\nexport const givenBuilder = <GivenState>() => ({\n statement: givenStatement<GivenState>(),\n});\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport {\n FullDependencies,\n GetFunctionArgs,\n isString,\n RequiredOrOptional,\n Restrict,\n StepType,\n} from \"./builderTypeUtils\";\nimport { addStep } from \"./common\";\nimport { Parser } from \"./parsers\";\n\nconst WHEN: StepType = \"when\";\n\n// The object a when step receives: `given` and `when` are reachable (narrowed to\n// declared dependencies, or `never` when none), `then` is always out of reach.\ntype WhenInput<Variables, Given, When> = {\n variables: Variables;\n given: Given;\n when: When;\n then: never;\n};\ntype WhenOutput<WhenState> = Partial<WhenState> | Promise<Partial<WhenState>>;\n\nconst whenDependencies =\n <Variables, GivenState, WhenState>(\n statement: (...args: any[]) => string,\n parsers?: Parser<any>[]\n ) =>\n <\n GivenDeps extends RequiredOrOptional<GivenState>,\n WhenDeps extends RequiredOrOptional<WhenState>,\n >(dependencies: {\n given?: GivenDeps;\n when?: WhenDeps;\n }) => ({\n step: addStep<\n WhenInput<\n Variables,\n Restrict<GivenState, GivenDeps>,\n Restrict<WhenState, WhenDeps>\n >,\n WhenOutput<WhenState>\n >(\n statement,\n WHEN,\n {\n given: dependencies.given ?? {},\n when: dependencies.when ?? {},\n then: {},\n } as FullDependencies,\n parsers\n ),\n });\n\nconst whenParsers =\n <Variables extends any[], GivenState, WhenState>(\n statement: (...args: any[]) => string\n ) =>\n <Parsers extends { [K in keyof Variables]: Parser<Variables[K]> }>(\n parsers: Parsers\n ) => ({\n dependencies: whenDependencies<Variables, GivenState, WhenState>(\n statement,\n parsers as unknown as Parser<any>[]\n ),\n step: addStep<WhenInput<Variables, never, never>, WhenOutput<WhenState>>(\n statement,\n WHEN,\n undefined,\n parsers as unknown as Parser<any>[]\n ),\n });\n\nconst whenStatement =\n <GivenState, WhenState>() =>\n <Statement extends ((...args: [...any]) => string) | string>(\n statement: Statement\n ) => {\n const normalizedStatement: (...args: any[]) => string = isString(statement)\n ? () => statement\n : (statement as (...args: any[]) => string);\n\n type Variables = Statement extends string ? [] : GetFunctionArgs<Statement>;\n return {\n dependencies: whenDependencies<Variables, GivenState, WhenState>(\n normalizedStatement\n ),\n parsers: whenParsers<Variables, GivenState, WhenState>(\n normalizedStatement\n ),\n step: addStep<WhenInput<Variables, never, never>, WhenOutput<WhenState>>(\n normalizedStatement,\n WHEN\n ),\n };\n };\n\nexport const whenBuilder = <GivenState, WhenState>() => ({\n statement: whenStatement<GivenState, WhenState>(),\n});\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport {\n FullDependencies,\n GetFunctionArgs,\n isString,\n RequiredOrOptional,\n Restrict,\n StepType,\n} from \"./builderTypeUtils\";\nimport { addStep } from \"./common\";\nimport { Parser } from \"./parsers\";\n\nconst THEN: StepType = \"then\";\n\n// The object a then step receives: all three phases are reachable (each narrowed\n// to declared dependencies, or `never` when none). Then steps may also return\n// nothing (assertion-only), hence the `void` in the output type.\ntype ThenInput<Variables, Given, When, Then> = {\n variables: Variables;\n given: Given;\n when: When;\n then: Then;\n};\ntype ThenOutput<ThenState> =\n Partial<ThenState> | Promise<Partial<ThenState>> | void | Promise<void>;\n\nconst thenDependencies =\n <Variables, GivenState, WhenState, ThenState>(\n statement: (...args: any[]) => string,\n parsers?: Parser<any>[]\n ) =>\n <\n GivenDeps extends RequiredOrOptional<GivenState>,\n WhenDeps extends RequiredOrOptional<WhenState>,\n ThenDeps extends RequiredOrOptional<ThenState>,\n >(dependencies: {\n given?: GivenDeps;\n when?: WhenDeps;\n then?: ThenDeps;\n }) => ({\n step: addStep<\n ThenInput<\n Variables,\n Restrict<GivenState, GivenDeps>,\n Restrict<WhenState, WhenDeps>,\n Restrict<ThenState, ThenDeps>\n >,\n ThenOutput<ThenState>\n >(\n statement,\n THEN,\n {\n given: dependencies.given ?? {},\n when: dependencies.when ?? {},\n then: dependencies.then ?? {},\n } as FullDependencies,\n parsers\n ),\n });\n\nconst thenParsers =\n <Variables extends any[], GivenState, WhenState, ThenState>(\n statement: (...args: any[]) => string\n ) =>\n <Parsers extends { [K in keyof Variables]: Parser<Variables[K]> }>(\n parsers: Parsers\n ) => ({\n dependencies: thenDependencies<Variables, GivenState, WhenState, ThenState>(\n statement,\n parsers as unknown as Parser<any>[]\n ),\n step: addStep<\n ThenInput<Variables, never, never, never>,\n ThenOutput<ThenState>\n >(statement, THEN, undefined, parsers as unknown as Parser<any>[]),\n });\n\nconst thenStatement =\n <GivenState, WhenState, ThenState>() =>\n <Statement extends ((...args: [...any]) => string) | string>(\n statement: Statement\n ) => {\n const normalizedStatement: (...args: any[]) => string = isString(statement)\n ? () => statement\n : (statement as (...args: any[]) => string);\n\n type Variables = Statement extends string ? [] : GetFunctionArgs<Statement>;\n return {\n dependencies: thenDependencies<\n Variables,\n GivenState,\n WhenState,\n ThenState\n >(normalizedStatement),\n parsers: thenParsers<Variables, GivenState, WhenState, ThenState>(\n normalizedStatement\n ),\n step: addStep<\n ThenInput<Variables, never, never, never>,\n ThenOutput<ThenState>\n >(normalizedStatement, THEN),\n };\n };\n\nexport const thenBuilder = <GivenState, WhenState, ThenState>() => ({\n statement: thenStatement<GivenState, WhenState, ThenState>(),\n});\n","import ts from \"typescript\";\nimport { StepDefinitionMeta } from \"./types.js\";\n\ntype StepType = \"given\" | \"when\" | \"then\";\n\nconst BUILDER_NAMES: Record<string, StepType> = {\n givenBuilder: \"given\",\n whenBuilder: \"when\",\n thenBuilder: \"then\",\n};\n\n/**\n * Threaded through the AST walk. `checker` is `null` on the parse-only fast\n * path; a step that genuinely needs type information sets `needsChecker`, which\n * triggers a one-time retry with a real type-checked `Program`.\n */\ninterface ExtractCtx {\n checker: ts.TypeChecker | null;\n needsChecker: boolean;\n}\n\nexport function extractStepDefinitions(\n filePaths: string[],\n tsConfigPath?: string\n): StepDefinitionMeta[] {\n // Fast path: parse each file with `createSourceFile` (tokenize + parse only,\n // no type resolution — ~1ms/file) and walk the AST. Building a full\n // type-checked `Program` loads `lib.*.d.ts` and resolves every import (~150ms)\n // and is only needed for two uncommon shapes: a `.step()` whose return isn't a\n // plain object literal, or the re-exported-builder pattern. Those set\n // `needsChecker`, and we retry once with a real Program below.\n const sources = filePaths\n .map(parseSourceFile)\n .filter((s): s is ts.SourceFile => s !== null);\n const fast = extractWithSources(sources, null);\n if (!fast.needsChecker) return fast.results;\n\n // Slow path: some step needs type information. Build the program once and\n // re-extract from *its* source files — the checker only understands nodes it\n // bound itself, so the parse-only ASTs above can't be reused here.\n const program = ts.createProgram(\n filePaths,\n resolveCompilerOptions(tsConfigPath)\n );\n const checker = program.getTypeChecker();\n const checkedSources = filePaths\n .map(fp => program.getSourceFile(fp))\n .filter((s): s is ts.SourceFile => s !== undefined);\n return extractWithSources(checkedSources, checker).results;\n}\n\n/** Parse a single file into an AST with no type resolution. */\nfunction parseSourceFile(filePath: string): ts.SourceFile | null {\n const text = ts.sys.readFile(filePath);\n if (text === undefined) return null;\n const scriptKind = filePath.endsWith(\".tsx\")\n ? ts.ScriptKind.TSX\n : ts.ScriptKind.TS;\n // setParentNodes: true — the extractor relies on `.getText()`/`.getStart()`,\n // which walk parent pointers up to the SourceFile.\n return ts.createSourceFile(\n filePath,\n text,\n ts.ScriptTarget.ESNext,\n true,\n scriptKind\n );\n}\n\n/** Resolve compiler options from tsconfig (fallback to sane defaults). */\nfunction resolveCompilerOptions(tsConfigPath?: string): ts.CompilerOptions {\n const configPath =\n tsConfigPath ?? ts.findConfigFile(process.cwd(), ts.sys.fileExists);\n let compilerOptions: ts.CompilerOptions = {\n target: ts.ScriptTarget.ESNext,\n module: ts.ModuleKind.ESNext,\n moduleResolution: ts.ModuleResolutionKind.Node10,\n strict: true,\n esModuleInterop: true,\n };\n\n if (configPath) {\n const configFile = ts.readConfigFile(configPath, ts.sys.readFile);\n if (!configFile.error) {\n const parsed = ts.parseJsonConfigFileContent(\n configFile.config,\n ts.sys,\n configPath.replace(/[/\\\\][^/\\\\]+$/, \"\")\n );\n compilerOptions = parsed.options;\n }\n }\n\n // Ensure noEmit so we don't write files\n compilerOptions.noEmit = true;\n return compilerOptions;\n}\n\nfunction extractWithSources(\n sources: ts.SourceFile[],\n checker: ts.TypeChecker | null\n): { results: StepDefinitionMeta[]; needsChecker: boolean } {\n const ctx: ExtractCtx = { checker, needsChecker: false };\n const results: StepDefinitionMeta[] = [];\n for (const sourceFile of sources) {\n results.push(...extractFromSourceFile(sourceFile, ctx));\n }\n return { results, needsChecker: ctx.needsChecker };\n}\n\nfunction extractFromSourceFile(\n sourceFile: ts.SourceFile,\n ctx: ExtractCtx\n): StepDefinitionMeta[] {\n const results: StepDefinitionMeta[] = [];\n\n function visit(node: ts.Node) {\n // The chain now terminates at `.step(...)`, which is the registration\n // point (there is no `.register()` anymore).\n if (\n ts.isCallExpression(node) &&\n ts.isPropertyAccessExpression(node.expression) &&\n node.expression.name.text === \"step\"\n ) {\n const meta = extractFromRegisterCall(node, sourceFile, ctx);\n if (meta) {\n results.push(meta);\n }\n }\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return results;\n}\n\nfunction extractFromRegisterCall(\n registerCall: ts.CallExpression,\n sourceFile: ts.SourceFile,\n ctx: ExtractCtx\n): StepDefinitionMeta | null {\n // Walk backwards through the method chain to find all parts\n // Pattern: builder().statement(...).dependencies?(...).step(...).register()\n // Or: Variable(\"...\").dependencies?(...).step(...).register()\n\n const chain = collectCallChain(registerCall);\n\n let stepType: StepType | null = null;\n let expression: string | null = null;\n let dependencies: StepDefinitionMeta[\"dependencies\"] = {\n given: {},\n when: {},\n then: {},\n };\n let produces: string[] = [];\n\n for (const link of chain) {\n const name = getCallName(link);\n if (!name) continue;\n\n if (name === \"register\") {\n // Already at register, continue\n continue;\n }\n\n if (name === \"step\") {\n produces = extractProducedKeys(link, ctx);\n continue;\n }\n\n if (name === \"dependencies\") {\n dependencies = extractDependencies(link);\n continue;\n }\n\n if (name === \"statement\") {\n expression = extractExpression(link);\n // Try to find the builder type by continuing up the chain\n continue;\n }\n\n // Check if this is a builder call like givenBuilder()\n if (BUILDER_NAMES[name]) {\n stepType = BUILDER_NAMES[name];\n continue;\n }\n }\n\n // If we didn't find the builder or expression in the chain, try the \"re-exported\" pattern:\n // const Given = givenBuilder<T>().statement;\n // Given(\"foo\").step(...).register()\n if (!stepType || !expression) {\n const reExport = resolveReExportedCall(chain, ctx);\n if (reExport) {\n if (!stepType) stepType = reExport.stepType;\n if (!expression) expression = reExport.expression;\n }\n }\n\n if (!stepType || !expression) {\n return null;\n }\n\n const line =\n sourceFile.getLineAndCharacterOfPosition(registerCall.getStart()).line + 1;\n\n return {\n stepType,\n expression,\n dependencies,\n produces,\n sourceFile: sourceFile.fileName,\n line,\n };\n}\n\n/**\n * Collect all call expressions in the method chain, from register() back to the origin.\n */\nfunction collectCallChain(call: ts.CallExpression): ts.CallExpression[] {\n const chain: ts.CallExpression[] = [call];\n let current: ts.Expression = call.expression;\n\n // Walk through PropertyAccessExpression to find the next call\n if (ts.isPropertyAccessExpression(current)) {\n current = current.expression;\n }\n\n while (ts.isCallExpression(current)) {\n chain.push(current);\n current = current.expression;\n if (ts.isPropertyAccessExpression(current)) {\n current = current.expression;\n }\n }\n\n return chain;\n}\n\nfunction getCallName(call: ts.CallExpression): string | null {\n const expr = call.expression;\n\n // .method() pattern\n if (ts.isPropertyAccessExpression(expr)) {\n return expr.name.text;\n }\n\n // direct call: functionName()\n if (ts.isIdentifier(expr)) {\n return expr.text;\n }\n\n return null;\n}\n\nfunction extractExpression(statementCall: ts.CallExpression): string | null {\n const arg = statementCall.arguments[0];\n if (!arg) return null;\n\n // String literal: .statement(\"a user\")\n if (ts.isStringLiteral(arg)) {\n return arg.text;\n }\n\n // Arrow function with template literal: .statement((name: string) => `a user named ${name}`)\n if (ts.isArrowFunction(arg)) {\n return extractExpressionFromArrowFunction(arg);\n }\n\n return null;\n}\n\nfunction extractExpressionFromArrowFunction(\n fn: ts.ArrowFunction\n): string | null {\n const params = fn.parameters.map(p => p.name.getText());\n\n // The body should be a template expression or string literal\n let body = fn.body;\n\n // If wrapped in a block with a return, unwrap\n if (ts.isBlock(body)) {\n const returnStmt = body.statements.find(ts.isReturnStatement);\n if (returnStmt?.expression) {\n body = returnStmt.expression;\n } else {\n return null;\n }\n }\n\n if (ts.isTemplateExpression(body)) {\n return reconstructExpressionFromTemplate(body, params);\n }\n\n if (ts.isNoSubstitutionTemplateLiteral(body)) {\n return body.text;\n }\n\n return null;\n}\n\nfunction reconstructExpressionFromTemplate(\n template: ts.TemplateExpression,\n paramNames: string[]\n): string {\n let result = template.head.text;\n\n for (const span of template.templateSpans) {\n if (\n ts.isIdentifier(span.expression) &&\n paramNames.includes(span.expression.text)\n ) {\n result += \"{string}\";\n } else {\n // Non-parameter expression, use {string} as fallback\n result += \"{string}\";\n }\n result += span.literal.text;\n }\n\n return result;\n}\n\nfunction extractDependencies(\n depsCall: ts.CallExpression\n): StepDefinitionMeta[\"dependencies\"] {\n const deps: StepDefinitionMeta[\"dependencies\"] = {\n given: {},\n when: {},\n then: {},\n };\n\n const arg = depsCall.arguments[0];\n if (!arg || !ts.isObjectLiteralExpression(arg)) return deps;\n\n for (const prop of arg.properties) {\n if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) continue;\n\n const phase = prop.name.text as \"given\" | \"when\" | \"then\";\n if (!deps[phase]) continue;\n\n if (ts.isObjectLiteralExpression(prop.initializer)) {\n for (const innerProp of prop.initializer.properties) {\n if (\n ts.isPropertyAssignment(innerProp) &&\n ts.isIdentifier(innerProp.name) &&\n ts.isStringLiteral(innerProp.initializer)\n ) {\n const val = innerProp.initializer.text;\n if (val === \"required\" || val === \"optional\") {\n deps[phase][innerProp.name.text] = val;\n }\n }\n }\n }\n }\n\n return deps;\n}\n\nfunction extractProducedKeys(\n stepCall: ts.CallExpression,\n ctx: ExtractCtx\n): string[] {\n const callback = stepCall.arguments[0];\n if (!callback) return [];\n\n // Try to get the return type of the callback by analyzing its body\n if (ts.isArrowFunction(callback) || ts.isFunctionExpression(callback)) {\n return extractProducedKeysFromCallback(callback, ctx);\n }\n\n return [];\n}\n\nfunction extractProducedKeysFromCallback(\n callback: ts.ArrowFunction | ts.FunctionExpression,\n ctx: ExtractCtx\n): string[] {\n const body = callback.body;\n\n // Concise arrow: () => ({ key: value })\n if (!ts.isBlock(body)) {\n return extractKeysFromExpression(body, ctx);\n }\n\n // Block body: look at return statements\n const keys = new Set<string>();\n function visitReturn(node: ts.Node) {\n if (ts.isReturnStatement(node) && node.expression) {\n for (const key of extractKeysFromExpression(node.expression, ctx)) {\n keys.add(key);\n }\n }\n ts.forEachChild(node, visitReturn);\n }\n visitReturn(body);\n return [...keys];\n}\n\nfunction extractKeysFromExpression(\n expr: ts.Expression,\n ctx: ExtractCtx\n): string[] {\n // Unwrap parenthesized expressions\n while (ts.isParenthesizedExpression(expr)) {\n expr = expr.expression;\n }\n\n // Object literal: { user: ..., token: ... }\n if (ts.isObjectLiteralExpression(expr)) {\n return expr.properties\n .filter(\n (p): p is ts.PropertyAssignment | ts.ShorthandPropertyAssignment =>\n ts.isPropertyAssignment(p) || ts.isShorthandPropertyAssignment(p)\n )\n .map(p => p.name.getText())\n .filter(Boolean);\n }\n\n // Non-literal return (a variable, a spread-only object, a function call): the\n // keys can only come from the type checker. On the parse-only pass we have\n // none — flag it so the caller retries with a real Program.\n if (!ctx.checker) {\n ctx.needsChecker = true;\n return [];\n }\n try {\n const type = ctx.checker.getTypeAtLocation(expr);\n return type\n .getProperties()\n .map(p => p.name)\n .filter(n => n !== \"merge\");\n } catch {\n return [];\n }\n}\n\ninterface ReExportResult {\n stepType: StepType;\n expression: string | null;\n}\n\nfunction resolveReExportedCall(\n chain: ts.CallExpression[],\n ctx: ExtractCtx\n): ReExportResult | null {\n // Look for the pattern: Variable(\"...\")... where Variable was assigned from builderType().statement\n // The last call in the chain (furthest from register) should be the variable call\n\n const lastCall = chain[chain.length - 1];\n if (!lastCall) return null;\n\n const expr = lastCall.expression;\n\n // If it's an identifier (like \"Given\", \"When\", \"Then\"), trace its declaration\n let identifier: ts.Identifier | null = null;\n if (ts.isIdentifier(expr)) {\n identifier = expr;\n } else if (\n ts.isPropertyAccessExpression(expr) &&\n ts.isIdentifier(expr.expression)\n ) {\n identifier = expr.expression;\n }\n\n if (!identifier) return null;\n\n // Tracing the re-exported builder's declaration needs symbol resolution,\n // which only a real Program provides. Flag for the checked retry.\n if (!ctx.checker) {\n ctx.needsChecker = true;\n return null;\n }\n\n const symbol = ctx.checker.getSymbolAtLocation(identifier);\n if (!symbol) return null;\n\n const decl = symbol.valueDeclaration;\n if (!decl || !ts.isVariableDeclaration(decl) || !decl.initializer)\n return null;\n\n // Check if initializer is builderType<T>().statement\n const init = decl.initializer;\n\n // Pattern: givenBuilder<T>().statement (PropertyAccessExpression)\n if (ts.isPropertyAccessExpression(init) && init.name.text === \"statement\") {\n const callExpr = init.expression;\n if (ts.isCallExpression(callExpr)) {\n const callee = callExpr.expression;\n if (ts.isIdentifier(callee) && BUILDER_NAMES[callee.text]) {\n // The lastCall IS the statement call — extract expression from it\n const expression = extractExpression(lastCall);\n return {\n stepType: BUILDER_NAMES[callee.text],\n expression,\n };\n }\n }\n }\n\n return null;\n}\n","import { MatchedStep, ParsedScenario, StepDefinitionMeta } from \"./types.js\";\n\ninterface CompiledPattern {\n regex: RegExp;\n definition: StepDefinitionMeta;\n}\n\nfunction compileDefinitions(\n definitions: StepDefinitionMeta[]\n): CompiledPattern[] {\n const compiled: CompiledPattern[] = [];\n for (const def of definitions) {\n try {\n // Replace {paramType} placeholders with (.+) to match any value,\n // regardless of which parser placeholder ({string}, {int}, ...) the\n // step definition declared.\n const placeholder = \"###PLACEHOLDER###\";\n const regexStr = def.expression\n .replace(/\\{[^}]+\\}/g, placeholder)\n .replace(/[.*+?^$()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(new RegExp(placeholder, \"g\"), \"(.+)\");\n compiled.push({\n regex: new RegExp(`^${regexStr}$`, \"i\"),\n definition: def,\n });\n } catch {\n // Skip definitions with invalid expressions\n }\n }\n return compiled;\n}\n\nexport function matchScenarioSteps(\n scenario: ParsedScenario,\n definitions: StepDefinitionMeta[]\n): MatchedStep[] {\n const compiled = compileDefinitions(definitions);\n\n return scenario.steps.map(step => {\n const matches = findMatches(step.text, step.effectiveKeyword, compiled);\n return {\n ...step,\n definitions: matches,\n };\n });\n}\n\nexport function findMatchingDefinitions(\n text: string,\n effectiveKeyword: \"Given\" | \"When\" | \"Then\",\n definitions: StepDefinitionMeta[]\n): StepDefinitionMeta[] {\n const compiled = compileDefinitions(definitions);\n return findMatches(text, effectiveKeyword, compiled);\n}\n\nfunction findMatches(\n text: string,\n effectiveKeyword: \"Given\" | \"When\" | \"Then\",\n compiled: CompiledPattern[]\n): StepDefinitionMeta[] {\n const keywordToStepType: Record<string, string> = {\n Given: \"given\",\n When: \"when\",\n Then: \"then\",\n };\n const expectedStepType = keywordToStepType[effectiveKeyword];\n\n // First try to match with the correct step type\n const typedMatches: StepDefinitionMeta[] = [];\n for (const { regex, definition } of compiled) {\n if (definition.stepType !== expectedStepType) continue;\n if (regex.test(text)) typedMatches.push(definition);\n }\n\n if (typedMatches.length > 0) return typedMatches;\n\n // Fallback: match any step type\n const fallbackMatches: StepDefinitionMeta[] = [];\n for (const { regex, definition } of compiled) {\n if (regex.test(text)) fallbackMatches.push(definition);\n }\n\n return fallbackMatches;\n}\n","import {\n AnalysisRule,\n Diagnostic,\n MatchedStep,\n ParsedScenario,\n} from \"../types.js\";\n\nexport const ambiguousStepRule: AnalysisRule = {\n name: \"ambiguous-step\",\n\n check(scenario: ParsedScenario, matchedSteps: MatchedStep[]): Diagnostic[] {\n return matchedSteps\n .filter(step => step.definitions.length > 1)\n .map(step => {\n const locations = step.definitions\n .map(d => `${d.sourceFile}:${d.line}`)\n .join(\", \");\n return {\n file: scenario.file,\n range: {\n startLine: step.line,\n startColumn: step.column,\n endLine: step.line,\n endColumn: step.column + step.text.length,\n },\n severity: \"error\" as const,\n message: `Step \"${step.text}\" matches multiple step definitions: ${locations}`,\n rule: \"ambiguous-step\",\n source: \"step-forge\" as const,\n };\n });\n },\n};\n","import {\n AnalysisRule,\n Diagnostic,\n MatchedStep,\n ParsedScenario,\n} from \"../types.js\";\n\nexport const dependencyRule: AnalysisRule = {\n name: \"dependency-check\",\n\n check(scenario: ParsedScenario, matchedSteps: MatchedStep[]): Diagnostic[] {\n const diagnostics: Diagnostic[] = [];\n const produced = {\n given: new Set<string>(),\n when: new Set<string>(),\n then: new Set<string>(),\n };\n\n for (const step of matchedSteps) {\n if (step.definitions.length !== 1) continue;\n\n const { dependencies, produces, stepType } = step.definitions[0];\n\n // Collect all missing required dependencies for this step\n const missing: Record<string, string[]> = {};\n for (const phase of [\"given\", \"when\", \"then\"] as const) {\n for (const [key, requirement] of Object.entries(dependencies[phase])) {\n if (requirement === \"required\" && !produced[phase].has(key)) {\n if (!missing[phase]) {\n missing[phase] = [];\n }\n missing[phase].push(key);\n }\n }\n }\n\n if (Object.keys(missing).length > 0) {\n const lines = Object.entries(missing).map(\n ([phase, keys]) =>\n `${phase.charAt(0).toUpperCase() + phase.slice(1)}: ${keys.map(k => `${phase}.${k}`).join(\", \")}`\n );\n const message = \"Missing required dependencies:\\n\" + lines.join(\"\\n\");\n\n diagnostics.push({\n file: scenario.file,\n range: {\n startLine: step.line,\n startColumn: step.column,\n endLine: step.line,\n endColumn: step.column + step.text.length,\n },\n severity: \"error\",\n message,\n rule: \"dependency-check\",\n source: \"step-forge\",\n });\n }\n\n // Add produced keys for this step\n for (const key of produces) {\n produced[stepType].add(key);\n }\n }\n\n return diagnostics;\n },\n};\n","import {\n AnalysisRule,\n Diagnostic,\n MatchedStep,\n ParsedScenario,\n} from \"../types.js\";\n\nexport const undefinedStepRule: AnalysisRule = {\n name: \"undefined-step\",\n\n check(scenario: ParsedScenario, matchedSteps: MatchedStep[]): Diagnostic[] {\n return matchedSteps\n .filter(step => step.definitions.length === 0)\n .map(step => ({\n file: scenario.file,\n range: {\n startLine: step.line,\n startColumn: step.column,\n endLine: step.line,\n endColumn: step.column + step.text.length,\n },\n severity: \"error\" as const,\n message: `Step \"${step.text}\" does not match any step definition`,\n rule: \"undefined-step\",\n source: \"step-forge\" as const,\n }));\n },\n};\n","import {\n AnalysisRule,\n Diagnostic,\n MatchedStep,\n ParsedScenario,\n} from \"../types.js\";\nimport { ambiguousStepRule } from \"./ambiguousStepRule.js\";\nimport { dependencyRule } from \"./dependencyRule.js\";\nimport { undefinedStepRule } from \"./undefinedStepRule.js\";\n\nexport const defaultRules: AnalysisRule[] = [\n undefinedStepRule,\n ambiguousStepRule,\n dependencyRule,\n];\n\nexport function runRules(\n rules: AnalysisRule[],\n scenario: ParsedScenario,\n matchedSteps: MatchedStep[]\n): Diagnostic[] {\n return rules.flatMap(rule => rule.check(scenario, matchedSteps));\n}\n","import { globFiles } from \"../globFiles.js\";\nimport { extractStepDefinitions } from \"./stepExtractor.js\";\nimport { parseFeatureFiles, parseFeatureContent } from \"./gherkinParser.js\";\nimport { matchScenarioSteps, findMatchingDefinitions } from \"./stepMatcher.js\";\nimport { defaultRules, runRules } from \"./rules/index.js\";\nimport type {\n AnalyzerConfig,\n AnalysisRule,\n Diagnostic,\n StepDefinitionMeta,\n ParsedScenario,\n MatchedStep,\n ParsedStep,\n} from \"./types.js\";\n\nexport type {\n AnalyzerConfig,\n AnalysisRule,\n Diagnostic,\n StepDefinitionMeta,\n ParsedScenario,\n MatchedStep,\n ParsedStep,\n};\n\nexport {\n extractStepDefinitions,\n parseFeatureFiles,\n parseFeatureContent,\n matchScenarioSteps,\n findMatchingDefinitions,\n defaultRules,\n};\n\nexport interface AnalyzeOptions {\n rules?: AnalysisRule[];\n}\n\nexport async function analyze(\n config: AnalyzerConfig,\n options?: AnalyzeOptions\n): Promise<Diagnostic[]> {\n const rules = options?.rules ?? defaultRules;\n\n // 1. Resolve file globs to paths\n const stepFilePaths = await globFiles(config.stepFiles);\n const featureFilePaths = await globFiles(config.featureFiles);\n\n if (stepFilePaths.length === 0) {\n return [];\n }\n if (featureFilePaths.length === 0) {\n return [];\n }\n\n // 2. Extract step metadata from step files\n const stepDefinitions = extractStepDefinitions(\n stepFilePaths,\n config.tsConfigPath\n );\n\n // 3. Parse feature files\n const scenarios = parseFeatureFiles(featureFilePaths);\n\n // 4. For each scenario, match steps and run rules\n const diagnostics: Diagnostic[] = [];\n for (const scenario of scenarios) {\n const matchedSteps = matchScenarioSteps(scenario, stepDefinitions);\n const scenarioDiags = runRules(rules, scenario, matchedSteps);\n diagnostics.push(...scenarioDiags);\n }\n\n return diagnostics;\n}\n","import { givenBuilder } from \"./given\";\nimport { thenBuilder } from \"./then\";\nimport { whenBuilder } from \"./when\";\n\nexport const createBuilders = <GivenState, WhenState, ThenState>() => {\n return {\n Given: givenBuilder<GivenState>().statement,\n When: whenBuilder<GivenState, WhenState>().statement,\n Then: thenBuilder<GivenState, WhenState, ThenState>().statement,\n };\n};\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n globalHookRegistry,\n PlainHookFn,\n ScenarioHookFn,\n ScenarioInfo,\n} from \"./runtime/hooks\";\nimport { MergeableWorld } from \"./world\";\n\n/**\n * Run before every scenario, with access to that scenario's fresh world. For\n * side effects only (reset a mock, seed an external system) — return values are\n * ignored; seed test *state* with given steps so the dependency graph stays the\n * single source of truth.\n */\nexport function beforeScenario<\n World extends MergeableWorld<any, any, any> = MergeableWorld<any, any, any>,\n>(\n fn: (context: {\n world: World;\n scenario: ScenarioInfo;\n }) => void | Promise<void>\n): void {\n globalHookRegistry.add({\n scope: \"scenario\",\n timing: \"before\",\n fn: fn as ScenarioHookFn,\n });\n}\n\n/**\n * Run after every scenario (even when a step failed), with access to that\n * scenario's world. Runs in reverse registration order so teardown unwinds\n * setup. For cleanup side effects only.\n */\nexport function afterScenario<\n World extends MergeableWorld<any, any, any> = MergeableWorld<any, any, any>,\n>(\n fn: (context: {\n world: World;\n scenario: ScenarioInfo;\n }) => void | Promise<void>\n): void {\n globalHookRegistry.add({\n scope: \"scenario\",\n timing: \"after\",\n fn: fn as ScenarioHookFn,\n });\n}\n\n/** Run once at the start of each feature file. No world exists at this boundary. */\nexport function beforeFeature(fn: PlainHookFn): void {\n globalHookRegistry.add({ scope: \"feature\", timing: \"before\", fn });\n}\n\n/** Run once at the end of each feature file (reverse registration order). */\nexport function afterFeature(fn: PlainHookFn): void {\n globalHookRegistry.add({ scope: \"feature\", timing: \"after\", fn });\n}\n\n/**\n * Run once before the entire run, ahead of any scenario (and before\n * concurrency starts). Multiple `beforeAll` hooks run **in parallel** with no\n * ordering between them — if a step of setup must precede another, sequence both\n * inside a single hook.\n */\nexport function beforeAll(fn: PlainHookFn): void {\n globalHookRegistry.add({ scope: \"global\", timing: \"before\", fn });\n}\n\n/**\n * Run once after the entire run, once every scenario is done. Multiple\n * `afterAll` hooks run **in parallel** with no ordering between them — sequence\n * dependent teardown inside a single hook.\n */\nexport function afterAll(fn: PlainHookFn): void {\n globalHookRegistry.add({ scope: \"global\", timing: \"after\", fn });\n}\n","import { givenBuilder } from \"./given\";\nimport { whenBuilder } from \"./when\";\nimport { thenBuilder } from \"./then\";\nimport { BasicWorld } from \"./world\";\nimport {\n stringParser,\n intParser,\n numberParser,\n booleanParser,\n} from \"./parsers\";\nimport type { Parser } from \"./parsers\";\nimport {\n analyze,\n extractStepDefinitions,\n parseFeatureFiles,\n parseFeatureContent,\n matchScenarioSteps,\n findMatchingDefinitions,\n defaultRules,\n} from \"./analyzer/index\";\nimport type {\n AnalyzerConfig,\n AnalyzeOptions,\n AnalysisRule,\n Diagnostic,\n StepDefinitionMeta,\n ParsedScenario,\n ParsedStep,\n MatchedStep,\n} from \"./analyzer/index\";\nimport { createBuilders } from \"./init\";\nimport {\n beforeScenario,\n afterScenario,\n beforeFeature,\n afterFeature,\n beforeAll,\n afterAll,\n} from \"./hooks\";\n\nexport {\n givenBuilder,\n whenBuilder,\n thenBuilder,\n BasicWorld,\n stringParser,\n intParser,\n numberParser,\n booleanParser,\n createBuilders,\n beforeScenario,\n afterScenario,\n beforeFeature,\n afterFeature,\n beforeAll,\n afterAll,\n};\n\nexport type { Parser };\nexport type {\n ScenarioInfo,\n PlainHookFn,\n ScenarioHookFn,\n} from \"./runtime/hooks\";\nexport type { StateFromDependencies } from \"./typeHelpers\";\n// Re-exported from the main entry so consumers can type their\n// `step-forge.config.ts` with a plain `@step-forge/step-forge` import.\nexport type { RunnerOptions } from \"./runtime/config\";\n\nexport const analyzer = {\n analyze,\n extractStepDefinitions,\n parseFeatureFiles,\n parseFeatureContent,\n matchScenarioSteps,\n findMatchingDefinitions,\n defaultRules,\n};\n\nexport type {\n AnalyzerConfig,\n AnalyzeOptions,\n AnalysisRule,\n Diagnostic,\n StepDefinitionMeta,\n ParsedScenario,\n ParsedStep,\n MatchedStep,\n};\n"],"mappings":";;;;;;;;AAiCA,MAAa,YACX,cACwB,OAAO,cAAc;;;;ACN/C,MAAa,eAA+B;CAC1C,MAAM;CACN,QAAQ,CAAC,4BAA4B,0BAA0B;CAC/D,QAAO,UAAS;EACd,MAAM,QAAQ,gBAAgB,KAAK,KAAK,KAAK,gBAAgB,KAAK,KAAK;EACvE,OAAO,QAAQ,MAAM,EAAE,CAAC,QAAQ,aAAa,IAAI,IAAI;CACvD;AACF;;AAGA,MAAa,YAA4B;CACvC,MAAM;CACN,QAAQ;CACR,QAAO,UAAS,SAAS,OAAO,EAAE;AACpC;;AAGA,MAAa,eAA+B;CAC1C,MAAM;CACN,QAAQ;CACR,QAAO,UAAS,WAAW,KAAK;AAClC;;;;;;AAOA,MAAa,gBAAiC;CAC5C,MAAM;CACN,QAAQ;CACR,QAAO,UAAS,UAAU;AAC5B;;;AC3DA,MAAa,oBACX,MACA,UACG;CACH,KAAK,SAAQ,QAAO;EAClB,IAAI,CAAC,MAAM,MAAM,MACf,MAAM,IAAI,MAAM,OAAO,OAAO,GAAG,EAAE,4BAA4B;CAEnE,CAAC;CACD,OAAO,KAAK,QACT,KAAK,QAAQ;EACZ,OAAO;GACL,GAAG;IACF,MAAM,MAAM,MAAM;EACrB;CACF,GACA,CAAC,CACH;AACF;AACA,MAAa,mBACX,MACA,UACG;CACH,KAAK,SAAQ,QAAO;EAClB,IAAI,CAAC,MAAM,KAAK,MACd,MAAM,IAAI,MAAM,OAAO,OAAO,GAAG,EAAE,2BAA2B;CAElE,CAAC;CACD,OAAO,KAAK,QACT,KAAK,QAAQ;EACZ,OAAO;GACL,GAAG;IACF,MAAM,MAAM,KAAK;EAC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as findMatchingDefinitions, o as extractStepDefinitions, r as defaultRules, t as analyze } from "./analyzer-DnfK54Dw.js";
2
1
  import { n as globalHookRegistry, o as globalRegistry } from "./hooks-BDCMKeNq.js";
3
- import { a as BasicWorld, n as parseFeatureContent, o as captureDefinitionSite, r as parseFeatureFiles } from "./gherkinParser-i-Q7M6mi.js";
2
+ import { a as BasicWorld, i as globFiles, n as parseFeatureContent, o as captureDefinitionSite, r as parseFeatureFiles } from "./gherkinParser-i-Q7M6mi.js";
4
3
  import _ from "lodash";
4
+ import ts from "typescript";
5
5
  //#region src/builderTypeUtils.ts
6
6
  const isString = (statement) => typeof statement === "string";
7
7
  //#endregion
@@ -194,6 +194,396 @@ const thenStatement = () => (statement) => {
194
194
  };
195
195
  const thenBuilder = () => ({ statement: thenStatement() });
196
196
  //#endregion
197
+ //#region src/analyzer/stepExtractor.ts
198
+ const BUILDER_NAMES = {
199
+ givenBuilder: "given",
200
+ whenBuilder: "when",
201
+ thenBuilder: "then"
202
+ };
203
+ function extractStepDefinitions(filePaths, tsConfigPath) {
204
+ const fast = extractWithSources(filePaths.map(parseSourceFile).filter((s) => s !== null), null);
205
+ if (!fast.needsChecker) return fast.results;
206
+ const program = ts.createProgram(filePaths, resolveCompilerOptions(tsConfigPath));
207
+ const checker = program.getTypeChecker();
208
+ return extractWithSources(filePaths.map((fp) => program.getSourceFile(fp)).filter((s) => s !== void 0), checker).results;
209
+ }
210
+ /** Parse a single file into an AST with no type resolution. */
211
+ function parseSourceFile(filePath) {
212
+ const text = ts.sys.readFile(filePath);
213
+ if (text === void 0) return null;
214
+ const scriptKind = filePath.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
215
+ return ts.createSourceFile(filePath, text, ts.ScriptTarget.ESNext, true, scriptKind);
216
+ }
217
+ /** Resolve compiler options from tsconfig (fallback to sane defaults). */
218
+ function resolveCompilerOptions(tsConfigPath) {
219
+ const configPath = tsConfigPath ?? ts.findConfigFile(process.cwd(), ts.sys.fileExists);
220
+ let compilerOptions = {
221
+ target: ts.ScriptTarget.ESNext,
222
+ module: ts.ModuleKind.ESNext,
223
+ moduleResolution: ts.ModuleResolutionKind.Node10,
224
+ strict: true,
225
+ esModuleInterop: true
226
+ };
227
+ if (configPath) {
228
+ const configFile = ts.readConfigFile(configPath, ts.sys.readFile);
229
+ if (!configFile.error) compilerOptions = ts.parseJsonConfigFileContent(configFile.config, ts.sys, configPath.replace(/[/\\][^/\\]+$/, "")).options;
230
+ }
231
+ compilerOptions.noEmit = true;
232
+ return compilerOptions;
233
+ }
234
+ function extractWithSources(sources, checker) {
235
+ const ctx = {
236
+ checker,
237
+ needsChecker: false
238
+ };
239
+ const results = [];
240
+ for (const sourceFile of sources) results.push(...extractFromSourceFile(sourceFile, ctx));
241
+ return {
242
+ results,
243
+ needsChecker: ctx.needsChecker
244
+ };
245
+ }
246
+ function extractFromSourceFile(sourceFile, ctx) {
247
+ const results = [];
248
+ function visit(node) {
249
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "step") {
250
+ const meta = extractFromRegisterCall(node, sourceFile, ctx);
251
+ if (meta) results.push(meta);
252
+ }
253
+ ts.forEachChild(node, visit);
254
+ }
255
+ visit(sourceFile);
256
+ return results;
257
+ }
258
+ function extractFromRegisterCall(registerCall, sourceFile, ctx) {
259
+ const chain = collectCallChain(registerCall);
260
+ let stepType = null;
261
+ let expression = null;
262
+ let dependencies = {
263
+ given: {},
264
+ when: {},
265
+ then: {}
266
+ };
267
+ let produces = [];
268
+ for (const link of chain) {
269
+ const name = getCallName(link);
270
+ if (!name) continue;
271
+ if (name === "register") continue;
272
+ if (name === "step") {
273
+ produces = extractProducedKeys(link, ctx);
274
+ continue;
275
+ }
276
+ if (name === "dependencies") {
277
+ dependencies = extractDependencies(link);
278
+ continue;
279
+ }
280
+ if (name === "statement") {
281
+ expression = extractExpression(link);
282
+ continue;
283
+ }
284
+ if (BUILDER_NAMES[name]) {
285
+ stepType = BUILDER_NAMES[name];
286
+ continue;
287
+ }
288
+ }
289
+ if (!stepType || !expression) {
290
+ const reExport = resolveReExportedCall(chain, ctx);
291
+ if (reExport) {
292
+ if (!stepType) stepType = reExport.stepType;
293
+ if (!expression) expression = reExport.expression;
294
+ }
295
+ }
296
+ if (!stepType || !expression) return null;
297
+ const line = sourceFile.getLineAndCharacterOfPosition(registerCall.getStart()).line + 1;
298
+ return {
299
+ stepType,
300
+ expression,
301
+ dependencies,
302
+ produces,
303
+ sourceFile: sourceFile.fileName,
304
+ line
305
+ };
306
+ }
307
+ /**
308
+ * Collect all call expressions in the method chain, from register() back to the origin.
309
+ */
310
+ function collectCallChain(call) {
311
+ const chain = [call];
312
+ let current = call.expression;
313
+ if (ts.isPropertyAccessExpression(current)) current = current.expression;
314
+ while (ts.isCallExpression(current)) {
315
+ chain.push(current);
316
+ current = current.expression;
317
+ if (ts.isPropertyAccessExpression(current)) current = current.expression;
318
+ }
319
+ return chain;
320
+ }
321
+ function getCallName(call) {
322
+ const expr = call.expression;
323
+ if (ts.isPropertyAccessExpression(expr)) return expr.name.text;
324
+ if (ts.isIdentifier(expr)) return expr.text;
325
+ return null;
326
+ }
327
+ function extractExpression(statementCall) {
328
+ const arg = statementCall.arguments[0];
329
+ if (!arg) return null;
330
+ if (ts.isStringLiteral(arg)) return arg.text;
331
+ if (ts.isArrowFunction(arg)) return extractExpressionFromArrowFunction(arg);
332
+ return null;
333
+ }
334
+ function extractExpressionFromArrowFunction(fn) {
335
+ const params = fn.parameters.map((p) => p.name.getText());
336
+ let body = fn.body;
337
+ if (ts.isBlock(body)) {
338
+ const returnStmt = body.statements.find(ts.isReturnStatement);
339
+ if (returnStmt?.expression) body = returnStmt.expression;
340
+ else return null;
341
+ }
342
+ if (ts.isTemplateExpression(body)) return reconstructExpressionFromTemplate(body, params);
343
+ if (ts.isNoSubstitutionTemplateLiteral(body)) return body.text;
344
+ return null;
345
+ }
346
+ function reconstructExpressionFromTemplate(template, paramNames) {
347
+ let result = template.head.text;
348
+ for (const span of template.templateSpans) {
349
+ if (ts.isIdentifier(span.expression) && paramNames.includes(span.expression.text)) result += "{string}";
350
+ else result += "{string}";
351
+ result += span.literal.text;
352
+ }
353
+ return result;
354
+ }
355
+ function extractDependencies(depsCall) {
356
+ const deps = {
357
+ given: {},
358
+ when: {},
359
+ then: {}
360
+ };
361
+ const arg = depsCall.arguments[0];
362
+ if (!arg || !ts.isObjectLiteralExpression(arg)) return deps;
363
+ for (const prop of arg.properties) {
364
+ if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) continue;
365
+ const phase = prop.name.text;
366
+ if (!deps[phase]) continue;
367
+ if (ts.isObjectLiteralExpression(prop.initializer)) {
368
+ for (const innerProp of prop.initializer.properties) if (ts.isPropertyAssignment(innerProp) && ts.isIdentifier(innerProp.name) && ts.isStringLiteral(innerProp.initializer)) {
369
+ const val = innerProp.initializer.text;
370
+ if (val === "required" || val === "optional") deps[phase][innerProp.name.text] = val;
371
+ }
372
+ }
373
+ }
374
+ return deps;
375
+ }
376
+ function extractProducedKeys(stepCall, ctx) {
377
+ const callback = stepCall.arguments[0];
378
+ if (!callback) return [];
379
+ if (ts.isArrowFunction(callback) || ts.isFunctionExpression(callback)) return extractProducedKeysFromCallback(callback, ctx);
380
+ return [];
381
+ }
382
+ function extractProducedKeysFromCallback(callback, ctx) {
383
+ const body = callback.body;
384
+ if (!ts.isBlock(body)) return extractKeysFromExpression(body, ctx);
385
+ const keys = /* @__PURE__ */ new Set();
386
+ function visitReturn(node) {
387
+ if (ts.isReturnStatement(node) && node.expression) for (const key of extractKeysFromExpression(node.expression, ctx)) keys.add(key);
388
+ ts.forEachChild(node, visitReturn);
389
+ }
390
+ visitReturn(body);
391
+ return [...keys];
392
+ }
393
+ function extractKeysFromExpression(expr, ctx) {
394
+ while (ts.isParenthesizedExpression(expr)) expr = expr.expression;
395
+ if (ts.isObjectLiteralExpression(expr)) return expr.properties.filter((p) => ts.isPropertyAssignment(p) || ts.isShorthandPropertyAssignment(p)).map((p) => p.name.getText()).filter(Boolean);
396
+ if (!ctx.checker) {
397
+ ctx.needsChecker = true;
398
+ return [];
399
+ }
400
+ try {
401
+ return ctx.checker.getTypeAtLocation(expr).getProperties().map((p) => p.name).filter((n) => n !== "merge");
402
+ } catch {
403
+ return [];
404
+ }
405
+ }
406
+ function resolveReExportedCall(chain, ctx) {
407
+ const lastCall = chain[chain.length - 1];
408
+ if (!lastCall) return null;
409
+ const expr = lastCall.expression;
410
+ let identifier = null;
411
+ if (ts.isIdentifier(expr)) identifier = expr;
412
+ else if (ts.isPropertyAccessExpression(expr) && ts.isIdentifier(expr.expression)) identifier = expr.expression;
413
+ if (!identifier) return null;
414
+ if (!ctx.checker) {
415
+ ctx.needsChecker = true;
416
+ return null;
417
+ }
418
+ const symbol = ctx.checker.getSymbolAtLocation(identifier);
419
+ if (!symbol) return null;
420
+ const decl = symbol.valueDeclaration;
421
+ if (!decl || !ts.isVariableDeclaration(decl) || !decl.initializer) return null;
422
+ const init = decl.initializer;
423
+ if (ts.isPropertyAccessExpression(init) && init.name.text === "statement") {
424
+ const callExpr = init.expression;
425
+ if (ts.isCallExpression(callExpr)) {
426
+ const callee = callExpr.expression;
427
+ if (ts.isIdentifier(callee) && BUILDER_NAMES[callee.text]) {
428
+ const expression = extractExpression(lastCall);
429
+ return {
430
+ stepType: BUILDER_NAMES[callee.text],
431
+ expression
432
+ };
433
+ }
434
+ }
435
+ }
436
+ return null;
437
+ }
438
+ //#endregion
439
+ //#region src/analyzer/stepMatcher.ts
440
+ function compileDefinitions(definitions) {
441
+ const compiled = [];
442
+ for (const def of definitions) try {
443
+ const placeholder = "###PLACEHOLDER###";
444
+ const regexStr = def.expression.replace(/\{[^}]+\}/g, placeholder).replace(/[.*+?^$()|[\]\\]/g, "\\$&").replace(new RegExp(placeholder, "g"), "(.+)");
445
+ compiled.push({
446
+ regex: new RegExp(`^${regexStr}$`, "i"),
447
+ definition: def
448
+ });
449
+ } catch {}
450
+ return compiled;
451
+ }
452
+ function matchScenarioSteps(scenario, definitions) {
453
+ const compiled = compileDefinitions(definitions);
454
+ return scenario.steps.map((step) => {
455
+ const matches = findMatches(step.text, step.effectiveKeyword, compiled);
456
+ return {
457
+ ...step,
458
+ definitions: matches
459
+ };
460
+ });
461
+ }
462
+ function findMatchingDefinitions(text, effectiveKeyword, definitions) {
463
+ return findMatches(text, effectiveKeyword, compileDefinitions(definitions));
464
+ }
465
+ function findMatches(text, effectiveKeyword, compiled) {
466
+ const expectedStepType = {
467
+ Given: "given",
468
+ When: "when",
469
+ Then: "then"
470
+ }[effectiveKeyword];
471
+ const typedMatches = [];
472
+ for (const { regex, definition } of compiled) {
473
+ if (definition.stepType !== expectedStepType) continue;
474
+ if (regex.test(text)) typedMatches.push(definition);
475
+ }
476
+ if (typedMatches.length > 0) return typedMatches;
477
+ const fallbackMatches = [];
478
+ for (const { regex, definition } of compiled) if (regex.test(text)) fallbackMatches.push(definition);
479
+ return fallbackMatches;
480
+ }
481
+ //#endregion
482
+ //#region src/analyzer/rules/index.ts
483
+ const defaultRules = [
484
+ {
485
+ name: "undefined-step",
486
+ check(scenario, matchedSteps) {
487
+ return matchedSteps.filter((step) => step.definitions.length === 0).map((step) => ({
488
+ file: scenario.file,
489
+ range: {
490
+ startLine: step.line,
491
+ startColumn: step.column,
492
+ endLine: step.line,
493
+ endColumn: step.column + step.text.length
494
+ },
495
+ severity: "error",
496
+ message: `Step "${step.text}" does not match any step definition`,
497
+ rule: "undefined-step",
498
+ source: "step-forge"
499
+ }));
500
+ }
501
+ },
502
+ {
503
+ name: "ambiguous-step",
504
+ check(scenario, matchedSteps) {
505
+ return matchedSteps.filter((step) => step.definitions.length > 1).map((step) => {
506
+ const locations = step.definitions.map((d) => `${d.sourceFile}:${d.line}`).join(", ");
507
+ return {
508
+ file: scenario.file,
509
+ range: {
510
+ startLine: step.line,
511
+ startColumn: step.column,
512
+ endLine: step.line,
513
+ endColumn: step.column + step.text.length
514
+ },
515
+ severity: "error",
516
+ message: `Step "${step.text}" matches multiple step definitions: ${locations}`,
517
+ rule: "ambiguous-step",
518
+ source: "step-forge"
519
+ };
520
+ });
521
+ }
522
+ },
523
+ {
524
+ name: "dependency-check",
525
+ check(scenario, matchedSteps) {
526
+ const diagnostics = [];
527
+ const produced = {
528
+ given: /* @__PURE__ */ new Set(),
529
+ when: /* @__PURE__ */ new Set(),
530
+ then: /* @__PURE__ */ new Set()
531
+ };
532
+ for (const step of matchedSteps) {
533
+ if (step.definitions.length !== 1) continue;
534
+ const { dependencies, produces, stepType } = step.definitions[0];
535
+ const missing = {};
536
+ for (const phase of [
537
+ "given",
538
+ "when",
539
+ "then"
540
+ ]) for (const [key, requirement] of Object.entries(dependencies[phase])) if (requirement === "required" && !produced[phase].has(key)) {
541
+ if (!missing[phase]) missing[phase] = [];
542
+ missing[phase].push(key);
543
+ }
544
+ if (Object.keys(missing).length > 0) {
545
+ const message = "Missing required dependencies:\n" + Object.entries(missing).map(([phase, keys]) => `${phase.charAt(0).toUpperCase() + phase.slice(1)}: ${keys.map((k) => `${phase}.${k}`).join(", ")}`).join("\n");
546
+ diagnostics.push({
547
+ file: scenario.file,
548
+ range: {
549
+ startLine: step.line,
550
+ startColumn: step.column,
551
+ endLine: step.line,
552
+ endColumn: step.column + step.text.length
553
+ },
554
+ severity: "error",
555
+ message,
556
+ rule: "dependency-check",
557
+ source: "step-forge"
558
+ });
559
+ }
560
+ for (const key of produces) produced[stepType].add(key);
561
+ }
562
+ return diagnostics;
563
+ }
564
+ }
565
+ ];
566
+ function runRules(rules, scenario, matchedSteps) {
567
+ return rules.flatMap((rule) => rule.check(scenario, matchedSteps));
568
+ }
569
+ //#endregion
570
+ //#region src/analyzer/index.ts
571
+ async function analyze(config, options) {
572
+ const rules = options?.rules ?? defaultRules;
573
+ const stepFilePaths = await globFiles(config.stepFiles);
574
+ const featureFilePaths = await globFiles(config.featureFiles);
575
+ if (stepFilePaths.length === 0) return [];
576
+ if (featureFilePaths.length === 0) return [];
577
+ const stepDefinitions = extractStepDefinitions(stepFilePaths, config.tsConfigPath);
578
+ const scenarios = parseFeatureFiles(featureFilePaths);
579
+ const diagnostics = [];
580
+ for (const scenario of scenarios) {
581
+ const scenarioDiags = runRules(rules, scenario, matchScenarioSteps(scenario, stepDefinitions));
582
+ diagnostics.push(...scenarioDiags);
583
+ }
584
+ return diagnostics;
585
+ }
586
+ //#endregion
197
587
  //#region src/init.ts
198
588
  const createBuilders = () => {
199
589
  return {