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