@fabricorg/experiments 0.6.5 → 0.8.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/dist/bin/fx.cjs CHANGED
@@ -11,6 +11,10 @@ var http = require('http');
11
11
  var module$1 = require('module');
12
12
  var databricksTestkit = require('@fabricorg/databricks-testkit');
13
13
  var fastXmlParser = require('fast-xml-parser');
14
+ var child_process = require('child_process');
15
+ var os = require('os');
16
+ var util$1 = require('util');
17
+ var process$1 = require('process');
14
18
 
15
19
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
16
20
  var __defProp = Object.defineProperty;
@@ -7437,6 +7441,39 @@ var AuditEvent = external_exports.object({
7437
7441
  payload: external_exports.record(external_exports.unknown())
7438
7442
  });
7439
7443
  var AuditListResponse = external_exports.object({ events: external_exports.array(AuditEvent) });
7444
+ var GovernanceSettings = external_exports.object({
7445
+ requireQualityForProduction: external_exports.boolean(),
7446
+ requiredQualitySuites: external_exports.array(external_exports.string().min(1).max(240)).max(50),
7447
+ qualityMaxAgeHours: external_exports.number().int().min(1).max(8760),
7448
+ retentionDays: external_exports.number().int().min(30).max(3650),
7449
+ legalHold: external_exports.boolean(),
7450
+ updatedBy: external_exports.string().nullable(),
7451
+ updatedAt: external_exports.string().datetime().nullable()
7452
+ });
7453
+ var UpdateGovernanceSettingsInput = GovernanceSettings.pick({
7454
+ requireQualityForProduction: true,
7455
+ requiredQualitySuites: true,
7456
+ qualityMaxAgeHours: true,
7457
+ retentionDays: true,
7458
+ legalHold: true
7459
+ });
7460
+ var QualityGateResult = external_exports.object({
7461
+ enabled: external_exports.boolean(),
7462
+ passed: external_exports.boolean(),
7463
+ checks: external_exports.array(
7464
+ external_exports.object({
7465
+ suite: external_exports.string(),
7466
+ passed: external_exports.boolean(),
7467
+ reason: external_exports.string(),
7468
+ runId: external_exports.string().nullable(),
7469
+ finishedAt: external_exports.string().datetime().nullable()
7470
+ })
7471
+ )
7472
+ });
7473
+ var GovernanceStatusResponse = external_exports.object({
7474
+ settings: GovernanceSettings,
7475
+ qualityGate: QualityGateResult
7476
+ });
7440
7477
  var AuditExport = external_exports.object({
7441
7478
  id: external_exports.string(),
7442
7479
  destinationKind: external_exports.enum(["s3", "r2", "splunk-hec"]),
@@ -7543,6 +7580,7 @@ var TestRunListInput = external_exports.object({
7543
7580
  status: TestRunStatus.optional(),
7544
7581
  source: CreateTestRunInput.shape.source.optional(),
7545
7582
  suite: external_exports.string().min(1).max(240).optional(),
7583
+ targetPack: external_exports.string().min(1).max(120).regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/).optional(),
7546
7584
  limit: external_exports.coerce.number().int().min(1).max(200).optional(),
7547
7585
  offset: external_exports.coerce.number().int().min(0).max(1e5).optional()
7548
7586
  });
@@ -7758,6 +7796,22 @@ var endpoints = {
7758
7796
  mutates: false,
7759
7797
  requiresRole: "viewer"
7760
7798
  },
7799
+ "governance.get": {
7800
+ method: "GET",
7801
+ path: "/v1/orgs/:orgId/governance",
7802
+ params: Empty,
7803
+ response: GovernanceStatusResponse,
7804
+ mutates: false,
7805
+ requiresRole: "viewer"
7806
+ },
7807
+ "governance.update": {
7808
+ method: "POST",
7809
+ path: "/v1/orgs/:orgId/governance",
7810
+ params: UpdateGovernanceSettingsInput,
7811
+ response: GovernanceStatusResponse,
7812
+ mutates: true,
7813
+ requiresRole: "admin"
7814
+ },
7761
7815
  "audit.exports.list": {
7762
7816
  method: "GET",
7763
7817
  path: "/v1/orgs/:orgId/audit/exports",
@@ -8009,6 +8063,10 @@ var ApiClient = class {
8009
8063
  audit = {
8010
8064
  list: (orgId) => this.call("audit.list", {}, orgId ? { orgId } : void 0)
8011
8065
  };
8066
+ governance = {
8067
+ get: (orgId) => this.call("governance.get", {}, orgId ? { orgId } : void 0),
8068
+ update: (params, orgId) => this.call("governance.update", params, orgId ? { orgId } : void 0)
8069
+ };
8012
8070
  preview = {
8013
8071
  sign: (params, orgId) => this.call("preview.sign", params, orgId ? { orgId } : void 0)
8014
8072
  };
@@ -8056,6 +8114,7 @@ async function cmdPreview(experimentId, options) {
8056
8114
  const client = new ApiClient({
8057
8115
  baseUrl: options.apiUrl,
8058
8116
  apiKey: options.apiKey,
8117
+ bearerToken: options.bearerToken,
8059
8118
  defaultOrgId: tenantId
8060
8119
  });
8061
8120
  const r = await client.call(
@@ -8142,7 +8201,12 @@ async function cmdPush(dir, options = {}) {
8142
8201
  );
8143
8202
  return 1;
8144
8203
  }
8145
- const api = new ApiClient({ baseUrl: apiUrl, apiKey, defaultOrgId: tenantId });
8204
+ const api = new ApiClient({
8205
+ baseUrl: apiUrl,
8206
+ apiKey,
8207
+ bearerToken: options.bearerToken,
8208
+ defaultOrgId: tenantId
8209
+ });
8146
8210
  const specs = (await loadExperimentDir(path.resolve(dir))).map((s) => s.spec);
8147
8211
  const summaries = (await api.experiments.list()).experiments;
8148
8212
  const current = [];
@@ -8207,7 +8271,7 @@ var FILES = {
8207
8271
  devDependencies: {
8208
8272
  "@cucumber/cucumber": "^13.0.0",
8209
8273
  "@duckdb/node-api": "^1.5.0",
8210
- "@fabricorg/databricks-bdd": "^0.4.0",
8274
+ "@fabricorg/databricks-bdd": "^0.5.0",
8211
8275
  tsx: "^4.19.2",
8212
8276
  typescript: "^5.8.3"
8213
8277
  }
@@ -8527,6 +8591,141 @@ async function writeState(path$1, state) {
8527
8591
  await promises.writeFile(path$1, `${JSON.stringify(state, null, 2)}
8528
8592
  `, "utf8");
8529
8593
  }
8594
+ var execFileAsync = util$1.promisify(child_process.execFile);
8595
+ function defaultConfigPath(env = process.env) {
8596
+ const configDir = env.FX_CONFIG_DIR ?? (process.platform === "win32" ? path.join(env.APPDATA ?? os.homedir(), "Fabric Experiments") : path.join(env.XDG_CONFIG_HOME ?? path.join(os.homedir(), ".config"), "fabric-experiments"));
8597
+ return path.join(configDir, "config.json");
8598
+ }
8599
+ async function loadHostedConfig(path = defaultConfigPath()) {
8600
+ try {
8601
+ const parsed = JSON.parse(await promises.readFile(path, "utf8"));
8602
+ return {
8603
+ version: 1,
8604
+ activeProfile: parsed.activeProfile,
8605
+ profiles: parsed.profiles ?? {}
8606
+ };
8607
+ } catch (error) {
8608
+ if (error.code === "ENOENT") {
8609
+ return { version: 1, profiles: {} };
8610
+ }
8611
+ throw new Error(`Unable to read Fabric CLI config at ${path}: ${error.message}`);
8612
+ }
8613
+ }
8614
+ async function saveHostedConfig(config, path$1 = defaultConfigPath()) {
8615
+ await promises.mkdir(path.dirname(path$1), { recursive: true, mode: 448 });
8616
+ const temporary = `${path$1}.${process.pid}.tmp`;
8617
+ await promises.writeFile(temporary, `${JSON.stringify(config, null, 2)}
8618
+ `, { mode: 384 });
8619
+ await promises.rename(temporary, path$1);
8620
+ await promises.chmod(path$1, 384);
8621
+ }
8622
+ async function removeHostedProfile(profileName, path = defaultConfigPath()) {
8623
+ const config = await loadHostedConfig(path);
8624
+ if (!config.profiles[profileName]) return false;
8625
+ delete config.profiles[profileName];
8626
+ if (config.activeProfile === profileName) {
8627
+ config.activeProfile = Object.keys(config.profiles).sort()[0];
8628
+ }
8629
+ if (Object.keys(config.profiles).length === 0) {
8630
+ try {
8631
+ await promises.unlink(path);
8632
+ } catch (error) {
8633
+ if (error.code !== "ENOENT") throw error;
8634
+ }
8635
+ return true;
8636
+ }
8637
+ await saveHostedConfig(config, path);
8638
+ return true;
8639
+ }
8640
+ async function configPermissionsArePrivate(path = defaultConfigPath()) {
8641
+ if (process.platform === "win32") return true;
8642
+ try {
8643
+ const details = await promises.stat(path);
8644
+ return (details.mode & 63) === 0;
8645
+ } catch (error) {
8646
+ if (error.code === "ENOENT") return true;
8647
+ throw error;
8648
+ }
8649
+ }
8650
+ async function resolveHostedContext(options = {}) {
8651
+ const env = options.env ?? process.env;
8652
+ const config = await loadHostedConfig(options.configPath ?? defaultConfigPath(env));
8653
+ const profileName = options.profileName ?? env.FX_PROFILE ?? config.activeProfile;
8654
+ const profile = profileName ? config.profiles[profileName] : void 0;
8655
+ const apiUrl = options.apiUrl ?? env.FX_API_URL ?? profile?.apiUrl;
8656
+ const apiKey = options.apiKey ?? env.FX_API_KEY ?? profile?.apiKey;
8657
+ const tenantId = options.tenantId ?? env.FX_ORG_ID ?? profile?.orgId;
8658
+ const bearerToken = options.bearerToken ?? (apiUrl ? await resolveGatewayBearer(apiUrl, {
8659
+ env,
8660
+ databricksProfile: profile?.databricksProfile,
8661
+ tokenProvider: options.tokenProvider
8662
+ }) : void 0);
8663
+ return { profileName, apiUrl, apiKey, tenantId, bearerToken };
8664
+ }
8665
+ async function resolveStudioApiUrl(studioUrl, fetchImpl = globalThis.fetch) {
8666
+ const source = new URL(studioUrl);
8667
+ const response = await fetchImpl(source.toString(), { method: "HEAD", redirect: "manual" });
8668
+ const location = response.headers.get("location");
8669
+ const target = location ? new URL(location, source) : source;
8670
+ target.pathname = "/api";
8671
+ target.search = "";
8672
+ target.hash = "";
8673
+ return target.toString().replace(/\/$/, "");
8674
+ }
8675
+ async function resolveGatewayBearer(apiUrl, options = {}) {
8676
+ const env = options.env ?? process.env;
8677
+ if (env.FX_GATEWAY_BEARER_TOKEN) return env.FX_GATEWAY_BEARER_TOKEN;
8678
+ if (!new URL(apiUrl).hostname.endsWith(".databricksapps.com")) return void 0;
8679
+ const databricksProfile = options.databricksProfile ?? env.FX_DATABRICKS_PROFILE;
8680
+ if (databricksProfile) {
8681
+ return (options.tokenProvider ?? databricksCliToken)(databricksProfile);
8682
+ }
8683
+ const host = env.DATABRICKS_HOST?.replace(/\/$/, "");
8684
+ const clientId = env.FX_QUALITY_DATABRICKS_CLIENT_ID ?? env.DATABRICKS_CLIENT_ID;
8685
+ const clientSecret = env.FX_QUALITY_DATABRICKS_CLIENT_SECRET ?? env.DATABRICKS_CLIENT_SECRET;
8686
+ if (!host || !clientId || !clientSecret) {
8687
+ try {
8688
+ return await (options.tokenProvider ?? databricksCliToken)();
8689
+ } catch {
8690
+ throw new Error(
8691
+ "Databricks Apps access requires a Databricks CLI login, --databricks-profile, FX_DATABRICKS_PROFILE, or DATABRICKS_HOST with client credentials"
8692
+ );
8693
+ }
8694
+ }
8695
+ const response = await fetch(`${host}/oidc/v1/token`, {
8696
+ method: "POST",
8697
+ headers: {
8698
+ authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`,
8699
+ "content-type": "application/x-www-form-urlencoded"
8700
+ },
8701
+ body: new URLSearchParams({ grant_type: "client_credentials", scope: "all-apis" })
8702
+ });
8703
+ if (!response.ok) {
8704
+ throw new Error(`Databricks OAuth failed (${response.status} ${response.statusText})`);
8705
+ }
8706
+ const body = await response.json();
8707
+ if (typeof body.access_token !== "string" || !body.access_token) {
8708
+ throw new Error("Databricks OAuth response did not include an access token");
8709
+ }
8710
+ return body.access_token;
8711
+ }
8712
+ async function databricksCliToken(profile) {
8713
+ try {
8714
+ const args = ["auth", "token", ...profile ? [profile] : [], "--output", "json"];
8715
+ const { stdout } = await execFileAsync("databricks", args, { encoding: "utf8" });
8716
+ const parsed = JSON.parse(stdout);
8717
+ if (typeof parsed.access_token !== "string" || !parsed.access_token) {
8718
+ throw new Error("token response did not include access_token");
8719
+ }
8720
+ return parsed.access_token;
8721
+ } catch (error) {
8722
+ throw new Error(
8723
+ `Unable to obtain a Databricks token${profile ? ` for profile ${profile}` : ""}: ${error.message}`
8724
+ );
8725
+ }
8726
+ }
8727
+
8728
+ // src/commands/test-publish.ts
8530
8729
  async function cmdTestPublish(evidencePath, options = {}) {
8531
8730
  const env = options.env ?? process.env;
8532
8731
  const apiUrl = options.apiUrl ?? env.FX_API_URL;
@@ -8555,30 +8754,7 @@ async function cmdTestPublish(evidencePath, options = {}) {
8555
8754
  return 0;
8556
8755
  }
8557
8756
  async function resolveGatewayToken(apiUrl, env) {
8558
- if (env.FX_GATEWAY_BEARER_TOKEN) return env.FX_GATEWAY_BEARER_TOKEN;
8559
- if (!new URL(apiUrl).hostname.endsWith(".databricksapps.com")) return void 0;
8560
- const host = env.DATABRICKS_HOST?.replace(/\/$/, "");
8561
- const clientId = env.FX_QUALITY_DATABRICKS_CLIENT_ID ?? env.DATABRICKS_CLIENT_ID;
8562
- const clientSecret = env.FX_QUALITY_DATABRICKS_CLIENT_SECRET ?? env.DATABRICKS_CLIENT_SECRET;
8563
- if (!host || !clientId || !clientSecret) {
8564
- throw new Error("Databricks Apps publication requires DATABRICKS_HOST and client credentials");
8565
- }
8566
- const response = await fetch(`${host}/oidc/v1/token`, {
8567
- method: "POST",
8568
- headers: {
8569
- authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`,
8570
- "content-type": "application/x-www-form-urlencoded"
8571
- },
8572
- body: new URLSearchParams({ grant_type: "client_credentials", scope: "all-apis" })
8573
- });
8574
- if (!response.ok) {
8575
- throw new Error(`Databricks OAuth failed (${response.status} ${response.statusText})`);
8576
- }
8577
- const body = await response.json();
8578
- if (typeof body.access_token !== "string" || !body.access_token) {
8579
- throw new Error("Databricks OAuth response did not include an access token");
8580
- }
8581
- return body.access_token;
8757
+ return resolveGatewayBearer(apiUrl, { env });
8582
8758
  }
8583
8759
  function normalizeTestEvidence(value, options = {}) {
8584
8760
  if (!value || typeof value !== "object") throw new Error("Evidence must be a JSON object");
@@ -8631,6 +8807,8 @@ function normalizeTestEvidence(value, options = {}) {
8631
8807
  };
8632
8808
  }
8633
8809
  if (kind === "databricks-live-suite") {
8810
+ const targetPack = objectOf(evidence.targetPack);
8811
+ const target = objectOf(targetPack.target);
8634
8812
  const cases = arrayOfRecords(evidence.results).map((result) => ({
8635
8813
  id: String(result.id ?? ""),
8636
8814
  name: String(result.description ?? result.id ?? "Live check"),
@@ -8652,11 +8830,19 @@ function normalizeTestEvidence(value, options = {}) {
8652
8830
  summary,
8653
8831
  environment: compact({
8654
8832
  profile: "live",
8655
- cloud: env.DBX_TEST_CLOUD ?? "azure",
8656
- workspace: env.DATABRICKS_HOST,
8833
+ cloud: target.cloud ?? env.DBX_TEST_CLOUD ?? "azure",
8834
+ region: target.region ?? env.DBX_TEST_REGION,
8835
+ workspace: target.workspace ?? env.DATABRICKS_HOST,
8657
8836
  warehouseId: env.DATABRICKS_WAREHOUSE_ID,
8658
- runtime: env.DBX_TEST_RUNTIME_VERSION,
8659
- compute: env.DBX_TEST_COMPUTE
8837
+ runtime: target.runtime ?? env.DBX_TEST_RUNTIME_VERSION,
8838
+ compute: target.compute ?? env.DBX_TEST_COMPUTE,
8839
+ targetPackId: targetPack.id,
8840
+ targetPackName: targetPack.name,
8841
+ targetPackVersion: targetPack.version,
8842
+ targetPackMaturity: targetPack.maturity,
8843
+ targetPackCapabilities: targetPack.capabilities,
8844
+ targetPackCertificationScopes: targetPack.certificationScopes,
8845
+ targetPackDocsUrl: targetPack.docsUrl
8660
8846
  }),
8661
8847
  revision,
8662
8848
  cases,
@@ -8812,6 +8998,329 @@ function isoOrNull(value) {
8812
8998
  if (typeof value !== "string" || Number.isNaN(Date.parse(value))) return null;
8813
8999
  return new Date(value).toISOString();
8814
9000
  }
9001
+ async function cmdLogin(options = {}) {
9002
+ const env = options.env ?? process.env;
9003
+ const profileName = options.profileName ?? "production";
9004
+ const apiUrl = options.apiUrl ? normalizeApiUrl(options.apiUrl) : await resolveStudioApiUrl(
9005
+ options.studioUrl ?? "https://studio.experiments.fabric.pro",
9006
+ options.fetchImpl
9007
+ );
9008
+ const apiKey = options.apiKey ?? env.FX_API_KEY ?? await (options.promptSecret ?? readSecretApiKey)();
9009
+ if (!apiKey) throw new Error("A Fabric API key is required");
9010
+ const bearerToken = await resolveGatewayBearer(apiUrl, {
9011
+ env,
9012
+ databricksProfile: options.databricksProfile,
9013
+ tokenProvider: options.tokenProvider
9014
+ });
9015
+ const client = new ApiClient({
9016
+ baseUrl: apiUrl,
9017
+ apiKey,
9018
+ bearerToken,
9019
+ fetchImpl: options.fetchImpl
9020
+ });
9021
+ const tenant = await client.tenants.me();
9022
+ if (options.tenantId && options.tenantId !== tenant.organization.id) {
9023
+ throw new Error(
9024
+ `API key belongs to ${tenant.organization.id}, not requested organization ${options.tenantId}`
9025
+ );
9026
+ }
9027
+ const now3 = (/* @__PURE__ */ new Date()).toISOString();
9028
+ const path = options.configPath ?? defaultConfigPath(env);
9029
+ const config = await loadHostedConfig(path);
9030
+ const existing = config.profiles[profileName];
9031
+ config.profiles[profileName] = {
9032
+ apiUrl,
9033
+ apiKey,
9034
+ orgId: tenant.organization.id,
9035
+ organizationName: tenant.organization.name,
9036
+ organizationSlug: tenant.organization.slug,
9037
+ role: tenant.member.role,
9038
+ databricksProfile: options.databricksProfile,
9039
+ createdAt: existing?.createdAt ?? now3,
9040
+ updatedAt: now3
9041
+ };
9042
+ config.activeProfile = profileName;
9043
+ await saveHostedConfig(config, path);
9044
+ process.stdout.write(
9045
+ `Logged in to ${tenant.organization.name} as ${tenant.member.role} (profile: ${profileName}).
9046
+ `
9047
+ );
9048
+ return 0;
9049
+ }
9050
+ async function cmdLogout(profileName, options = {}) {
9051
+ const env = options.env ?? process.env;
9052
+ const path = options.configPath ?? defaultConfigPath(env);
9053
+ const config = await loadHostedConfig(path);
9054
+ const target = profileName ?? config.activeProfile;
9055
+ if (!target) {
9056
+ process.stdout.write("No Fabric CLI profile is configured.\n");
9057
+ return 0;
9058
+ }
9059
+ const removed = await removeHostedProfile(target, path);
9060
+ process.stdout.write(
9061
+ removed ? `Logged out profile ${target}.
9062
+ ` : `Profile ${target} not found.
9063
+ `
9064
+ );
9065
+ return removed ? 0 : 1;
9066
+ }
9067
+ async function cmdProfile(action = "list", profileName, options = {}) {
9068
+ const env = options.env ?? process.env;
9069
+ const path = options.configPath ?? defaultConfigPath(env);
9070
+ const config = await loadHostedConfig(path);
9071
+ if (action === "use") {
9072
+ if (!profileName || !config.profiles[profileName]) {
9073
+ process.stderr.write("Usage: fx profile use <name>\n");
9074
+ return 1;
9075
+ }
9076
+ config.activeProfile = profileName;
9077
+ await saveHostedConfig(config, path);
9078
+ process.stdout.write(`Active profile: ${profileName}
9079
+ `);
9080
+ return 0;
9081
+ }
9082
+ if (action === "show") {
9083
+ const selected = profileName ?? config.activeProfile;
9084
+ const profile = selected ? config.profiles[selected] : void 0;
9085
+ if (!selected || !profile) {
9086
+ process.stderr.write("No active Fabric CLI profile. Run fx login.\n");
9087
+ return 1;
9088
+ }
9089
+ process.stdout.write(formatProfile(selected, profile, selected === config.activeProfile));
9090
+ return 0;
9091
+ }
9092
+ const names = Object.keys(config.profiles).sort();
9093
+ if (names.length === 0) {
9094
+ process.stdout.write("No Fabric CLI profiles. Run fx login.\n");
9095
+ return 0;
9096
+ }
9097
+ for (const name of names) {
9098
+ process.stdout.write(
9099
+ formatProfile(name, config.profiles[name], name === config.activeProfile)
9100
+ );
9101
+ }
9102
+ return 0;
9103
+ }
9104
+ async function cmdDoctor(options = {}) {
9105
+ const env = options.env ?? process.env;
9106
+ const path = options.configPath ?? defaultConfigPath(env);
9107
+ const context = await resolveHostedContext({
9108
+ profileName: options.profileName,
9109
+ env,
9110
+ configPath: path,
9111
+ tokenProvider: options.tokenProvider
9112
+ });
9113
+ if (!context.apiUrl || !context.apiKey || !context.tenantId) {
9114
+ process.stderr.write("No complete hosted profile. Run fx login.\n");
9115
+ return 1;
9116
+ }
9117
+ const client = new ApiClient({
9118
+ baseUrl: context.apiUrl,
9119
+ apiKey: context.apiKey,
9120
+ bearerToken: context.bearerToken,
9121
+ defaultOrgId: context.tenantId,
9122
+ fetchImpl: options.fetchImpl
9123
+ });
9124
+ const tenant = await client.tenants.me();
9125
+ const privatePermissions = await configPermissionsArePrivate(path);
9126
+ process.stdout.write(
9127
+ [
9128
+ "Fabric CLI doctor",
9129
+ ` Profile: ${context.profileName ?? "(environment)"}`,
9130
+ ` API: ${context.apiUrl}`,
9131
+ ` Organization: ${tenant.organization.name} (${tenant.organization.id})`,
9132
+ ` Role: ${tenant.member.role}`,
9133
+ ` Gateway: ${context.bearerToken ? "authenticated" : "not required"}`,
9134
+ ` Config mode: ${privatePermissions ? "private" : "INSECURE"}`,
9135
+ ""
9136
+ ].join("\n")
9137
+ );
9138
+ return privatePermissions ? 0 : 2;
9139
+ }
9140
+ function normalizeApiUrl(value) {
9141
+ const url = new URL(value);
9142
+ if (!url.pathname || url.pathname === "/") url.pathname = "/api";
9143
+ return url.toString().replace(/\/$/, "");
9144
+ }
9145
+ function formatProfile(name, profile, active) {
9146
+ return `${active ? "*" : " "} ${name} \u2014 ${profile.organizationName ?? profile.orgId} (${profile.role ?? "unknown"})
9147
+ ${profile.apiUrl}
9148
+ `;
9149
+ }
9150
+ async function readSecretApiKey() {
9151
+ if (!process$1.stdin.isTTY || typeof process$1.stdin.setRawMode !== "function") {
9152
+ throw new Error("Set FX_API_KEY or pass --api-key when stdin is not interactive");
9153
+ }
9154
+ process$1.stderr.write("Fabric API key: ");
9155
+ process$1.stdin.setRawMode(true);
9156
+ process$1.stdin.resume();
9157
+ return new Promise((resolve11, reject) => {
9158
+ let value = "";
9159
+ const onData = (chunk) => {
9160
+ const text = chunk.toString("utf8");
9161
+ if (text === "") {
9162
+ cleanup();
9163
+ reject(new Error("Login canceled"));
9164
+ return;
9165
+ }
9166
+ if (text === "\r" || text === "\n") {
9167
+ cleanup();
9168
+ process$1.stderr.write("\n");
9169
+ resolve11(value.trim());
9170
+ return;
9171
+ }
9172
+ if (text === "\x7F") value = value.slice(0, -1);
9173
+ else value += text;
9174
+ };
9175
+ const cleanup = () => {
9176
+ process$1.stdin.off("data", onData);
9177
+ process$1.stdin.setRawMode(false);
9178
+ process$1.stdin.pause();
9179
+ };
9180
+ process$1.stdin.on("data", onData);
9181
+ });
9182
+ }
9183
+ var registry = databricksTestkit.createTargetPackRegistry(databricksTestkit.builtinTargetPacks);
9184
+ async function cmdTargets(action, packId, options = {}) {
9185
+ const stdout = options.stdout ?? process.stdout;
9186
+ const stderr2 = options.stderr ?? process.stderr;
9187
+ const env = { ...options.env ?? process.env };
9188
+ if (action === "list") {
9189
+ const packs = [...registry.values()].map(describePack);
9190
+ if (options.json) {
9191
+ stdout.write(`${JSON.stringify({ packs }, null, 2)}
9192
+ `);
9193
+ } else {
9194
+ stdout.write("ID MATURITY VERSION CAPABILITIES NAME\n");
9195
+ for (const pack2 of packs) {
9196
+ stdout.write(
9197
+ `${pack2.id.padEnd(19)} ${pack2.maturity.padEnd(12)} ${pack2.version.padEnd(8)} ${String(pack2.capabilityCount).padEnd(13)} ${pack2.name}
9198
+ `
9199
+ );
9200
+ }
9201
+ }
9202
+ return 0;
9203
+ }
9204
+ if (!packId) {
9205
+ stderr2.write(`Usage: fx targets ${action || "<list|doctor|run>"} <pack> [flags]
9206
+ `);
9207
+ return 1;
9208
+ }
9209
+ const pack = registry.get(packId);
9210
+ if (!pack) {
9211
+ stderr2.write(
9212
+ `Unknown target pack '${packId}'. Available: ${[...registry.keys()].join(", ")}
9213
+ `
9214
+ );
9215
+ return 1;
9216
+ }
9217
+ const requiredChecks = options.requiredChecks ?? pack.requiredChecks;
9218
+ const doctor = databricksTestkit.doctorTargetPack(pack, env, requiredChecks);
9219
+ if (action === "doctor") {
9220
+ writeDoctor(doctor, options.json === true, stdout);
9221
+ return doctor.ready ? 0 : 1;
9222
+ }
9223
+ if (action !== "run") {
9224
+ stderr2.write(`Unknown targets action '${action}'. Use list, doctor, run, or publish.
9225
+ `);
9226
+ return 1;
9227
+ }
9228
+ if (options.live) env.DBX_TEST_LIVE = "1";
9229
+ if (env.DBX_TEST_LIVE !== "1") {
9230
+ stderr2.write(
9231
+ "Target packs can create or mutate Databricks resources. Pass --live or set DBX_TEST_LIVE=1.\n"
9232
+ );
9233
+ return 1;
9234
+ }
9235
+ if (!doctor.ready) {
9236
+ writeDoctor(doctor, options.json === true, stderr2);
9237
+ return 1;
9238
+ }
9239
+ const evidencePath = options.evidencePath ?? `reports/target-packs/${pack.id}/evidence.json`;
9240
+ const junitPath = options.junitPath ?? `reports/target-packs/${pack.id}/junit.xml`;
9241
+ const evidence = await databricksTestkit.runTargetPack(pack, {
9242
+ env,
9243
+ requiredChecks,
9244
+ evidencePath,
9245
+ junitPath
9246
+ });
9247
+ if (!evidence) {
9248
+ stderr2.write("Target pack did not run because DBX_TEST_LIVE is disabled.\n");
9249
+ return 1;
9250
+ }
9251
+ if (options.json) {
9252
+ stdout.write(`${JSON.stringify(evidence, null, 2)}
9253
+ `);
9254
+ } else {
9255
+ for (const result of evidence.results) {
9256
+ stdout.write(`${symbol(result.status)} ${result.id} (${result.durationMs}ms)
9257
+ `);
9258
+ }
9259
+ stdout.write(
9260
+ `${evidence.success ? "PASS" : "FAIL"} ${pack.name}; evidence=${evidencePath}; junit=${junitPath}
9261
+ `
9262
+ );
9263
+ }
9264
+ return evidence.success ? 0 : 1;
9265
+ }
9266
+ async function cmdTargetPublish(evidencePath, options = {}) {
9267
+ const raw = JSON.parse(await promises.readFile(evidencePath, "utf8"));
9268
+ const metadata = objectOf2(raw.targetPack);
9269
+ const packName = typeof metadata.name === "string" ? metadata.name : void 0;
9270
+ const packId = typeof metadata.id === "string" ? metadata.id : void 0;
9271
+ if (!packName && !packId) {
9272
+ throw new Error("Target evidence is missing targetPack metadata");
9273
+ }
9274
+ return cmdTestPublish(evidencePath, {
9275
+ ...options,
9276
+ suite: options.suite ?? `Databricks target: ${packName ?? packId}`
9277
+ });
9278
+ }
9279
+ function describePack(pack) {
9280
+ return {
9281
+ id: pack.id,
9282
+ name: pack.name,
9283
+ description: pack.description,
9284
+ version: pack.version,
9285
+ maturity: pack.maturity,
9286
+ capabilityCount: pack.capabilities.length,
9287
+ capabilities: [...pack.capabilities],
9288
+ requiredChecks: [...pack.requiredChecks ?? []],
9289
+ docsUrl: pack.docsUrl,
9290
+ certificationScopes: [...pack.certificationScopes ?? []]
9291
+ };
9292
+ }
9293
+ function writeDoctor(doctor, json, stream) {
9294
+ if (json) {
9295
+ stream.write(`${JSON.stringify(doctor, null, 2)}
9296
+ `);
9297
+ return;
9298
+ }
9299
+ stream.write(
9300
+ `${doctor.ready ? "READY" : "NOT READY"} ${doctor.pack.name} ${doctor.pack.version} (${doctor.pack.maturity})
9301
+ `
9302
+ );
9303
+ for (const requirement of doctor.requirements) {
9304
+ stream.write(
9305
+ `${requirement.satisfied ? "\u2713" : requirement.required ? "\u2717" : "-"} requirement ${requirement.id}: ${requirement.description} [${requirement.variables.join(" | ")}]
9306
+ `
9307
+ );
9308
+ }
9309
+ for (const check of doctor.checks) {
9310
+ stream.write(
9311
+ `${check.configured ? "\u2713" : check.required ? "\u2717" : "-"} check ${check.id}${check.required ? " [required]" : ""}: ${check.description}
9312
+ `
9313
+ );
9314
+ }
9315
+ }
9316
+ function symbol(status) {
9317
+ if (status === "pass") return "\u2713";
9318
+ if (status === "fail") return "\u2717";
9319
+ return "-";
9320
+ }
9321
+ function objectOf2(value) {
9322
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
9323
+ }
8815
9324
 
8816
9325
  // src/bin/fx.ts
8817
9326
  var HELP = `fx \u2014 Fabric Experiments CLI
@@ -8833,6 +9342,14 @@ COMMANDS
8833
9342
  test env <action> Create, destroy, list, or reap Databricks test environments.
8834
9343
  test publish <file> Publish BDD/live/JUnit/CLI evidence to Studio Quality.
8835
9344
  init databricks-tests Scaffold a Databricks BDD test project.
9345
+ login Configure and verify a secure hosted profile.
9346
+ logout [profile] Remove a stored hosted profile.
9347
+ profile [list|show|use] Inspect or switch hosted profiles.
9348
+ doctor Verify API, tenant, gateway, role, and config security.
9349
+ targets list List built-in Databricks target packs.
9350
+ targets doctor <pack> Validate target configuration without creating resources.
9351
+ targets run <pack> Run a pack and write JSON/JUnit evidence. Requires --live.
9352
+ targets publish <file> Publish target-pack evidence to Studio Quality.
8836
9353
 
8837
9354
  GLOBAL FLAGS
8838
9355
  --tenant <id> Tenant scope (default: default)
@@ -8849,6 +9366,9 @@ GLOBAL FLAGS
8849
9366
  --static <dir> publish: write signed manifest + tag-loader bundle to <dir>
8850
9367
  --api-url <url> push/preview/test publish: hosted API base URL
8851
9368
  --api-key <key> push/preview/test publish: hosted API key
9369
+ --profile <name> hosted profile (default: active profile)
9370
+ --studio-url <url> login: branded Studio URL
9371
+ --databricks-profile <p> login: Databricks CLI profile used for Apps OAuth
8852
9372
  --no-publish push: apply actions without publishing manifest
8853
9373
  --name <name> test env: environment name (for example pr-1234)
8854
9374
  --seed <dir> test env create: JSON fixture directory
@@ -8860,6 +9380,10 @@ GLOBAL FLAGS
8860
9380
  --suite <name> test publish: display name for the suite
8861
9381
  --external-id <id> test publish: idempotent CI run identifier
8862
9382
  --run-url <url> test publish: CI artifact/run link
9383
+ --live targets run: explicitly allow live Databricks operations
9384
+ --required <ids> targets run: comma-separated required check IDs
9385
+ --evidence <file> targets run: evidence JSON output path
9386
+ --junit <file> targets run: JUnit XML output path
8863
9387
  --key-id <id> publish: keyId to sign with (default: dev-default)
8864
9388
  --out <dir> import-mojito: output directory
8865
9389
  --report <file> import-mojito: compatibility report path
@@ -8867,7 +9391,7 @@ GLOBAL FLAGS
8867
9391
  -h, --help print this help
8868
9392
  -v, --version print version
8869
9393
  `;
8870
- var VERSION2 = "0.6.5";
9394
+ var VERSION2 = "0.8.0";
8871
9395
  function parse2(argv) {
8872
9396
  const positional = [];
8873
9397
  const flags = {};
@@ -8912,13 +9436,64 @@ async function main() {
8912
9436
  `);
8913
9437
  return 0;
8914
9438
  }
8915
- const tenantId = args.flags.tenant ?? "default";
9439
+ const explicitTenantId = args.flags.tenant;
9440
+ const tenantId = explicitTenantId ?? "default";
8916
9441
  const allowDeletes = args.flags["allow-deletes"] === true;
8917
9442
  switch (args.command) {
8918
9443
  case "":
8919
9444
  case "help":
8920
9445
  process.stdout.write(HELP);
8921
9446
  return 0;
9447
+ case "login":
9448
+ return cmdLogin({
9449
+ profileName: args.flags.profile,
9450
+ studioUrl: args.flags["studio-url"],
9451
+ apiUrl: args.flags["api-url"],
9452
+ apiKey: args.flags["api-key"],
9453
+ tenantId: explicitTenantId,
9454
+ databricksProfile: args.flags["databricks-profile"]
9455
+ });
9456
+ case "logout":
9457
+ return cmdLogout(args.positional[0] ?? args.flags.profile);
9458
+ case "profile":
9459
+ return cmdProfile(
9460
+ args.positional[0] ?? "list",
9461
+ args.positional[1] ?? args.flags.profile
9462
+ );
9463
+ case "doctor":
9464
+ return cmdDoctor({ profileName: args.flags.profile });
9465
+ case "targets": {
9466
+ const action = args.positional[0] ?? "list";
9467
+ if (action === "publish") {
9468
+ const evidencePath = args.positional[1];
9469
+ if (!evidencePath) {
9470
+ process.stderr.write("Usage: fx targets publish <evidence.json> [flags]\n");
9471
+ return 1;
9472
+ }
9473
+ const hosted = await resolveHostedContext({
9474
+ profileName: args.flags.profile,
9475
+ apiUrl: args.flags["api-url"],
9476
+ apiKey: args.flags["api-key"],
9477
+ tenantId: explicitTenantId
9478
+ });
9479
+ return cmdTargetPublish(evidencePath, {
9480
+ tenantId: hosted.tenantId,
9481
+ apiUrl: hosted.apiUrl,
9482
+ apiKey: hosted.apiKey,
9483
+ bearerToken: hosted.bearerToken,
9484
+ suite: args.flags.suite,
9485
+ externalId: args.flags["external-id"],
9486
+ runUrl: args.flags["run-url"]
9487
+ });
9488
+ }
9489
+ return cmdTargets(action, args.positional[1], {
9490
+ json: args.flags.json === true,
9491
+ live: args.flags.live === true,
9492
+ requiredChecks: typeof args.flags.required === "string" ? args.flags.required.split(",").map((value) => value.trim()).filter(Boolean) : void 0,
9493
+ evidencePath: args.flags.evidence,
9494
+ junitPath: args.flags.junit
9495
+ });
9496
+ }
8922
9497
  case "validate":
8923
9498
  return cmdValidate(args.positional[0] ?? ".");
8924
9499
  case "plan":
@@ -8937,17 +9512,25 @@ async function main() {
8937
9512
  dryRun: args.flags["dry-run"] === true,
8938
9513
  allowDeletes
8939
9514
  });
8940
- case "push":
9515
+ case "push": {
9516
+ const hosted = await resolveHostedContext({
9517
+ profileName: args.flags.profile,
9518
+ apiUrl: args.flags["api-url"],
9519
+ apiKey: args.flags["api-key"],
9520
+ tenantId: explicitTenantId
9521
+ });
8941
9522
  return cmdPush(args.positional[0] ?? ".", {
8942
- tenantId,
9523
+ tenantId: hosted.tenantId,
8943
9524
  ownerId: args.flags.owner,
8944
9525
  approverId: args.flags.approver,
8945
9526
  dryRun: args.flags["dry-run"] === true,
8946
9527
  allowDeletes,
8947
- apiUrl: args.flags["api-url"],
8948
- apiKey: args.flags["api-key"],
9528
+ apiUrl: hosted.apiUrl,
9529
+ apiKey: hosted.apiKey,
9530
+ bearerToken: hosted.bearerToken,
8949
9531
  publish: args.flags["no-publish"] !== true
8950
9532
  });
9533
+ }
8951
9534
  case "dev":
8952
9535
  return cmdDev({
8953
9536
  port: args.flags.port ? Number(args.flags.port) : void 0,
@@ -8990,32 +9573,47 @@ async function main() {
8990
9573
  outputDir: args.flags.out,
8991
9574
  reportFile: args.flags.report,
8992
9575
  strict: args.flags.strict === true});
8993
- case "preview":
9576
+ case "preview": {
8994
9577
  if (!args.positional[0]) {
8995
9578
  process.stderr.write(
8996
9579
  "Usage: fx preview <experimentId> --variant <key> [--ttl 900] [--origin https://...] [--api-url ... --api-key ...]\n"
8997
9580
  );
8998
9581
  return 1;
8999
9582
  }
9583
+ const hosted = args.flags.local === true ? {} : await resolveHostedContext({
9584
+ profileName: args.flags.profile,
9585
+ apiUrl: args.flags["api-url"],
9586
+ apiKey: args.flags["api-key"],
9587
+ tenantId: explicitTenantId
9588
+ });
9000
9589
  return cmdPreview(args.positional[0], {
9001
- tenantId,
9590
+ tenantId: hosted.tenantId ?? tenantId,
9002
9591
  variantKey: typeof args.flags.variant === "string" ? args.flags.variant : "",
9003
9592
  ttlSeconds: args.flags.ttl ? Number(args.flags.ttl) : void 0,
9004
9593
  origin: args.flags.origin,
9005
- apiUrl: args.flags["api-url"],
9006
- apiKey: args.flags["api-key"],
9594
+ apiUrl: hosted.apiUrl,
9595
+ apiKey: hosted.apiKey,
9596
+ bearerToken: hosted.bearerToken,
9007
9597
  local: args.flags.local === true
9008
9598
  });
9599
+ }
9009
9600
  case "test":
9010
9601
  if (args.positional[0] === "publish") {
9011
9602
  if (!args.positional[1]) {
9012
9603
  process.stderr.write("Usage: fx test publish <evidence.json|junit.xml> [flags]\n");
9013
9604
  return 1;
9014
9605
  }
9015
- return cmdTestPublish(args.positional[1], {
9016
- tenantId,
9606
+ const hosted = await resolveHostedContext({
9607
+ profileName: args.flags.profile,
9017
9608
  apiUrl: args.flags["api-url"],
9018
9609
  apiKey: args.flags["api-key"],
9610
+ tenantId: explicitTenantId
9611
+ });
9612
+ return cmdTestPublish(args.positional[1], {
9613
+ tenantId: hosted.tenantId,
9614
+ apiUrl: hosted.apiUrl,
9615
+ apiKey: hosted.apiKey,
9616
+ bearerToken: hosted.bearerToken,
9019
9617
  suite: args.flags.suite,
9020
9618
  externalId: args.flags["external-id"],
9021
9619
  runUrl: args.flags["run-url"]