@fabricorg/databricks-bdd 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +56 -5
- package/dist/actions-CuXXKUqe.d.ts +92 -0
- package/dist/actions-CxfxhBZh.d.cts +92 -0
- package/dist/actions.cjs +14 -0
- package/dist/actions.cjs.map +1 -0
- package/dist/actions.d.cts +6 -0
- package/dist/actions.d.ts +6 -0
- package/dist/actions.js +3 -0
- package/dist/actions.js.map +1 -0
- package/dist/cardinality.cjs +24 -0
- package/dist/cardinality.cjs.map +1 -0
- package/dist/cardinality.d.cts +19 -0
- package/dist/cardinality.d.ts +19 -0
- package/dist/cardinality.js +3 -0
- package/dist/cardinality.js.map +1 -0
- package/dist/{chunk-FNTI2VUP.js → chunk-3XDMBHFP.js} +117 -4
- package/dist/chunk-3XDMBHFP.js.map +1 -0
- package/dist/chunk-6JC65RH2.js +11 -0
- package/dist/chunk-6JC65RH2.js.map +1 -0
- package/dist/chunk-HTKRJLVX.js +70 -0
- package/dist/chunk-HTKRJLVX.js.map +1 -0
- package/dist/chunk-K5LJ7WSW.js +22 -0
- package/dist/chunk-K5LJ7WSW.js.map +1 -0
- package/dist/chunk-SZL3KWW7.js +62 -0
- package/dist/chunk-SZL3KWW7.js.map +1 -0
- package/dist/fixtures.cjs +65 -0
- package/dist/fixtures.cjs.map +1 -0
- package/dist/fixtures.d.cts +34 -0
- package/dist/fixtures.d.ts +34 -0
- package/dist/fixtures.js +3 -0
- package/dist/fixtures.js.map +1 -0
- package/dist/index.cjs +277 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +24 -55
- package/dist/index.d.ts +24 -55
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/scoped-state.cjs +74 -0
- package/dist/scoped-state.cjs.map +1 -0
- package/dist/scoped-state.d.cts +30 -0
- package/dist/scoped-state.d.ts +30 -0
- package/dist/scoped-state.js +3 -0
- package/dist/scoped-state.js.map +1 -0
- package/dist/steps.cjs +254 -2
- package/dist/steps.cjs.map +1 -1
- package/dist/steps.js +15 -4
- package/dist/steps.js.map +1 -1
- package/package.json +41 -1
- package/dist/chunk-FNTI2VUP.js.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -9,6 +9,142 @@ var path = require('path');
|
|
|
9
9
|
var util = require('util');
|
|
10
10
|
|
|
11
11
|
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
12
|
+
// src/world.ts
|
|
13
|
+
|
|
14
|
+
// src/actions.ts
|
|
15
|
+
function defineAction(action) {
|
|
16
|
+
return action;
|
|
17
|
+
}
|
|
18
|
+
async function runAction(world, action, ...args) {
|
|
19
|
+
return await action(world, ...args);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// src/fixtures.ts
|
|
23
|
+
function isFixtureResult(value) {
|
|
24
|
+
return typeof value === "object" && value !== null && Object.prototype.hasOwnProperty.call(value, "value") && typeof value.cleanup === "function";
|
|
25
|
+
}
|
|
26
|
+
var SharedFixtureRegistry = class {
|
|
27
|
+
runEntries = /* @__PURE__ */ new Map();
|
|
28
|
+
featureEntries = /* @__PURE__ */ new Map();
|
|
29
|
+
cleanupOrder = [];
|
|
30
|
+
runFixture(key, setup) {
|
|
31
|
+
return this.resolve(this.runEntries, key, setup);
|
|
32
|
+
}
|
|
33
|
+
featureFixture(featureUri, key, setup) {
|
|
34
|
+
if (!featureUri) throw new Error("featureFixture requires a feature URI");
|
|
35
|
+
let feature = this.featureEntries.get(featureUri);
|
|
36
|
+
if (!feature) {
|
|
37
|
+
feature = /* @__PURE__ */ new Map();
|
|
38
|
+
this.featureEntries.set(featureUri, feature);
|
|
39
|
+
}
|
|
40
|
+
return this.resolve(feature, key, setup);
|
|
41
|
+
}
|
|
42
|
+
resolve(entries, key, setup) {
|
|
43
|
+
if (!key.trim()) throw new Error("Fixture key must not be empty");
|
|
44
|
+
const existing = entries.get(key);
|
|
45
|
+
if (existing) return existing.value;
|
|
46
|
+
const entry = {
|
|
47
|
+
value: Promise.resolve().then(setup).then((result) => {
|
|
48
|
+
if (isFixtureResult(result)) {
|
|
49
|
+
entry.cleanup = result.cleanup;
|
|
50
|
+
return result.value;
|
|
51
|
+
}
|
|
52
|
+
return result;
|
|
53
|
+
}).catch((error) => {
|
|
54
|
+
entries.delete(key);
|
|
55
|
+
const index = this.cleanupOrder.indexOf(entry);
|
|
56
|
+
if (index >= 0) this.cleanupOrder.splice(index, 1);
|
|
57
|
+
throw error;
|
|
58
|
+
})
|
|
59
|
+
};
|
|
60
|
+
entries.set(key, entry);
|
|
61
|
+
this.cleanupOrder.push(entry);
|
|
62
|
+
return entry.value;
|
|
63
|
+
}
|
|
64
|
+
async dispose() {
|
|
65
|
+
const errors = [];
|
|
66
|
+
for (const entry of this.cleanupOrder.splice(0).reverse()) {
|
|
67
|
+
try {
|
|
68
|
+
await entry.value.catch(() => void 0);
|
|
69
|
+
await entry.cleanup?.();
|
|
70
|
+
} catch (error) {
|
|
71
|
+
errors.push(error);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
this.runEntries.clear();
|
|
75
|
+
this.featureEntries.clear();
|
|
76
|
+
if (errors.length > 0) throw new AggregateError(errors, "Shared fixture cleanup failed");
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
var sharedFixtures = new SharedFixtureRegistry();
|
|
80
|
+
|
|
81
|
+
// src/scoped-state.ts
|
|
82
|
+
var SharedStateRegistry = class {
|
|
83
|
+
runValues = /* @__PURE__ */ new Map();
|
|
84
|
+
featureValues = /* @__PURE__ */ new Map();
|
|
85
|
+
run() {
|
|
86
|
+
return this.runValues;
|
|
87
|
+
}
|
|
88
|
+
feature(featureUri) {
|
|
89
|
+
if (!featureUri) throw new Error("Feature state requires a feature URI");
|
|
90
|
+
let values = this.featureValues.get(featureUri);
|
|
91
|
+
if (!values) {
|
|
92
|
+
values = /* @__PURE__ */ new Map();
|
|
93
|
+
this.featureValues.set(featureUri, values);
|
|
94
|
+
}
|
|
95
|
+
return values;
|
|
96
|
+
}
|
|
97
|
+
clear() {
|
|
98
|
+
this.runValues.clear();
|
|
99
|
+
this.featureValues.clear();
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
var ScopedState = class {
|
|
103
|
+
constructor(runValues, featureValues) {
|
|
104
|
+
this.runValues = runValues;
|
|
105
|
+
this.featureValues = featureValues;
|
|
106
|
+
}
|
|
107
|
+
runValues;
|
|
108
|
+
featureValues;
|
|
109
|
+
scenarioValues = /* @__PURE__ */ new Map();
|
|
110
|
+
set(scope, key, value) {
|
|
111
|
+
this.values(scope).set(validateKey(key), value);
|
|
112
|
+
return value;
|
|
113
|
+
}
|
|
114
|
+
get(key) {
|
|
115
|
+
const validKey = validateKey(key);
|
|
116
|
+
if (this.scenarioValues.has(validKey)) return this.scenarioValues.get(validKey);
|
|
117
|
+
if (this.featureValues.has(validKey)) return this.featureValues.get(validKey);
|
|
118
|
+
return this.runValues.get(validKey);
|
|
119
|
+
}
|
|
120
|
+
require(key) {
|
|
121
|
+
const value = this.get(key);
|
|
122
|
+
if (value === void 0) throw new Error(`Required BDD state '${key}' is not set`);
|
|
123
|
+
return value;
|
|
124
|
+
}
|
|
125
|
+
has(key) {
|
|
126
|
+
const validKey = validateKey(key);
|
|
127
|
+
return this.scenarioValues.has(validKey) || this.featureValues.has(validKey) || this.runValues.has(validKey);
|
|
128
|
+
}
|
|
129
|
+
delete(scope, key) {
|
|
130
|
+
return this.values(scope).delete(validateKey(key));
|
|
131
|
+
}
|
|
132
|
+
clearScenario() {
|
|
133
|
+
this.scenarioValues.clear();
|
|
134
|
+
}
|
|
135
|
+
values(scope) {
|
|
136
|
+
if (scope === "run") return this.runValues;
|
|
137
|
+
if (scope === "feature") return this.featureValues;
|
|
138
|
+
return this.scenarioValues;
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
function validateKey(key) {
|
|
142
|
+
const trimmed = key.trim();
|
|
143
|
+
if (!trimmed) throw new Error("BDD state key must not be empty");
|
|
144
|
+
return trimmed;
|
|
145
|
+
}
|
|
146
|
+
var sharedState = new SharedStateRegistry();
|
|
147
|
+
|
|
12
148
|
// src/world.ts
|
|
13
149
|
var DatabricksWorld = class extends cucumber.World {
|
|
14
150
|
profile;
|
|
@@ -24,10 +160,14 @@ var DatabricksWorld = class extends cucumber.World {
|
|
|
24
160
|
catalogOverride;
|
|
25
161
|
lastSql;
|
|
26
162
|
lastStatementId;
|
|
163
|
+
featureUri;
|
|
164
|
+
scenarioName;
|
|
165
|
+
effectiveTags = [];
|
|
27
166
|
stepOutputCapture;
|
|
28
167
|
lakebasePool;
|
|
29
168
|
ctx;
|
|
30
169
|
activeCtx;
|
|
170
|
+
scopedState;
|
|
31
171
|
cleanups = [];
|
|
32
172
|
constructor(options) {
|
|
33
173
|
super(options);
|
|
@@ -62,6 +202,43 @@ var DatabricksWorld = class extends cucumber.World {
|
|
|
62
202
|
addCleanup(cleanup) {
|
|
63
203
|
this.cleanups.push(cleanup);
|
|
64
204
|
}
|
|
205
|
+
/** Initialize Behave-style feature/scenario metadata and layered state. */
|
|
206
|
+
initializeScenario(featureUri, scenarioName, tags) {
|
|
207
|
+
this.featureUri = featureUri;
|
|
208
|
+
this.scenarioName = scenarioName;
|
|
209
|
+
this.effectiveTags = [...tags];
|
|
210
|
+
this.scopedState = new ScopedState(sharedState.run(), sharedState.feature(featureUri));
|
|
211
|
+
}
|
|
212
|
+
/** Set typed state at run, feature, or scenario scope. */
|
|
213
|
+
setState(scope, key, value) {
|
|
214
|
+
return this.state().set(scope, key, value);
|
|
215
|
+
}
|
|
216
|
+
/** Resolve state using scenario → feature → run precedence. */
|
|
217
|
+
getState(key) {
|
|
218
|
+
return this.state().get(key);
|
|
219
|
+
}
|
|
220
|
+
/** Resolve required layered state or fail with a useful message. */
|
|
221
|
+
requireState(key) {
|
|
222
|
+
return this.state().require(key);
|
|
223
|
+
}
|
|
224
|
+
/** Compose a reusable typed action without reparsing textual Gherkin. */
|
|
225
|
+
runAction(action, ...args) {
|
|
226
|
+
return runAction(this, action, ...args);
|
|
227
|
+
}
|
|
228
|
+
/** Setup a resource once for this Cucumber run and clean it up in AfterAll. */
|
|
229
|
+
runFixture(key, setup) {
|
|
230
|
+
return sharedFixtures.runFixture(key, setup);
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Setup a resource once per feature file. It is isolated by feature URI and
|
|
234
|
+
* cleaned in AfterAll because cucumber-js has no reliable after-feature hook.
|
|
235
|
+
*/
|
|
236
|
+
featureFixture(key, setup) {
|
|
237
|
+
if (!this.featureUri) {
|
|
238
|
+
throw new Error("featureFixture is only available after the scenario Before hook");
|
|
239
|
+
}
|
|
240
|
+
return sharedFixtures.featureFixture(this.featureUri, key, setup);
|
|
241
|
+
}
|
|
65
242
|
/** Resolve runner userdata from worldParameters first, then DBX_TEST_USERDATA_* env. */
|
|
66
243
|
userdata(name) {
|
|
67
244
|
const configured = this.parameters.userdata?.[name];
|
|
@@ -94,8 +271,16 @@ var DatabricksWorld = class extends cucumber.World {
|
|
|
94
271
|
errors.push(error);
|
|
95
272
|
}
|
|
96
273
|
this.ctx = void 0;
|
|
274
|
+
this.scopedState?.clearScenario();
|
|
275
|
+
this.scopedState = void 0;
|
|
97
276
|
if (errors.length > 0) throw new AggregateError(errors, "Scenario cleanup failed");
|
|
98
277
|
}
|
|
278
|
+
state() {
|
|
279
|
+
if (!this.scopedState) {
|
|
280
|
+
throw new Error("BDD scoped state is only available after the scenario Before hook");
|
|
281
|
+
}
|
|
282
|
+
return this.scopedState;
|
|
283
|
+
}
|
|
99
284
|
};
|
|
100
285
|
|
|
101
286
|
// src/profile.ts
|
|
@@ -114,6 +299,68 @@ function liveOnlyReason(tags, profile) {
|
|
|
114
299
|
if (blocking.length === 0) return null;
|
|
115
300
|
return `requires a live workspace (${blocking.join(", ")}); running under DBX_TEST_PROFILE=local`;
|
|
116
301
|
}
|
|
302
|
+
function capabilitiesFromEnv(profile, env = process.env) {
|
|
303
|
+
const capabilities = { profile };
|
|
304
|
+
const builtins = [
|
|
305
|
+
["cloud", env.DBX_TEST_CLOUD],
|
|
306
|
+
["compute", env.DBX_TEST_COMPUTE_MODE ?? env.DBX_TEST_COMPUTE],
|
|
307
|
+
["stage", env.DBX_TEST_STAGE]
|
|
308
|
+
];
|
|
309
|
+
for (const [key, value] of builtins) {
|
|
310
|
+
if (value !== void 0 && value !== "") capabilities[key] = value;
|
|
311
|
+
}
|
|
312
|
+
for (const [name, value] of Object.entries(env)) {
|
|
313
|
+
if (!name.startsWith("DBX_TEST_CAPABILITY_") || value === void 0) continue;
|
|
314
|
+
capabilities[normalizeCapabilityKey(name.slice("DBX_TEST_CAPABILITY_".length))] = value;
|
|
315
|
+
}
|
|
316
|
+
return capabilities;
|
|
317
|
+
}
|
|
318
|
+
function capabilityTagReason(tags, capabilities) {
|
|
319
|
+
const normalized = new Map(
|
|
320
|
+
Object.entries(capabilities).map(([key, value]) => [
|
|
321
|
+
normalizeCapabilityKey(key),
|
|
322
|
+
String(value).toLowerCase()
|
|
323
|
+
])
|
|
324
|
+
);
|
|
325
|
+
for (const tag of tags) {
|
|
326
|
+
const predicate = parseCapabilityTag(tag);
|
|
327
|
+
if (!predicate) continue;
|
|
328
|
+
const actual = normalized.get(normalizeCapabilityKey(predicate.key));
|
|
329
|
+
const matches = predicate.expected ? actual === predicate.expected.toLowerCase() : actual !== void 0 && !["", "0", "false", "no", "off"].includes(actual);
|
|
330
|
+
if (predicate.kind === "requires" && !matches) {
|
|
331
|
+
return `${tag} requires capability ${predicate.key}${predicate.expected ? `=${predicate.expected}` : ""}; actual ${actual ?? "unset"}`;
|
|
332
|
+
}
|
|
333
|
+
if (predicate.kind === "excludes" && matches) {
|
|
334
|
+
return `${tag} excludes capability ${predicate.key}${predicate.expected ? `=${predicate.expected}` : ""}`;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
return null;
|
|
338
|
+
}
|
|
339
|
+
function scenarioSkipReason(tags, profile, env = process.env) {
|
|
340
|
+
return liveOnlyReason(tags, profile) ?? capabilityTagReason(tags, capabilitiesFromEnv(profile, env));
|
|
341
|
+
}
|
|
342
|
+
function parseCapabilityTag(tag) {
|
|
343
|
+
const direct = tag.match(/^@(requires|excludes)\.([^=]+)(?:=(.+))?$/i);
|
|
344
|
+
if (direct?.[1] && direct[2]) {
|
|
345
|
+
return {
|
|
346
|
+
kind: direct[1].toLowerCase(),
|
|
347
|
+
key: direct[2],
|
|
348
|
+
...direct[3] ? { expected: direct[3] } : {}
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
const behave = tag.match(/^@(use|not)\.with_([^=]+)=(.+)$/i);
|
|
352
|
+
if (behave?.[1] && behave[2] && behave[3]) {
|
|
353
|
+
return {
|
|
354
|
+
kind: behave[1].toLowerCase() === "use" ? "requires" : "excludes",
|
|
355
|
+
key: behave[2],
|
|
356
|
+
expected: behave[3]
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
return void 0;
|
|
360
|
+
}
|
|
361
|
+
function normalizeCapabilityKey(key) {
|
|
362
|
+
return key.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_");
|
|
363
|
+
}
|
|
117
364
|
|
|
118
365
|
// src/infer.ts
|
|
119
366
|
var INT_RE = /^-?\d+$/;
|
|
@@ -378,6 +625,25 @@ function renderChunks(chunks) {
|
|
|
378
625
|
return rendered.trimEnd();
|
|
379
626
|
}
|
|
380
627
|
|
|
628
|
+
// src/cardinality.ts
|
|
629
|
+
function parseCardinalityField(value, cardinality, transform, options = {}) {
|
|
630
|
+
const fieldName = options.fieldName ?? "field";
|
|
631
|
+
const trimmed = value.trim();
|
|
632
|
+
const items = trimmed ? trimmed.split(options.separator ?? /\s*,\s*/).map((item) => item.trim()) : [];
|
|
633
|
+
if (items.some((item) => !item)) {
|
|
634
|
+
throw new Error(`${fieldName} contains an empty value`);
|
|
635
|
+
}
|
|
636
|
+
if (cardinality === "?" && items.length > 1) {
|
|
637
|
+
throw new Error(`${fieldName} expects zero or one value, received ${items.length}`);
|
|
638
|
+
}
|
|
639
|
+
if (cardinality === "+" && items.length === 0) {
|
|
640
|
+
throw new Error(`${fieldName} expects one or more values`);
|
|
641
|
+
}
|
|
642
|
+
const parsed = items.map(transform);
|
|
643
|
+
if (cardinality === "?") return parsed[0];
|
|
644
|
+
return parsed;
|
|
645
|
+
}
|
|
646
|
+
|
|
381
647
|
Object.defineProperty(exports, "waitForPipelineUpdate", {
|
|
382
648
|
enumerable: true,
|
|
383
649
|
get: function () { return databricksTestkit.waitForPipelineUpdate; }
|
|
@@ -386,17 +652,28 @@ exports.DatabricksWorld = DatabricksWorld;
|
|
|
386
652
|
exports.FAILURE_EVIDENCE_MEDIA_TYPE = FAILURE_EVIDENCE_MEDIA_TYPE;
|
|
387
653
|
exports.LIVE_ONLY_TAGS = LIVE_ONLY_TAGS;
|
|
388
654
|
exports.RUN_STATES = RUN_STATES;
|
|
655
|
+
exports.ScopedState = ScopedState;
|
|
656
|
+
exports.SharedFixtureRegistry = SharedFixtureRegistry;
|
|
657
|
+
exports.SharedStateRegistry = SharedStateRegistry;
|
|
658
|
+
exports.capabilitiesFromEnv = capabilitiesFromEnv;
|
|
659
|
+
exports.capabilityTagReason = capabilityTagReason;
|
|
389
660
|
exports.coerceMatchRows = coerceMatchRows;
|
|
661
|
+
exports.defineAction = defineAction;
|
|
390
662
|
exports.inferFixture = inferFixture;
|
|
391
663
|
exports.liveOnlyReason = liveOnlyReason;
|
|
664
|
+
exports.parseCardinalityField = parseCardinalityField;
|
|
392
665
|
exports.parseDuration = parseDuration;
|
|
393
666
|
exports.parseFailureEvidenceAttachment = parseFailureEvidenceAttachment;
|
|
394
667
|
exports.parseTableIdentifier = parseTableIdentifier;
|
|
395
668
|
exports.redactSecrets = redactSecrets;
|
|
396
669
|
exports.resolveJobId = resolveJobId;
|
|
397
670
|
exports.resolvePipelineId = resolvePipelineId;
|
|
671
|
+
exports.runAction = runAction;
|
|
398
672
|
exports.runFeatures = runFeatures;
|
|
399
673
|
exports.runJobToTerminal = runJobToTerminal;
|
|
674
|
+
exports.scenarioSkipReason = scenarioSkipReason;
|
|
675
|
+
exports.sharedFixtures = sharedFixtures;
|
|
676
|
+
exports.sharedState = sharedState;
|
|
400
677
|
exports.startPipelineUpdate = startPipelineUpdate;
|
|
401
678
|
exports.startStepOutputCapture = startStepOutputCapture;
|
|
402
679
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/world.ts","../src/profile.ts","../src/infer.ts","../src/jobs.ts","../src/pipelines.ts","../src/run-features.ts","../src/parameter-types.ts","../src/evidence-formatter.ts","../src/output-capture.ts"],"names":["World","resolveProfile","createExecutionContext","waitForDatabricksRun","require","createRequire","join","dirname","execFile","format"],"mappings":";;;;;;;;;;;;AAuBO,IAAM,eAAA,GAAN,cAA8BA,cAAA,CAAiC;AAAA,EAC3D,OAAA;AAAA;AAAA,EAET,QAAA,GAA6C,IAAA;AAAA;AAAA,EAE7C,SAAA,GAA0B,IAAA;AAAA;AAAA,EAE1B,OAAA,GAA0C,IAAA;AAAA;AAAA,EAE1C,kBAAA,GAAsE,IAAA;AAAA,EACtE,cAAA;AAAA,EACA,eAAA;AAAA,EACA,OAAA;AAAA,EACA,eAAA;AAAA,EACA,iBAAA;AAAA,EACA,YAAA;AAAA,EAGQ,GAAA;AAAA,EACA,SAAA;AAAA,EACS,WAAsB,EAAC;AAAA,EAExC,YAAY,OAAA,EAAmD;AAC7D,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,UAAUC,gCAAA,EAAe;AAAA,EAChC;AAAA,EAEA,MAAM,OAAA,GAAqC;AACzC,IAAA,IAAI,IAAA,CAAK,SAAA,EAAW,OAAO,IAAA,CAAK,SAAA;AAChC,IAAA,IAAI,CAAC,KAAK,GAAA,EAAK;AACb,MAAA,MAAM,GAAA,GAAM,IAAA,CAAK,eAAA,GACb,EA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CAAe,MAAM,MAAM,CAAA;AAC3D,IAAA,OAAO,IAAA;AAAA,EACT,CAAA;AACF;AAEA,SAAS,cAAc,KAAA,EAAwB;AAC7C,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,EAAU,OAAO,KAAA;AACtC,EAAA,IAAI,OAAO,QAAA,CAAS,KAAK,GAAG,OAAO,KAAA,CAAM,SAAS,MAAM,CAAA;AACxD,EAAA,IAAI,KAAA,YAAiB,YAAY,OAAO,MAAA,CAAO,KAAK,KAAK,CAAA,CAAE,SAAS,MAAM,CAAA;AAC1E,EAAA,OAAO,OAAO,KAAK,CAAA;AACrB;AAEA,SAAS,YAAA,CAAa,OAAe,QAAA,EAA0B;AAC7D,EAAA,OAAO,MAAA,CAAO,IAAA,CAAK,KAAK,CAAA,CACrB,QAAA,CAAS,CAAA,EAAG,QAAQ,CAAA,CACpB,QAAA,CAAS,MAAM,CAAA,CACf,OAAA,CAAQ,YAAY,EAAE,CAAA;AAC3B;AAEA,SAAS,aAAa,MAAA,EAA0C;AAC9D,EAAA,IAAI,QAAA,GAAW,EAAA;AACf,EAAA,IAAI,QAAA;AACJ,EAAA,KAAA,MAAW,SAAS,MAAA,EAAQ;AAC1B,IAAA,IAAI,KAAA,CAAM,WAAW,QAAA,EAAU;AAC7B,MAAA,IAAI,YAAY,CAAC,QAAA,CAAS,QAAA,CAAS,IAAI,GAAG,QAAA,IAAY,IAAA;AACtD,MAAA,QAAA,IAAY,CAAA,CAAA,EAAI,MAAM,MAAM,CAAA;AAAA,CAAA;AAC5B,MAAA,QAAA,GAAW,KAAA,CAAM,MAAA;AAAA,IACnB;AACA,IAAA,QAAA,IAAY,KAAA,CAAM,IAAA;AAAA,EACpB;AACA,EAAA,OAAO,SAAS,OAAA,EAAQ;AAC1B","file":"index.cjs","sourcesContent":["import { type IWorldOptions, World } from '@cucumber/cucumber';\nimport {\n type ExecutionContext,\n type TestProfile,\n createExecutionContext,\n resolveProfile,\n} from '@fabricorg/databricks-testkit';\nimport type { StepOutputCapture } from './output-capture.js';\n\nexport interface DatabricksWorldParameters {\n /** Default schema for the execution context; overridable per scenario via the catalog/schema step. */\n schema?: string;\n /** Arbitrary typed runner configuration, comparable to behave `-D` userdata. */\n userdata?: Record<string, string | number | boolean>;\n}\n\ntype Cleanup = () => void | Promise<void>;\n\n/**\n * Cucumber World holding one ExecutionContext per scenario. The context is\n * created lazily on first use so `Given catalog ... and schema ...` can run\n * first; it is closed by the After hook registered in ./steps.ts.\n */\nexport class DatabricksWorld extends World<DatabricksWorldParameters> {\n readonly profile: TestProfile;\n /** Rows from the last `When I run the SQL` / `When I query table` step. */\n lastRows: Record<string, unknown>[] | null = null;\n /** Error captured from the last statement, for `Then the statement fails ...`. */\n lastError: Error | null = null;\n /** Terminal run record from the last `When I run job ...` step. */\n lastRun: Record<string, unknown> | null = null;\n /** Pipeline update handle from `When I start a full refresh of pipeline ...`. */\n lastPipelineUpdate: { pipelineId: string; updateId: string } | null = null;\n schemaOverride: string | undefined;\n catalogOverride: string | undefined;\n lastSql: string | undefined;\n lastStatementId: string | undefined;\n stepOutputCapture: StepOutputCapture | undefined;\n lakebasePool:\n | { query<T extends Record<string, unknown>>(sql: string): Promise<{ rows: T[] }> }\n | undefined;\n private ctx: ExecutionContext | undefined;\n private activeCtx: ExecutionContext | undefined;\n private readonly cleanups: Cleanup[] = [];\n\n constructor(options: IWorldOptions<DatabricksWorldParameters>) {\n super(options);\n this.profile = resolveProfile();\n }\n\n async context(): Promise<ExecutionContext> {\n if (this.activeCtx) return this.activeCtx;\n if (!this.ctx) {\n const env = this.catalogOverride\n ? { ...process.env, DBX_TEST_CATALOG: this.catalogOverride }\n : process.env;\n this.ctx = await createExecutionContext({\n profile: this.profile,\n env,\n schema: this.schemaOverride ?? this.parameters.schema,\n onStatement: ({ sql, statementId }) => {\n this.lastSql = sql;\n this.lastStatementId = statementId;\n },\n });\n }\n return this.ctx;\n }\n\n /** Route subsequent steps through a scenario-owned secondary identity. */\n useExecutionContext(context: ExecutionContext): void {\n if (this.activeCtx) throw new Error('A secondary execution context is already active');\n this.activeCtx = context;\n this.addCleanup(async () => {\n await context.close();\n this.activeCtx = undefined;\n });\n }\n\n /** Register scenario-scoped cleanup. Cleanups run in reverse order. */\n addCleanup(cleanup: Cleanup): void {\n this.cleanups.push(cleanup);\n }\n\n /** Resolve runner userdata from worldParameters first, then DBX_TEST_USERDATA_* env. */\n userdata(name: string): string | number | boolean | undefined {\n const configured = this.parameters.userdata?.[name];\n if (configured !== undefined) return configured;\n return process.env[`DBX_TEST_USERDATA_${name.replace(/[^A-Za-z0-9]/g, '_').toUpperCase()}`];\n }\n\n scopeTo(catalog: string, schema: string): void {\n if (this.ctx) {\n throw new Error(\n 'Given catalog/schema must run before any step that touches the warehouse in the scenario',\n );\n }\n // Feature files stay portable and readable with illustrative names. A live\n // runner may redirect every scenario into its provisioned scratch scope.\n this.catalogOverride =\n this.profile === 'live' ? (process.env.DBX_TEST_CATALOG ?? catalog) : catalog;\n this.schemaOverride =\n this.profile === 'live' ? (process.env.DBX_TEST_SCHEMA ?? schema) : schema;\n }\n\n async dispose(): Promise<void> {\n this.stepOutputCapture?.stop();\n this.stepOutputCapture = undefined;\n const errors: unknown[] = [];\n for (const cleanup of this.cleanups.splice(0).reverse()) {\n try {\n await cleanup();\n } catch (error) {\n errors.push(error);\n }\n }\n try {\n await this.ctx?.close();\n } catch (error) {\n errors.push(error);\n }\n this.ctx = undefined;\n if (errors.length > 0) throw new AggregateError(errors, 'Scenario cleanup failed');\n }\n}\n","import type { TestProfile } from '@fabricorg/databricks-testkit';\n\n/**\n * Tags that require a live workspace (or a long budget). Scenarios carrying\n * any of them are skipped under the `local` profile — see ADR-0006.\n */\nexport const LIVE_ONLY_TAGS = [\n '@live',\n '@jobs',\n '@dlt',\n '@pipeline',\n '@autoloader',\n '@lakebase',\n '@slow',\n] as const;\n\n/** Returns a skip reason when the scenario cannot run under the given profile, else null. */\nexport function liveOnlyReason(tags: readonly string[], profile: TestProfile): string | null {\n if (profile === 'live') return null;\n const blocking = tags.filter((t) => (LIVE_ONLY_TAGS as readonly string[]).includes(t));\n if (blocking.length === 0) return null;\n return `requires a live workspace (${blocking.join(', ')}); running under DBX_TEST_PROFILE=local`;\n}\n","import type { TableFixture } from '@fabricorg/databricks-testkit';\n\nconst INT_RE = /^-?\\d+$/;\nconst FLOAT_RE = /^-?\\d+\\.\\d+$/;\nconst TIMESTAMP_RE = /^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(:\\d{2})?/;\nconst BOOL_RE = /^(true|false)$/i;\n\n/**\n * Turn a Gherkin data table (header row + string cells) into a TableFixture,\n * inferring portable column types from the values: BIGINT, DOUBLE,\n * TIMESTAMP, BOOLEAN, else STRING. Empty cells become NULL.\n */\nexport function inferFixture(table: string, raw: readonly (readonly string[])[]): TableFixture {\n if (raw.length < 2) {\n throw new Error(`Data table for ${table} needs a header row and at least one data row`);\n }\n const [header, ...body] = raw as [readonly string[], ...(readonly string[])[]];\n const types = header.map((_, col) => inferColumnType(body.map((row) => row[col] ?? '')));\n const schema = header.map((name, i) => `\"${name}\" ${types[i]}`).join(', ');\n const rows = body.map((row) => row.map((cell, i) => coerceCell(cell, types[i] ?? 'STRING')));\n return { table, schema, rows };\n}\n\n/** Coerce data-table string cells to typed values for row matching (no header row). */\nexport function coerceMatchRows(raw: readonly (readonly string[])[]): Record<string, unknown>[] {\n if (raw.length < 2) {\n throw new Error('Match table needs a header row and at least one data row');\n }\n const [header, ...body] = raw as [readonly string[], ...(readonly string[])[]];\n return body.map((row) => {\n const out: Record<string, unknown> = {};\n header.forEach((name, i) => {\n out[name] = coerceCell(row[i] ?? '', inferColumnType([row[i] ?? '']));\n });\n return out;\n });\n}\n\nfunction inferColumnType(cells: readonly string[]): string {\n const present = cells.filter((c) => c !== '');\n if (present.length === 0) return 'STRING';\n if (present.every((c) => INT_RE.test(c))) return 'BIGINT';\n if (present.every((c) => FLOAT_RE.test(c) || INT_RE.test(c))) return 'DOUBLE';\n if (present.every((c) => TIMESTAMP_RE.test(c))) return 'TIMESTAMP';\n if (present.every((c) => BOOL_RE.test(c))) return 'BOOLEAN';\n return 'STRING';\n}\n\nfunction coerceCell(cell: string, type: string): unknown {\n if (cell === '') return null;\n if (type === 'BIGINT' || type === 'DOUBLE') return Number(cell);\n if (type === 'BOOLEAN') return /^true$/i.test(cell);\n return cell;\n}\n","import { type DatabricksRestClient, waitForDatabricksRun } from '@fabric-harness/databricks';\nimport type { WorkspaceClientLike } from '@fabricorg/databricks-testkit';\n\nexport interface RunJobOptions {\n pollIntervalMs?: number;\n timeoutMs?: number;\n}\n\nexport interface JobRunResult {\n runId: number;\n lifeCycleState: string;\n resultState: string;\n run: Record<string, unknown>;\n}\n\n/** Resolve a job by numeric id or by exact name via /api/2.1/jobs/list. */\nexport async function resolveJobId(client: WorkspaceClientLike, nameOrId: string): Promise<number> {\n if (/^\\d+$/.test(nameOrId)) return Number(nameOrId);\n const response = await client.get<{ jobs?: { job_id: number; settings?: { name?: string } }[] }>(\n '/api/2.1/jobs/list',\n { name: nameOrId },\n );\n const match = (response.jobs ?? []).find((j) => j.settings?.name === nameOrId);\n if (!match) throw new Error(`No Databricks job named '${nameOrId}' found`);\n return match.job_id;\n}\n\n/** run-now a job and poll its run to a terminal state. */\nexport async function runJobToTerminal(\n client: WorkspaceClientLike,\n nameOrId: string,\n options: RunJobOptions = {},\n): Promise<JobRunResult> {\n const jobId = await resolveJobId(client, nameOrId);\n const submitted = await client.post<{ run_id: number }>('/api/2.1/jobs/run-now', {\n job_id: jobId,\n });\n const run = await waitForDatabricksRun(client as DatabricksRestClient, submitted.run_id, {\n pollIntervalMs: options.pollIntervalMs,\n timeoutMs: options.timeoutMs,\n });\n const state = (run as { state?: { life_cycle_state?: string; result_state?: string } }).state;\n return {\n runId: submitted.run_id,\n lifeCycleState: state?.life_cycle_state ?? 'UNKNOWN',\n resultState: state?.result_state ?? 'UNKNOWN',\n run,\n };\n}\n","import {\n type PollOptions,\n type WorkspaceClientLike,\n waitForPipelineUpdate,\n} from '@fabricorg/databricks-testkit';\n\nexport type PipelineWaitOptions = PollOptions;\n\n/** Resolve a DLT/Lakeflow pipeline by id or exact name via /api/2.0/pipelines. */\nexport async function resolvePipelineId(\n client: WorkspaceClientLike,\n nameOrId: string,\n): Promise<string> {\n if (/^[0-9a-f]{8}-[0-9a-f-]{27,}$/i.test(nameOrId)) return nameOrId;\n const response = await client.get<{ statuses?: { pipeline_id: string; name?: string }[] }>(\n '/api/2.0/pipelines',\n { filter: `name LIKE '${nameOrId}'` },\n );\n const match = (response.statuses ?? []).find((p) => p.name === nameOrId);\n if (!match) throw new Error(`No Databricks pipeline named '${nameOrId}' found`);\n return match.pipeline_id;\n}\n\n/** Start a pipeline update; returns the update id to poll. */\nexport async function startPipelineUpdate(\n client: WorkspaceClientLike,\n pipelineId: string,\n options: { fullRefresh?: boolean } = {},\n): Promise<string> {\n const response = await client.post<{ update_id: string }>(\n `/api/2.0/pipelines/${encodeURIComponent(pipelineId)}/updates`,\n { full_refresh: options.fullRefresh ?? false },\n );\n return response.update_id;\n}\n\n/** Poll an update to a terminal state; throws on timeout or non-COMPLETED terminal states. */\nexport { waitForPipelineUpdate };\n","import { execFile } from 'node:child_process';\nimport { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\n\nexport interface RunFeaturesOptions {\n /** Directory containing the cucumber config / features. */\n cwd: string;\n /** Extra CLI args, e.g. ['--tags', 'not @slow'] or ['features/foo.feature']. */\n args?: string[];\n /** Extra environment (merged over process.env). */\n env?: Record<string, string>;\n /** Load TypeScript support code via tsx (default true). */\n tsx?: boolean;\n timeoutMs?: number;\n}\n\nexport interface RunFeaturesResult {\n success: boolean;\n exitCode: number;\n output: string;\n}\n\n/**\n * Vitest bridge: run cucumber-js as a subprocess so feature suites can be\n * embedded in an existing vitest run (one CI entry point) without fighting\n * over cucumber's global step registry or vitest's module transforms.\n */\nexport async function runFeatures(options: RunFeaturesOptions): Promise<RunFeaturesResult> {\n const require = createRequire(import.meta.url);\n // The bin path is not in the package's exports map — resolve it relative\n // to package.json (which is exported).\n const pkgPath = require.resolve('@cucumber/cucumber/package.json');\n const pkg = require(pkgPath) as { bin: Record<string, string> };\n const bin = join(dirname(pkgPath), pkg.bin['cucumber-js'] ?? 'bin/cucumber.js');\n const env: NodeJS.ProcessEnv = { ...process.env, ...options.env };\n if (options.tsx ?? true) {\n const tsxImport = '--import tsx';\n env.NODE_OPTIONS = env.NODE_OPTIONS ? `${env.NODE_OPTIONS} ${tsxImport}` : tsxImport;\n }\n return new Promise((resolve) => {\n execFile(\n process.execPath,\n [bin, ...(options.args ?? [])],\n { cwd: options.cwd, env, timeout: options.timeoutMs ?? 120_000, maxBuffer: 16 * 1024 * 1024 },\n (error, stdout, stderr) => {\n const exitCode =\n error && typeof (error as { code?: unknown }).code === 'number'\n ? ((error as { code?: number }).code ?? 1)\n : error\n ? 1\n : 0;\n resolve({ success: exitCode === 0, exitCode, output: `${stdout}\\n${stderr}` });\n },\n );\n });\n}\n","import { defineParameterType } from '@cucumber/cucumber';\n\nexport const RUN_STATES = ['SUCCESS', 'FAILED', 'CANCELED', 'TIMEDOUT'] as const;\nexport type RunState = (typeof RUN_STATES)[number];\n\nexport function parseDuration(value: string): number {\n const match = value.trim().match(/^(\\d+(?:\\.\\d+)?)\\s*(milliseconds?|ms|seconds?|s|minutes?|m)$/i);\n if (!match) throw new Error(`Invalid duration '${value}'`);\n const amount = Number(match[1]);\n const unit = match[2]?.toLowerCase() ?? '';\n if (unit === 'ms' || unit.startsWith('millisecond')) return amount;\n if (unit === 's' || unit.startsWith('second')) return amount * 1_000;\n return amount * 60_000;\n}\n\nexport function parseTableIdentifier(value: string): string {\n const identifier = value.trim();\n const part = '(?:[A-Za-z_][A-Za-z0-9_]*|`[^`]+`)';\n if (!new RegExp(`^${part}(?:\\\\.${part}){0,2}$`).test(identifier)) {\n throw new Error(`Invalid 1-3 part table identifier '${value}'`);\n }\n return identifier;\n}\n\nexport function registerParameterTypes(): void {\n defineParameterType({\n name: 'runState',\n regexp: /SUCCESS|FAILED|CANCELED|TIMEDOUT/,\n transformer: (value: string): RunState => value as RunState,\n });\n\n defineParameterType({\n name: 'duration',\n regexp: /\\d+(?:\\.\\d+)?\\s*(?:milliseconds?|ms|seconds?|s|minutes?|m)/,\n transformer: parseDuration,\n });\n\n defineParameterType({\n name: 'table',\n regexp: /(?:[A-Za-z_][A-Za-z0-9_]*|`[^`]+`)(?:\\.(?:[A-Za-z_][A-Za-z0-9_]*|`[^`]+`)){0,2}/,\n transformer: parseTableIdentifier,\n });\n}\n","import { Formatter, type IFormatterOptions } from '@cucumber/cucumber';\n\n/**\n * Evidence formatter: schema-versioned, secret-redacted JSON summary of a\n * BDD run, shared in spirit with the live check runner's evidence output so\n * nightly runs double as audit artifacts. Wire it up in cucumber config:\n *\n * format: [['@fabricorg/databricks-bdd/evidence-formatter', 'reports/evidence.json']]\n */\nexport interface EvidenceScenario {\n name: string;\n uri: string;\n tags: string[];\n status: string;\n durationMs: number;\n error?: string;\n failures?: StepFailureEvidence[];\n}\n\nexport interface StepFailureEvidence {\n step: string;\n statementId?: string;\n sql?: string;\n output?: string;\n outputBytes?: number;\n outputTruncated?: boolean;\n}\n\nexport interface EvidenceReport {\n schemaVersion: 2;\n kind: 'databricks-bdd';\n profile: string;\n finishedAt: string;\n success: boolean;\n summary: Record<string, number>;\n scenarios: EvidenceScenario[];\n}\n\ninterface Envelope {\n attachment?: {\n body: string;\n contentEncoding: 'IDENTITY' | 'BASE64';\n mediaType: string;\n testCaseStartedId?: string;\n };\n pickle?: { id: string; name: string; uri: string; tags?: { name: string }[] };\n testCase?: { id: string; pickleId: string };\n testCaseStarted?: { id: string; testCaseId: string };\n testStepFinished?: {\n testCaseStartedId: string;\n testStepResult: {\n status: string;\n message?: string;\n duration?: { seconds: number; nanos: number };\n };\n };\n testRunFinished?: { success?: boolean; timestamp?: { seconds: number; nanos: number } };\n}\n\nexport const FAILURE_EVIDENCE_MEDIA_TYPE = 'application/vnd.fabric.databricks-bdd.failure+json';\n\nconst STATUS_RANK = ['UNKNOWN', 'PASSED', 'SKIPPED', 'PENDING', 'UNDEFINED', 'AMBIGUOUS', 'FAILED'];\n\nexport default class EvidenceFormatter extends Formatter {\n private readonly pickles = new Map<string, NonNullable<Envelope['pickle']>>();\n private readonly testCases = new Map<string, string>(); // testCaseId → pickleId\n private readonly attempts = new Map<\n string,\n {\n pickleId: string;\n status: string;\n durationMs: number;\n error?: string;\n failures: StepFailureEvidence[];\n }\n >();\n\n constructor(options: IFormatterOptions) {\n super(options);\n options.eventBroadcaster.on('envelope', (envelope: Envelope) => this.onEnvelope(envelope));\n }\n\n private onEnvelope(envelope: Envelope): void {\n if (envelope.pickle) this.pickles.set(envelope.pickle.id, envelope.pickle);\n if (envelope.testCase) this.testCases.set(envelope.testCase.id, envelope.testCase.pickleId);\n if (envelope.testCaseStarted) {\n this.attempts.set(envelope.testCaseStarted.id, {\n pickleId: this.testCases.get(envelope.testCaseStarted.testCaseId) ?? '',\n status: 'UNKNOWN',\n durationMs: 0,\n failures: [],\n });\n }\n if (envelope.attachment?.testCaseStartedId) {\n const attempt = this.attempts.get(envelope.attachment.testCaseStartedId);\n const failure = parseFailureEvidenceAttachment(envelope.attachment);\n if (attempt && failure) attempt.failures.push(failure);\n }\n if (envelope.testStepFinished) {\n const attempt = this.attempts.get(envelope.testStepFinished.testCaseStartedId);\n if (attempt) {\n const result = envelope.testStepFinished.testStepResult;\n if (STATUS_RANK.indexOf(result.status) > STATUS_RANK.indexOf(attempt.status)) {\n attempt.status = result.status;\n if (result.message) attempt.error = redactSecrets(result.message);\n }\n const d = result.duration;\n if (d) attempt.durationMs += d.seconds * 1000 + d.nanos / 1e6;\n }\n }\n if (envelope.testRunFinished) this.finish(envelope.testRunFinished);\n }\n\n private finish(finished: NonNullable<Envelope['testRunFinished']>): void {\n const scenarios: EvidenceScenario[] = [];\n const summary: Record<string, number> = {};\n for (const attempt of this.attempts.values()) {\n const pickle = this.pickles.get(attempt.pickleId);\n const status = attempt.status.toLowerCase();\n summary[status] = (summary[status] ?? 0) + 1;\n scenarios.push({\n name: pickle?.name ?? attempt.pickleId,\n uri: pickle?.uri ?? '',\n tags: (pickle?.tags ?? []).map((t) => t.name),\n status,\n durationMs: Math.round(attempt.durationMs),\n ...(attempt.error ? { error: attempt.error } : {}),\n ...(attempt.failures.length > 0 ? { failures: attempt.failures } : {}),\n });\n }\n const report: EvidenceReport = {\n schemaVersion: 2,\n kind: 'databricks-bdd',\n profile: process.env.DBX_TEST_PROFILE ?? 'local',\n finishedAt: new Date().toISOString(),\n success: finished.success ?? !scenarios.some((s) => s.status === 'failed'),\n summary,\n scenarios,\n };\n this.log(`${JSON.stringify(report, null, 2)}\\n`);\n }\n}\n\n/** Decode the structured attachment emitted by the failure hook. */\nexport function parseFailureEvidenceAttachment(\n attachment: NonNullable<Envelope['attachment']>,\n): StepFailureEvidence | null {\n if (attachment.mediaType !== FAILURE_EVIDENCE_MEDIA_TYPE) return null;\n try {\n const body =\n attachment.contentEncoding === 'BASE64'\n ? Buffer.from(attachment.body, 'base64').toString('utf8')\n : attachment.body;\n const parsed = JSON.parse(redactSecrets(body)) as Partial<StepFailureEvidence>;\n if (typeof parsed.step !== 'string') return null;\n return {\n step: parsed.step,\n ...(typeof parsed.statementId === 'string' ? { statementId: parsed.statementId } : {}),\n ...(typeof parsed.sql === 'string' ? { sql: parsed.sql } : {}),\n ...(typeof parsed.output === 'string' ? { output: parsed.output } : {}),\n ...(typeof parsed.outputBytes === 'number' ? { outputBytes: parsed.outputBytes } : {}),\n ...(typeof parsed.outputTruncated === 'boolean'\n ? { outputTruncated: parsed.outputTruncated }\n : {}),\n };\n } catch {\n return null;\n }\n}\n\nconst SECRET_ENV_RE = /(TOKEN|SECRET|PASSWORD|BEARER|KEY)/;\n\n/** Replace values of secret-looking env vars anywhere they appear in text. */\nexport function redactSecrets(\n text: string,\n env: Record<string, string | undefined> = process.env,\n): string {\n let out = text;\n for (const [name, value] of Object.entries(env)) {\n if (!value || value.length < 6) continue;\n if (!SECRET_ENV_RE.test(name)) continue;\n out = out.split(value).join('[REDACTED]');\n }\n return out;\n}\n","import type { Writable } from 'node:stream';\nimport { format } from 'node:util';\n\nexport type CapturedStream = 'stdout' | 'stderr';\n\nexport interface CapturedStepOutput {\n /** Ordered stdout/stderr output with stream labels. */\n text: string;\n /** True when output exceeded the configured byte budget. */\n truncated: boolean;\n /** Total bytes emitted before truncation. */\n totalBytes: number;\n}\n\nexport interface StepOutputCapture {\n stop(): CapturedStepOutput;\n}\n\nexport interface StepOutputCaptureOptions {\n /** Maximum UTF-8 bytes retained for one step. Defaults to 32 KiB. */\n maxBytes?: number;\n /** Forward output while capturing. Defaults to false, matching Behave capture semantics. */\n passthrough?: boolean;\n}\n\ninterface CapturedChunk {\n stream: CapturedStream;\n text: string;\n}\n\ntype Write = Writable['write'];\ntype ConsoleMethod = 'debug' | 'error' | 'info' | 'log' | 'warn';\n\nconst DEFAULT_MAX_BYTES = 32 * 1024;\n\n/**\n * Capture process stdout/stderr until stop() is called. Console output and\n * Pino's standard destination both flow through these streams. Child\n * processes that inherit the OS file descriptors directly are intentionally\n * outside this in-process capture boundary.\n */\nexport function startStepOutputCapture(options: StepOutputCaptureOptions = {}): StepOutputCapture {\n const maxBytes = Math.max(0, options.maxBytes ?? DEFAULT_MAX_BYTES);\n const stdout = process.stdout;\n const stderr = process.stderr;\n const originalStdoutWrite = stdout.write;\n const originalStderrWrite = stderr.write;\n const originalConsole = Object.fromEntries(\n (['debug', 'error', 'info', 'log', 'warn'] as const).map((method) => [method, console[method]]),\n ) as Record<ConsoleMethod, typeof console.log>;\n const chunks: CapturedChunk[] = [];\n let retainedBytes = 0;\n let totalBytes = 0;\n let stopped = false;\n\n const capture = (stream: CapturedStream, chunk: unknown): void => {\n const text = chunkToString(chunk);\n const bytes = Buffer.byteLength(text);\n totalBytes += bytes;\n const remaining = maxBytes - retainedBytes;\n if (remaining <= 0 || bytes === 0) return;\n const retained = bytes <= remaining ? text : truncateUtf8(text, remaining);\n retainedBytes += Buffer.byteLength(retained);\n if (retained) chunks.push({ stream, text: retained });\n };\n\n stdout.write = interceptedWrite(\n stdout,\n 'stdout',\n originalStdoutWrite,\n capture,\n options.passthrough,\n );\n stderr.write = interceptedWrite(\n stderr,\n 'stderr',\n originalStderrWrite,\n capture,\n options.passthrough,\n );\n if (!options.passthrough) {\n for (const method of ['debug', 'info', 'log'] as const) {\n console[method] = (...args: unknown[]) => capture('stdout', `${format(...args)}\\n`);\n }\n for (const method of ['error', 'warn'] as const) {\n console[method] = (...args: unknown[]) => capture('stderr', `${format(...args)}\\n`);\n }\n }\n\n return {\n stop(): CapturedStepOutput {\n if (!stopped) {\n stdout.write = originalStdoutWrite;\n stderr.write = originalStderrWrite;\n for (const method of Object.keys(originalConsole) as ConsoleMethod[]) {\n console[method] = originalConsole[method];\n }\n stopped = true;\n }\n return {\n text: renderChunks(chunks),\n truncated: totalBytes > retainedBytes,\n totalBytes,\n };\n },\n };\n}\n\nfunction interceptedWrite(\n destination: Writable,\n stream: CapturedStream,\n original: Write,\n capture: (stream: CapturedStream, chunk: unknown) => void,\n passthrough = false,\n): Write {\n return function write(chunk: unknown, encodingOrCallback?: unknown, callback?: unknown): boolean {\n capture(stream, chunk);\n if (passthrough) {\n return original.call(\n destination,\n chunk as never,\n encodingOrCallback as never,\n callback as never,\n );\n }\n const done = typeof encodingOrCallback === 'function' ? encodingOrCallback : callback;\n if (typeof done === 'function') queueMicrotask(() => done());\n return true;\n } as Write;\n}\n\nfunction chunkToString(chunk: unknown): string {\n if (typeof chunk === 'string') return chunk;\n if (Buffer.isBuffer(chunk)) return chunk.toString('utf8');\n if (chunk instanceof Uint8Array) return Buffer.from(chunk).toString('utf8');\n return String(chunk);\n}\n\nfunction truncateUtf8(value: string, maxBytes: number): string {\n return Buffer.from(value)\n .subarray(0, maxBytes)\n .toString('utf8')\n .replace(/\\uFFFD$/u, '');\n}\n\nfunction renderChunks(chunks: readonly CapturedChunk[]): string {\n let rendered = '';\n let previous: CapturedStream | undefined;\n for (const chunk of chunks) {\n if (chunk.stream !== previous) {\n if (rendered && !rendered.endsWith('\\n')) rendered += '\\n';\n rendered += `[${chunk.stream}]\\n`;\n previous = chunk.stream;\n }\n rendered += chunk.text;\n }\n return rendered.trimEnd();\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/actions.ts","../src/fixtures.ts","../src/scoped-state.ts","../src/world.ts","../src/profile.ts","../src/infer.ts","../src/jobs.ts","../src/pipelines.ts","../src/run-features.ts","../src/parameter-types.ts","../src/evidence-formatter.ts","../src/output-capture.ts","../src/cardinality.ts"],"names":["World","resolveProfile","createExecutionContext","waitForDatabricksRun","require","createRequire","join","dirname","execFile","format"],"mappings":";;;;;;;;;;;;;;AAeO,SAAS,aACd,MAAA,EAC8B;AAC9B,EAAA,OAAO,MAAA;AACT;AAGA,eAAsB,SAAA,CACpB,KAAA,EACA,MAAA,EAAA,GACG,IAAA,EACuB;AAC1B,EAAA,OAAQ,MAAM,MAAA,CAAO,KAAA,EAAO,GAAG,IAAI,CAAA;AACrC;;;ACDA,SAAS,gBAAmB,KAAA,EAG1B;AACA,EAAA,OACE,OAAO,KAAA,KAAU,QAAA,IACjB,KAAA,KAAU,QACV,MAAA,CAAO,SAAA,CAAU,cAAA,CAAe,IAAA,CAAK,KAAA,EAAO,OAAO,CAAA,IACnD,OAAQ,MAAgC,OAAA,KAAY,UAAA;AAExD;AAEO,IAAM,wBAAN,MAA4B;AAAA,EAChB,UAAA,uBAAiB,GAAA,EAA0B;AAAA,EAC3C,cAAA,uBAAqB,GAAA,EAAuC;AAAA,EAC5D,eAA+B,EAAC;AAAA,EAEjD,UAAA,CAAc,KAAa,KAAA,EAAoC;AAC7D,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,IAAA,CAAK,UAAA,EAAY,KAAK,KAAK,CAAA;AAAA,EACjD;AAAA,EAEA,cAAA,CAAkB,UAAA,EAAoB,GAAA,EAAa,KA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AAG,SAAS,CAAA,2BAAA,CAA6B,CAAA;AAAA,EAC3D;AAEA,EAAA,MAAM,MAAA,GAAS,KAAA,CAAM,GAAA,CAAI,SAAS,CAAA;AAClC,EAAA,IAAI,WAAA,KAAgB,GAAA,EAAK,OAAO,MAAA,CAAO,CAAC,CAAA;AACxC,EAAA,OAAO,MAAA;AACT","file":"index.cjs","sourcesContent":["import type { DatabricksWorld } from './world.js';\n\n/**\n * A reusable, typed scenario action.\n *\n * Behave suites sometimes compose behavior with `context.execute_steps()`. In\n * TypeScript, composing ordinary functions preserves type checking, stack\n * traces, and direct unit-testability without reparsing Gherkin at runtime.\n */\nexport type ScenarioAction<Args extends readonly unknown[] = readonly unknown[], Result = void> = (\n world: DatabricksWorld,\n ...args: Args\n) => Result | Promise<Result>;\n\n/** Preserve inference while declaring a reusable scenario action. */\nexport function defineAction<Args extends readonly unknown[], Result>(\n action: ScenarioAction<Args, Result>,\n): ScenarioAction<Args, Result> {\n return action;\n}\n\n/** Execute a typed action against the current scenario World. */\nexport async function runAction<Args extends readonly unknown[], Result>(\n world: DatabricksWorld,\n action: ScenarioAction<Args, Result>,\n ...args: Args\n): Promise<Awaited<Result>> {\n return (await action(world, ...args)) as Awaited<Result>;\n}\n","/**\n * Behave-style shared fixtures for expensive Databricks resources.\n *\n * Cucumber Worlds are scenario-scoped. These registries provide the two\n * broader scopes users commonly need when migrating Behave suites:\n *\n * - runFixture: setup once for the entire Cucumber run;\n * - featureFixture: setup once per feature URI.\n *\n * Both scopes are drained by the package AfterAll hook. Deferring feature\n * cleanup until AfterAll is intentional: cucumber-js may interleave scenarios\n * and does not expose an after-feature hook. The resource is still isolated by\n * feature URI and is never reused by another feature.\n */\n\nexport type FixtureCleanup = () => void | Promise<void>;\nexport type FixtureSetup<T> = () =>\n | T\n | Promise<T>\n | { value: T; cleanup: FixtureCleanup }\n | Promise<{ value: T; cleanup: FixtureCleanup }>;\n\ninterface FixtureEntry<T = unknown> {\n value: Promise<T>;\n cleanup?: FixtureCleanup;\n}\n\nfunction isFixtureResult<T>(value: T | { value: T; cleanup: FixtureCleanup }): value is {\n value: T;\n cleanup: FixtureCleanup;\n} {\n return (\n typeof value === 'object' &&\n value !== null &&\n Object.prototype.hasOwnProperty.call(value, 'value') &&\n typeof (value as { cleanup?: unknown }).cleanup === 'function'\n );\n}\n\nexport class SharedFixtureRegistry {\n private readonly runEntries = new Map<string, FixtureEntry>();\n private readonly featureEntries = new Map<string, Map<string, FixtureEntry>>();\n private readonly cleanupOrder: FixtureEntry[] = [];\n\n runFixture<T>(key: string, setup: FixtureSetup<T>): Promise<T> {\n return this.resolve(this.runEntries, key, setup);\n }\n\n featureFixture<T>(featureUri: string, key: string, setup: FixtureSetup<T>): Promise<T> {\n if (!featureUri) throw new Error('featureFixture requires a feature URI');\n let feature = this.featureEntries.get(featureUri);\n if (!feature) {\n feature = new Map();\n this.featureEntries.set(featureUri, feature);\n }\n return this.resolve(feature, key, setup);\n }\n\n private resolve<T>(entries: Map<string, FixtureEntry>, key: string, setup: FixtureSetup<T>) {\n if (!key.trim()) throw new Error('Fixture key must not be empty');\n const existing = entries.get(key);\n if (existing) return existing.value as Promise<T>;\n\n const entry: FixtureEntry<T> = {\n value: Promise.resolve()\n .then(setup)\n .then((result) => {\n if (isFixtureResult(result)) {\n entry.cleanup = result.cleanup;\n return result.value;\n }\n return result;\n })\n .catch((error) => {\n entries.delete(key);\n const index = this.cleanupOrder.indexOf(entry);\n if (index >= 0) this.cleanupOrder.splice(index, 1);\n throw error;\n }),\n };\n entries.set(key, entry);\n this.cleanupOrder.push(entry);\n return entry.value;\n }\n\n async dispose(): Promise<void> {\n const errors: unknown[] = [];\n for (const entry of this.cleanupOrder.splice(0).reverse()) {\n try {\n // Ensure setup has settled before attempting its cleanup.\n await entry.value.catch(() => undefined);\n await entry.cleanup?.();\n } catch (error) {\n errors.push(error);\n }\n }\n this.runEntries.clear();\n this.featureEntries.clear();\n if (errors.length > 0) throw new AggregateError(errors, 'Shared fixture cleanup failed');\n }\n}\n\nexport const sharedFixtures = new SharedFixtureRegistry();\n","export type StateScope = 'run' | 'feature' | 'scenario';\n\ntype StateValues = Map<string, unknown>;\n\n/**\n * Process-local state backing Behave-style run and feature context layers.\n * Scenario values stay on the scenario World and are never shared.\n */\nexport class SharedStateRegistry {\n private readonly runValues: StateValues = new Map();\n private readonly featureValues = new Map<string, StateValues>();\n\n run(): StateValues {\n return this.runValues;\n }\n\n feature(featureUri: string): StateValues {\n if (!featureUri) throw new Error('Feature state requires a feature URI');\n let values = this.featureValues.get(featureUri);\n if (!values) {\n values = new Map();\n this.featureValues.set(featureUri, values);\n }\n return values;\n }\n\n clear(): void {\n this.runValues.clear();\n this.featureValues.clear();\n }\n}\n\n/** Layered state lookup: scenario overrides feature, which overrides run. */\nexport class ScopedState {\n private readonly scenarioValues: StateValues = new Map();\n\n constructor(\n private readonly runValues: StateValues,\n private readonly featureValues: StateValues,\n ) {}\n\n set<T>(scope: StateScope, key: string, value: T): T {\n this.values(scope).set(validateKey(key), value);\n return value;\n }\n\n get<T>(key: string): T | undefined {\n const validKey = validateKey(key);\n if (this.scenarioValues.has(validKey)) return this.scenarioValues.get(validKey) as T;\n if (this.featureValues.has(validKey)) return this.featureValues.get(validKey) as T;\n return this.runValues.get(validKey) as T | undefined;\n }\n\n require<T>(key: string): T {\n const value = this.get<T>(key);\n if (value === undefined) throw new Error(`Required BDD state '${key}' is not set`);\n return value;\n }\n\n has(key: string): boolean {\n const validKey = validateKey(key);\n return (\n this.scenarioValues.has(validKey) ||\n this.featureValues.has(validKey) ||\n this.runValues.has(validKey)\n );\n }\n\n delete(scope: StateScope, key: string): boolean {\n return this.values(scope).delete(validateKey(key));\n }\n\n clearScenario(): void {\n this.scenarioValues.clear();\n }\n\n private values(scope: StateScope): StateValues {\n if (scope === 'run') return this.runValues;\n if (scope === 'feature') return this.featureValues;\n return this.scenarioValues;\n }\n}\n\nfunction validateKey(key: string): string {\n const trimmed = key.trim();\n if (!trimmed) throw new Error('BDD state key must not be empty');\n return trimmed;\n}\n\nexport const sharedState = new SharedStateRegistry();\n","import { type IWorldOptions, World } from '@cucumber/cucumber';\nimport {\n type ExecutionContext,\n type TestProfile,\n createExecutionContext,\n resolveProfile,\n} from '@fabricorg/databricks-testkit';\nimport { type ScenarioAction, runAction as executeAction } from './actions.js';\nimport { type FixtureSetup, sharedFixtures } from './fixtures.js';\nimport type { StepOutputCapture } from './output-capture.js';\nimport { ScopedState, type StateScope, sharedState } from './scoped-state.js';\n\nexport interface DatabricksWorldParameters {\n /** Default schema for the execution context; overridable per scenario via the catalog/schema step. */\n schema?: string;\n /** Arbitrary typed runner configuration, comparable to behave `-D` userdata. */\n userdata?: Record<string, string | number | boolean>;\n}\n\ntype Cleanup = () => void | Promise<void>;\n\n/**\n * Cucumber World holding one ExecutionContext per scenario. The context is\n * created lazily on first use so `Given catalog ... and schema ...` can run\n * first; it is closed by the After hook registered in ./steps.ts.\n */\nexport class DatabricksWorld extends World<DatabricksWorldParameters> {\n readonly profile: TestProfile;\n /** Rows from the last `When I run the SQL` / `When I query table` step. */\n lastRows: Record<string, unknown>[] | null = null;\n /** Error captured from the last statement, for `Then the statement fails ...`. */\n lastError: Error | null = null;\n /** Terminal run record from the last `When I run job ...` step. */\n lastRun: Record<string, unknown> | null = null;\n /** Pipeline update handle from `When I start a full refresh of pipeline ...`. */\n lastPipelineUpdate: { pipelineId: string; updateId: string } | null = null;\n schemaOverride: string | undefined;\n catalogOverride: string | undefined;\n lastSql: string | undefined;\n lastStatementId: string | undefined;\n featureUri: string | undefined;\n scenarioName: string | undefined;\n effectiveTags: readonly string[] = [];\n stepOutputCapture: StepOutputCapture | undefined;\n lakebasePool:\n | { query<T extends Record<string, unknown>>(sql: string): Promise<{ rows: T[] }> }\n | undefined;\n private ctx: ExecutionContext | undefined;\n private activeCtx: ExecutionContext | undefined;\n private scopedState: ScopedState | undefined;\n private readonly cleanups: Cleanup[] = [];\n\n constructor(options: IWorldOptions<DatabricksWorldParameters>) {\n super(options);\n this.profile = resolveProfile();\n }\n\n async context(): Promise<ExecutionContext> {\n if (this.activeCtx) return this.activeCtx;\n if (!this.ctx) {\n const env = this.catalogOverride\n ? { ...process.env, DBX_TEST_CATALOG: this.catalogOverride }\n : process.env;\n this.ctx = await createExecutionContext({\n profile: this.profile,\n env,\n schema: this.schemaOverride ?? this.parameters.schema,\n onStatement: ({ sql, statementId }) => {\n this.lastSql = sql;\n this.lastStatementId = statementId;\n },\n });\n }\n return this.ctx;\n }\n\n /** Route subsequent steps through a scenario-owned secondary identity. */\n useExecutionContext(context: ExecutionContext): void {\n if (this.activeCtx) throw new Error('A secondary execution context is already active');\n this.activeCtx = context;\n this.addCleanup(async () => {\n await context.close();\n this.activeCtx = undefined;\n });\n }\n\n /** Register scenario-scoped cleanup. Cleanups run in reverse order. */\n addCleanup(cleanup: Cleanup): void {\n this.cleanups.push(cleanup);\n }\n\n /** Initialize Behave-style feature/scenario metadata and layered state. */\n initializeScenario(featureUri: string, scenarioName: string, tags: readonly string[]): void {\n this.featureUri = featureUri;\n this.scenarioName = scenarioName;\n this.effectiveTags = [...tags];\n this.scopedState = new ScopedState(sharedState.run(), sharedState.feature(featureUri));\n }\n\n /** Set typed state at run, feature, or scenario scope. */\n setState<T>(scope: StateScope, key: string, value: T): T {\n return this.state().set(scope, key, value);\n }\n\n /** Resolve state using scenario → feature → run precedence. */\n getState<T>(key: string): T | undefined {\n return this.state().get<T>(key);\n }\n\n /** Resolve required layered state or fail with a useful message. */\n requireState<T>(key: string): T {\n return this.state().require<T>(key);\n }\n\n /** Compose a reusable typed action without reparsing textual Gherkin. */\n runAction<Args extends readonly unknown[], Result>(\n action: ScenarioAction<Args, Result>,\n ...args: Args\n ): Promise<Awaited<Result>> {\n return executeAction(this, action, ...args);\n }\n\n /** Setup a resource once for this Cucumber run and clean it up in AfterAll. */\n runFixture<T>(key: string, setup: FixtureSetup<T>): Promise<T> {\n return sharedFixtures.runFixture(key, setup);\n }\n\n /**\n * Setup a resource once per feature file. It is isolated by feature URI and\n * cleaned in AfterAll because cucumber-js has no reliable after-feature hook.\n */\n featureFixture<T>(key: string, setup: FixtureSetup<T>): Promise<T> {\n if (!this.featureUri) {\n throw new Error('featureFixture is only available after the scenario Before hook');\n }\n return sharedFixtures.featureFixture(this.featureUri, key, setup);\n }\n\n /** Resolve runner userdata from worldParameters first, then DBX_TEST_USERDATA_* env. */\n userdata(name: string): string | number | boolean | undefined {\n const configured = this.parameters.userdata?.[name];\n if (configured !== undefined) return configured;\n return process.env[`DBX_TEST_USERDATA_${name.replace(/[^A-Za-z0-9]/g, '_').toUpperCase()}`];\n }\n\n scopeTo(catalog: string, schema: string): void {\n if (this.ctx) {\n throw new Error(\n 'Given catalog/schema must run before any step that touches the warehouse in the scenario',\n );\n }\n // Feature files stay portable and readable with illustrative names. A live\n // runner may redirect every scenario into its provisioned scratch scope.\n this.catalogOverride =\n this.profile === 'live' ? (process.env.DBX_TEST_CATALOG ?? catalog) : catalog;\n this.schemaOverride =\n this.profile === 'live' ? (process.env.DBX_TEST_SCHEMA ?? schema) : schema;\n }\n\n async dispose(): Promise<void> {\n this.stepOutputCapture?.stop();\n this.stepOutputCapture = undefined;\n const errors: unknown[] = [];\n for (const cleanup of this.cleanups.splice(0).reverse()) {\n try {\n await cleanup();\n } catch (error) {\n errors.push(error);\n }\n }\n try {\n await this.ctx?.close();\n } catch (error) {\n errors.push(error);\n }\n this.ctx = undefined;\n this.scopedState?.clearScenario();\n this.scopedState = undefined;\n if (errors.length > 0) throw new AggregateError(errors, 'Scenario cleanup failed');\n }\n\n private state(): ScopedState {\n if (!this.scopedState) {\n throw new Error('BDD scoped state is only available after the scenario Before hook');\n }\n return this.scopedState;\n }\n}\n","import type { TestProfile } from '@fabricorg/databricks-testkit';\n\n/**\n * Tags that require a live workspace (or a long budget). Scenarios carrying\n * any of them are skipped under the `local` profile — see ADR-0006.\n */\nexport const LIVE_ONLY_TAGS = [\n '@live',\n '@jobs',\n '@dlt',\n '@pipeline',\n '@autoloader',\n '@lakebase',\n '@slow',\n] as const;\n\n/** Returns a skip reason when the scenario cannot run under the given profile, else null. */\nexport function liveOnlyReason(tags: readonly string[], profile: TestProfile): string | null {\n if (profile === 'live') return null;\n const blocking = tags.filter((t) => (LIVE_ONLY_TAGS as readonly string[]).includes(t));\n if (blocking.length === 0) return null;\n return `requires a live workspace (${blocking.join(', ')}); running under DBX_TEST_PROFILE=local`;\n}\n\nexport type CapabilityValue = string | number | boolean;\nexport type CapabilityMap = Readonly<Record<string, CapabilityValue>>;\n\n/** Build the runtime capability map used by active-tag predicates. */\nexport function capabilitiesFromEnv(\n profile: TestProfile,\n env: NodeJS.ProcessEnv = process.env,\n): CapabilityMap {\n const capabilities: Record<string, CapabilityValue> = { profile };\n const builtins: Array<[string, string | undefined]> = [\n ['cloud', env.DBX_TEST_CLOUD],\n ['compute', env.DBX_TEST_COMPUTE_MODE ?? env.DBX_TEST_COMPUTE],\n ['stage', env.DBX_TEST_STAGE],\n ];\n for (const [key, value] of builtins) {\n if (value !== undefined && value !== '') capabilities[key] = value;\n }\n for (const [name, value] of Object.entries(env)) {\n if (!name.startsWith('DBX_TEST_CAPABILITY_') || value === undefined) continue;\n capabilities[normalizeCapabilityKey(name.slice('DBX_TEST_CAPABILITY_'.length))] = value;\n }\n return capabilities;\n}\n\n/**\n * Evaluate TypeScript-native active tags.\n *\n * Supported forms:\n * - `@requires.cloud=azure` / `@requires.serverless`\n * - `@excludes.compute=classic`\n * - Behave-compatible aliases `@use.with_cloud=azure` and\n * `@not.with_cloud=azure`\n */\nexport function capabilityTagReason(\n tags: readonly string[],\n capabilities: CapabilityMap,\n): string | null {\n const normalized = new Map(\n Object.entries(capabilities).map(([key, value]) => [\n normalizeCapabilityKey(key),\n String(value).toLowerCase(),\n ]),\n );\n\n for (const tag of tags) {\n const predicate = parseCapabilityTag(tag);\n if (!predicate) continue;\n const actual = normalized.get(normalizeCapabilityKey(predicate.key));\n const matches = predicate.expected\n ? actual === predicate.expected.toLowerCase()\n : actual !== undefined && !['', '0', 'false', 'no', 'off'].includes(actual);\n if (predicate.kind === 'requires' && !matches) {\n return `${tag} requires capability ${predicate.key}${predicate.expected ? `=${predicate.expected}` : ''}; actual ${actual ?? 'unset'}`;\n }\n if (predicate.kind === 'excludes' && matches) {\n return `${tag} excludes capability ${predicate.key}${predicate.expected ? `=${predicate.expected}` : ''}`;\n }\n }\n return null;\n}\n\n/** Combined local/live and active-capability skip policy. */\nexport function scenarioSkipReason(\n tags: readonly string[],\n profile: TestProfile,\n env: NodeJS.ProcessEnv = process.env,\n): string | null {\n return (\n liveOnlyReason(tags, profile) ?? capabilityTagReason(tags, capabilitiesFromEnv(profile, env))\n );\n}\n\nfunction parseCapabilityTag(\n tag: string,\n): { kind: 'requires' | 'excludes'; key: string; expected?: string } | undefined {\n const direct = tag.match(/^@(requires|excludes)\\.([^=]+)(?:=(.+))?$/i);\n if (direct?.[1] && direct[2]) {\n return {\n kind: direct[1].toLowerCase() as 'requires' | 'excludes',\n key: direct[2],\n ...(direct[3] ? { expected: direct[3] } : {}),\n };\n }\n const behave = tag.match(/^@(use|not)\\.with_([^=]+)=(.+)$/i);\n if (behave?.[1] && behave[2] && behave[3]) {\n return {\n kind: behave[1].toLowerCase() === 'use' ? 'requires' : 'excludes',\n key: behave[2],\n expected: behave[3],\n };\n }\n return undefined;\n}\n\nfunction normalizeCapabilityKey(key: string): string {\n return key\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '_');\n}\n","import type { TableFixture } from '@fabricorg/databricks-testkit';\n\nconst INT_RE = /^-?\\d+$/;\nconst FLOAT_RE = /^-?\\d+\\.\\d+$/;\nconst TIMESTAMP_RE = /^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(:\\d{2})?/;\nconst BOOL_RE = /^(true|false)$/i;\n\n/**\n * Turn a Gherkin data table (header row + string cells) into a TableFixture,\n * inferring portable column types from the values: BIGINT, DOUBLE,\n * TIMESTAMP, BOOLEAN, else STRING. Empty cells become NULL.\n */\nexport function inferFixture(table: string, raw: readonly (readonly string[])[]): TableFixture {\n if (raw.length < 2) {\n throw new Error(`Data table for ${table} needs a header row and at least one data row`);\n }\n const [header, ...body] = raw as [readonly string[], ...(readonly string[])[]];\n const types = header.map((_, col) => inferColumnType(body.map((row) => row[col] ?? '')));\n const schema = header.map((name, i) => `\"${name}\" ${types[i]}`).join(', ');\n const rows = body.map((row) => row.map((cell, i) => coerceCell(cell, types[i] ?? 'STRING')));\n return { table, schema, rows };\n}\n\n/** Coerce data-table string cells to typed values for row matching (no header row). */\nexport function coerceMatchRows(raw: readonly (readonly string[])[]): Record<string, unknown>[] {\n if (raw.length < 2) {\n throw new Error('Match table needs a header row and at least one data row');\n }\n const [header, ...body] = raw as [readonly string[], ...(readonly string[])[]];\n return body.map((row) => {\n const out: Record<string, unknown> = {};\n header.forEach((name, i) => {\n out[name] = coerceCell(row[i] ?? '', inferColumnType([row[i] ?? '']));\n });\n return out;\n });\n}\n\nfunction inferColumnType(cells: readonly string[]): string {\n const present = cells.filter((c) => c !== '');\n if (present.length === 0) return 'STRING';\n if (present.every((c) => INT_RE.test(c))) return 'BIGINT';\n if (present.every((c) => FLOAT_RE.test(c) || INT_RE.test(c))) return 'DOUBLE';\n if (present.every((c) => TIMESTAMP_RE.test(c))) return 'TIMESTAMP';\n if (present.every((c) => BOOL_RE.test(c))) return 'BOOLEAN';\n return 'STRING';\n}\n\nfunction coerceCell(cell: string, type: string): unknown {\n if (cell === '') return null;\n if (type === 'BIGINT' || type === 'DOUBLE') return Number(cell);\n if (type === 'BOOLEAN') return /^true$/i.test(cell);\n return cell;\n}\n","import { type DatabricksRestClient, waitForDatabricksRun } from '@fabric-harness/databricks';\nimport type { WorkspaceClientLike } from '@fabricorg/databricks-testkit';\n\nexport interface RunJobOptions {\n pollIntervalMs?: number;\n timeoutMs?: number;\n}\n\nexport interface JobRunResult {\n runId: number;\n lifeCycleState: string;\n resultState: string;\n run: Record<string, unknown>;\n}\n\n/** Resolve a job by numeric id or by exact name via /api/2.1/jobs/list. */\nexport async function resolveJobId(client: WorkspaceClientLike, nameOrId: string): Promise<number> {\n if (/^\\d+$/.test(nameOrId)) return Number(nameOrId);\n const response = await client.get<{ jobs?: { job_id: number; settings?: { name?: string } }[] }>(\n '/api/2.1/jobs/list',\n { name: nameOrId },\n );\n const match = (response.jobs ?? []).find((j) => j.settings?.name === nameOrId);\n if (!match) throw new Error(`No Databricks job named '${nameOrId}' found`);\n return match.job_id;\n}\n\n/** run-now a job and poll its run to a terminal state. */\nexport async function runJobToTerminal(\n client: WorkspaceClientLike,\n nameOrId: string,\n options: RunJobOptions = {},\n): Promise<JobRunResult> {\n const jobId = await resolveJobId(client, nameOrId);\n const submitted = await client.post<{ run_id: number }>('/api/2.1/jobs/run-now', {\n job_id: jobId,\n });\n const run = await waitForDatabricksRun(client as DatabricksRestClient, submitted.run_id, {\n pollIntervalMs: options.pollIntervalMs,\n timeoutMs: options.timeoutMs,\n });\n const state = (run as { state?: { life_cycle_state?: string; result_state?: string } }).state;\n return {\n runId: submitted.run_id,\n lifeCycleState: state?.life_cycle_state ?? 'UNKNOWN',\n resultState: state?.result_state ?? 'UNKNOWN',\n run,\n };\n}\n","import {\n type PollOptions,\n type WorkspaceClientLike,\n waitForPipelineUpdate,\n} from '@fabricorg/databricks-testkit';\n\nexport type PipelineWaitOptions = PollOptions;\n\n/** Resolve a DLT/Lakeflow pipeline by id or exact name via /api/2.0/pipelines. */\nexport async function resolvePipelineId(\n client: WorkspaceClientLike,\n nameOrId: string,\n): Promise<string> {\n if (/^[0-9a-f]{8}-[0-9a-f-]{27,}$/i.test(nameOrId)) return nameOrId;\n const response = await client.get<{ statuses?: { pipeline_id: string; name?: string }[] }>(\n '/api/2.0/pipelines',\n { filter: `name LIKE '${nameOrId}'` },\n );\n const match = (response.statuses ?? []).find((p) => p.name === nameOrId);\n if (!match) throw new Error(`No Databricks pipeline named '${nameOrId}' found`);\n return match.pipeline_id;\n}\n\n/** Start a pipeline update; returns the update id to poll. */\nexport async function startPipelineUpdate(\n client: WorkspaceClientLike,\n pipelineId: string,\n options: { fullRefresh?: boolean } = {},\n): Promise<string> {\n const response = await client.post<{ update_id: string }>(\n `/api/2.0/pipelines/${encodeURIComponent(pipelineId)}/updates`,\n { full_refresh: options.fullRefresh ?? false },\n );\n return response.update_id;\n}\n\n/** Poll an update to a terminal state; throws on timeout or non-COMPLETED terminal states. */\nexport { waitForPipelineUpdate };\n","import { execFile } from 'node:child_process';\nimport { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\n\nexport interface RunFeaturesOptions {\n /** Directory containing the cucumber config / features. */\n cwd: string;\n /** Extra CLI args, e.g. ['--tags', 'not @slow'] or ['features/foo.feature']. */\n args?: string[];\n /** Extra environment (merged over process.env). */\n env?: Record<string, string>;\n /** Load TypeScript support code via tsx (default true). */\n tsx?: boolean;\n timeoutMs?: number;\n}\n\nexport interface RunFeaturesResult {\n success: boolean;\n exitCode: number;\n output: string;\n}\n\n/**\n * Vitest bridge: run cucumber-js as a subprocess so feature suites can be\n * embedded in an existing vitest run (one CI entry point) without fighting\n * over cucumber's global step registry or vitest's module transforms.\n */\nexport async function runFeatures(options: RunFeaturesOptions): Promise<RunFeaturesResult> {\n const require = createRequire(import.meta.url);\n // The bin path is not in the package's exports map — resolve it relative\n // to package.json (which is exported).\n const pkgPath = require.resolve('@cucumber/cucumber/package.json');\n const pkg = require(pkgPath) as { bin: Record<string, string> };\n const bin = join(dirname(pkgPath), pkg.bin['cucumber-js'] ?? 'bin/cucumber.js');\n const env: NodeJS.ProcessEnv = { ...process.env, ...options.env };\n if (options.tsx ?? true) {\n const tsxImport = '--import tsx';\n env.NODE_OPTIONS = env.NODE_OPTIONS ? `${env.NODE_OPTIONS} ${tsxImport}` : tsxImport;\n }\n return new Promise((resolve) => {\n execFile(\n process.execPath,\n [bin, ...(options.args ?? [])],\n { cwd: options.cwd, env, timeout: options.timeoutMs ?? 120_000, maxBuffer: 16 * 1024 * 1024 },\n (error, stdout, stderr) => {\n const exitCode =\n error && typeof (error as { code?: unknown }).code === 'number'\n ? ((error as { code?: number }).code ?? 1)\n : error\n ? 1\n : 0;\n resolve({ success: exitCode === 0, exitCode, output: `${stdout}\\n${stderr}` });\n },\n );\n });\n}\n","import { defineParameterType } from '@cucumber/cucumber';\n\nexport const RUN_STATES = ['SUCCESS', 'FAILED', 'CANCELED', 'TIMEDOUT'] as const;\nexport type RunState = (typeof RUN_STATES)[number];\n\nexport function parseDuration(value: string): number {\n const match = value.trim().match(/^(\\d+(?:\\.\\d+)?)\\s*(milliseconds?|ms|seconds?|s|minutes?|m)$/i);\n if (!match) throw new Error(`Invalid duration '${value}'`);\n const amount = Number(match[1]);\n const unit = match[2]?.toLowerCase() ?? '';\n if (unit === 'ms' || unit.startsWith('millisecond')) return amount;\n if (unit === 's' || unit.startsWith('second')) return amount * 1_000;\n return amount * 60_000;\n}\n\nexport function parseTableIdentifier(value: string): string {\n const identifier = value.trim();\n const part = '(?:[A-Za-z_][A-Za-z0-9_]*|`[^`]+`)';\n if (!new RegExp(`^${part}(?:\\\\.${part}){0,2}$`).test(identifier)) {\n throw new Error(`Invalid 1-3 part table identifier '${value}'`);\n }\n return identifier;\n}\n\nexport function registerParameterTypes(): void {\n defineParameterType({\n name: 'runState',\n regexp: /SUCCESS|FAILED|CANCELED|TIMEDOUT/,\n transformer: (value: string): RunState => value as RunState,\n });\n\n defineParameterType({\n name: 'duration',\n regexp: /\\d+(?:\\.\\d+)?\\s*(?:milliseconds?|ms|seconds?|s|minutes?|m)/,\n transformer: parseDuration,\n });\n\n defineParameterType({\n name: 'table',\n regexp: /(?:[A-Za-z_][A-Za-z0-9_]*|`[^`]+`)(?:\\.(?:[A-Za-z_][A-Za-z0-9_]*|`[^`]+`)){0,2}/,\n transformer: parseTableIdentifier,\n });\n}\n","import { Formatter, type IFormatterOptions } from '@cucumber/cucumber';\n\n/**\n * Evidence formatter: schema-versioned, secret-redacted JSON summary of a\n * BDD run, shared in spirit with the live check runner's evidence output so\n * nightly runs double as audit artifacts. Wire it up in cucumber config:\n *\n * format: [['@fabricorg/databricks-bdd/evidence-formatter', 'reports/evidence.json']]\n */\nexport interface EvidenceScenario {\n name: string;\n uri: string;\n tags: string[];\n status: string;\n durationMs: number;\n error?: string;\n failures?: StepFailureEvidence[];\n}\n\nexport interface StepFailureEvidence {\n step: string;\n statementId?: string;\n sql?: string;\n output?: string;\n outputBytes?: number;\n outputTruncated?: boolean;\n}\n\nexport interface EvidenceReport {\n schemaVersion: 2;\n kind: 'databricks-bdd';\n profile: string;\n finishedAt: string;\n success: boolean;\n summary: Record<string, number>;\n scenarios: EvidenceScenario[];\n}\n\ninterface Envelope {\n attachment?: {\n body: string;\n contentEncoding: 'IDENTITY' | 'BASE64';\n mediaType: string;\n testCaseStartedId?: string;\n };\n pickle?: { id: string; name: string; uri: string; tags?: { name: string }[] };\n testCase?: { id: string; pickleId: string };\n testCaseStarted?: { id: string; testCaseId: string };\n testStepFinished?: {\n testCaseStartedId: string;\n testStepResult: {\n status: string;\n message?: string;\n duration?: { seconds: number; nanos: number };\n };\n };\n testRunFinished?: { success?: boolean; timestamp?: { seconds: number; nanos: number } };\n}\n\nexport const FAILURE_EVIDENCE_MEDIA_TYPE = 'application/vnd.fabric.databricks-bdd.failure+json';\n\nconst STATUS_RANK = ['UNKNOWN', 'PASSED', 'SKIPPED', 'PENDING', 'UNDEFINED', 'AMBIGUOUS', 'FAILED'];\n\nexport default class EvidenceFormatter extends Formatter {\n private readonly pickles = new Map<string, NonNullable<Envelope['pickle']>>();\n private readonly testCases = new Map<string, string>(); // testCaseId → pickleId\n private readonly attempts = new Map<\n string,\n {\n pickleId: string;\n status: string;\n durationMs: number;\n error?: string;\n failures: StepFailureEvidence[];\n }\n >();\n\n constructor(options: IFormatterOptions) {\n super(options);\n options.eventBroadcaster.on('envelope', (envelope: Envelope) => this.onEnvelope(envelope));\n }\n\n private onEnvelope(envelope: Envelope): void {\n if (envelope.pickle) this.pickles.set(envelope.pickle.id, envelope.pickle);\n if (envelope.testCase) this.testCases.set(envelope.testCase.id, envelope.testCase.pickleId);\n if (envelope.testCaseStarted) {\n this.attempts.set(envelope.testCaseStarted.id, {\n pickleId: this.testCases.get(envelope.testCaseStarted.testCaseId) ?? '',\n status: 'UNKNOWN',\n durationMs: 0,\n failures: [],\n });\n }\n if (envelope.attachment?.testCaseStartedId) {\n const attempt = this.attempts.get(envelope.attachment.testCaseStartedId);\n const failure = parseFailureEvidenceAttachment(envelope.attachment);\n if (attempt && failure) attempt.failures.push(failure);\n }\n if (envelope.testStepFinished) {\n const attempt = this.attempts.get(envelope.testStepFinished.testCaseStartedId);\n if (attempt) {\n const result = envelope.testStepFinished.testStepResult;\n if (STATUS_RANK.indexOf(result.status) > STATUS_RANK.indexOf(attempt.status)) {\n attempt.status = result.status;\n if (result.message) attempt.error = redactSecrets(result.message);\n }\n const d = result.duration;\n if (d) attempt.durationMs += d.seconds * 1000 + d.nanos / 1e6;\n }\n }\n if (envelope.testRunFinished) this.finish(envelope.testRunFinished);\n }\n\n private finish(finished: NonNullable<Envelope['testRunFinished']>): void {\n const scenarios: EvidenceScenario[] = [];\n const summary: Record<string, number> = {};\n for (const attempt of this.attempts.values()) {\n const pickle = this.pickles.get(attempt.pickleId);\n const status = attempt.status.toLowerCase();\n summary[status] = (summary[status] ?? 0) + 1;\n scenarios.push({\n name: pickle?.name ?? attempt.pickleId,\n uri: pickle?.uri ?? '',\n tags: (pickle?.tags ?? []).map((t) => t.name),\n status,\n durationMs: Math.round(attempt.durationMs),\n ...(attempt.error ? { error: attempt.error } : {}),\n ...(attempt.failures.length > 0 ? { failures: attempt.failures } : {}),\n });\n }\n const report: EvidenceReport = {\n schemaVersion: 2,\n kind: 'databricks-bdd',\n profile: process.env.DBX_TEST_PROFILE ?? 'local',\n finishedAt: new Date().toISOString(),\n success: finished.success ?? !scenarios.some((s) => s.status === 'failed'),\n summary,\n scenarios,\n };\n this.log(`${JSON.stringify(report, null, 2)}\\n`);\n }\n}\n\n/** Decode the structured attachment emitted by the failure hook. */\nexport function parseFailureEvidenceAttachment(\n attachment: NonNullable<Envelope['attachment']>,\n): StepFailureEvidence | null {\n if (attachment.mediaType !== FAILURE_EVIDENCE_MEDIA_TYPE) return null;\n try {\n const body =\n attachment.contentEncoding === 'BASE64'\n ? Buffer.from(attachment.body, 'base64').toString('utf8')\n : attachment.body;\n const parsed = JSON.parse(redactSecrets(body)) as Partial<StepFailureEvidence>;\n if (typeof parsed.step !== 'string') return null;\n return {\n step: parsed.step,\n ...(typeof parsed.statementId === 'string' ? { statementId: parsed.statementId } : {}),\n ...(typeof parsed.sql === 'string' ? { sql: parsed.sql } : {}),\n ...(typeof parsed.output === 'string' ? { output: parsed.output } : {}),\n ...(typeof parsed.outputBytes === 'number' ? { outputBytes: parsed.outputBytes } : {}),\n ...(typeof parsed.outputTruncated === 'boolean'\n ? { outputTruncated: parsed.outputTruncated }\n : {}),\n };\n } catch {\n return null;\n }\n}\n\nconst SECRET_ENV_RE = /(TOKEN|SECRET|PASSWORD|BEARER|KEY)/;\n\n/** Replace values of secret-looking env vars anywhere they appear in text. */\nexport function redactSecrets(\n text: string,\n env: Record<string, string | undefined> = process.env,\n): string {\n let out = text;\n for (const [name, value] of Object.entries(env)) {\n if (!value || value.length < 6) continue;\n if (!SECRET_ENV_RE.test(name)) continue;\n out = out.split(value).join('[REDACTED]');\n }\n return out;\n}\n","import type { Writable } from 'node:stream';\nimport { format } from 'node:util';\n\nexport type CapturedStream = 'stdout' | 'stderr';\n\nexport interface CapturedStepOutput {\n /** Ordered stdout/stderr output with stream labels. */\n text: string;\n /** True when output exceeded the configured byte budget. */\n truncated: boolean;\n /** Total bytes emitted before truncation. */\n totalBytes: number;\n}\n\nexport interface StepOutputCapture {\n stop(): CapturedStepOutput;\n}\n\nexport interface StepOutputCaptureOptions {\n /** Maximum UTF-8 bytes retained for one step. Defaults to 32 KiB. */\n maxBytes?: number;\n /** Forward output while capturing. Defaults to false, matching Behave capture semantics. */\n passthrough?: boolean;\n}\n\ninterface CapturedChunk {\n stream: CapturedStream;\n text: string;\n}\n\ntype Write = Writable['write'];\ntype ConsoleMethod = 'debug' | 'error' | 'info' | 'log' | 'warn';\n\nconst DEFAULT_MAX_BYTES = 32 * 1024;\n\n/**\n * Capture process stdout/stderr until stop() is called. Console output and\n * Pino's standard destination both flow through these streams. Child\n * processes that inherit the OS file descriptors directly are intentionally\n * outside this in-process capture boundary.\n */\nexport function startStepOutputCapture(options: StepOutputCaptureOptions = {}): StepOutputCapture {\n const maxBytes = Math.max(0, options.maxBytes ?? DEFAULT_MAX_BYTES);\n const stdout = process.stdout;\n const stderr = process.stderr;\n const originalStdoutWrite = stdout.write;\n const originalStderrWrite = stderr.write;\n const originalConsole = Object.fromEntries(\n (['debug', 'error', 'info', 'log', 'warn'] as const).map((method) => [method, console[method]]),\n ) as Record<ConsoleMethod, typeof console.log>;\n const chunks: CapturedChunk[] = [];\n let retainedBytes = 0;\n let totalBytes = 0;\n let stopped = false;\n\n const capture = (stream: CapturedStream, chunk: unknown): void => {\n const text = chunkToString(chunk);\n const bytes = Buffer.byteLength(text);\n totalBytes += bytes;\n const remaining = maxBytes - retainedBytes;\n if (remaining <= 0 || bytes === 0) return;\n const retained = bytes <= remaining ? text : truncateUtf8(text, remaining);\n retainedBytes += Buffer.byteLength(retained);\n if (retained) chunks.push({ stream, text: retained });\n };\n\n stdout.write = interceptedWrite(\n stdout,\n 'stdout',\n originalStdoutWrite,\n capture,\n options.passthrough,\n );\n stderr.write = interceptedWrite(\n stderr,\n 'stderr',\n originalStderrWrite,\n capture,\n options.passthrough,\n );\n if (!options.passthrough) {\n for (const method of ['debug', 'info', 'log'] as const) {\n console[method] = (...args: unknown[]) => capture('stdout', `${format(...args)}\\n`);\n }\n for (const method of ['error', 'warn'] as const) {\n console[method] = (...args: unknown[]) => capture('stderr', `${format(...args)}\\n`);\n }\n }\n\n return {\n stop(): CapturedStepOutput {\n if (!stopped) {\n stdout.write = originalStdoutWrite;\n stderr.write = originalStderrWrite;\n for (const method of Object.keys(originalConsole) as ConsoleMethod[]) {\n console[method] = originalConsole[method];\n }\n stopped = true;\n }\n return {\n text: renderChunks(chunks),\n truncated: totalBytes > retainedBytes,\n totalBytes,\n };\n },\n };\n}\n\nfunction interceptedWrite(\n destination: Writable,\n stream: CapturedStream,\n original: Write,\n capture: (stream: CapturedStream, chunk: unknown) => void,\n passthrough = false,\n): Write {\n return function write(chunk: unknown, encodingOrCallback?: unknown, callback?: unknown): boolean {\n capture(stream, chunk);\n if (passthrough) {\n return original.call(\n destination,\n chunk as never,\n encodingOrCallback as never,\n callback as never,\n );\n }\n const done = typeof encodingOrCallback === 'function' ? encodingOrCallback : callback;\n if (typeof done === 'function') queueMicrotask(() => done());\n return true;\n } as Write;\n}\n\nfunction chunkToString(chunk: unknown): string {\n if (typeof chunk === 'string') return chunk;\n if (Buffer.isBuffer(chunk)) return chunk.toString('utf8');\n if (chunk instanceof Uint8Array) return Buffer.from(chunk).toString('utf8');\n return String(chunk);\n}\n\nfunction truncateUtf8(value: string, maxBytes: number): string {\n return Buffer.from(value)\n .subarray(0, maxBytes)\n .toString('utf8')\n .replace(/\\uFFFD$/u, '');\n}\n\nfunction renderChunks(chunks: readonly CapturedChunk[]): string {\n let rendered = '';\n let previous: CapturedStream | undefined;\n for (const chunk of chunks) {\n if (chunk.stream !== previous) {\n if (rendered && !rendered.endsWith('\\n')) rendered += '\\n';\n rendered += `[${chunk.stream}]\\n`;\n previous = chunk.stream;\n }\n rendered += chunk.text;\n }\n return rendered.trimEnd();\n}\n","/** Cardinalities supported by Behave's cfparse fields. */\nexport type FieldCardinality = '?' | '*' | '+';\n\nexport interface CardinalityOptions {\n /** Delimiter between values. Defaults to a comma with optional whitespace. */\n separator?: string | RegExp;\n /** Human-readable field name used in validation errors. */\n fieldName?: string;\n}\n\nexport type CardinalityResult<T, C extends FieldCardinality> = C extends '?' ? T | undefined : T[];\n\n/**\n * Parse a Cucumber string parameter with cfparse-compatible cardinality.\n *\n * Use `?` for zero-or-one, `*` for zero-or-more, and `+` for one-or-more.\n * This keeps the capability in TypeScript while allowing standard Cucumber\n * Expressions and readable comma-separated parameters.\n */\nexport function parseCardinalityField<T, C extends FieldCardinality>(\n value: string,\n cardinality: C,\n transform: (item: string, index: number) => T,\n options: CardinalityOptions = {},\n): CardinalityResult<T, C> {\n const fieldName = options.fieldName ?? 'field';\n const trimmed = value.trim();\n const items = trimmed\n ? trimmed.split(options.separator ?? /\\s*,\\s*/).map((item) => item.trim())\n : [];\n if (items.some((item) => !item)) {\n throw new Error(`${fieldName} contains an empty value`);\n }\n\n if (cardinality === '?' && items.length > 1) {\n throw new Error(`${fieldName} expects zero or one value, received ${items.length}`);\n }\n if (cardinality === '+' && items.length === 0) {\n throw new Error(`${fieldName} expects one or more values`);\n }\n\n const parsed = items.map(transform);\n if (cardinality === '?') return parsed[0] as CardinalityResult<T, C>;\n return parsed as CardinalityResult<T, C>;\n}\n"]}
|