@fabricorg/experiments 0.5.2 → 0.6.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/index.cjs CHANGED
@@ -1,12 +1,16 @@
1
1
  'use strict';
2
2
 
3
- var path = require('path');
4
3
  var fs = require('fs');
4
+ var path = require('path');
5
5
  var crypto$1 = require('crypto');
6
6
  var promises = require('fs/promises');
7
- var yaml = require('yaml');
7
+ var experimentsYaml = require('@fabricorg/experiments-yaml');
8
8
  var http = require('http');
9
+ var module$1 = require('module');
10
+ var yaml = require('yaml');
11
+ var databricksTestkit = require('@fabricorg/databricks-testkit');
9
12
 
13
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
10
14
  var __defProp = Object.defineProperty;
11
15
  var __export = (target, all) => {
12
16
  for (var name in all)
@@ -4066,23 +4070,131 @@ var ExperimentState = external_exports.enum([
4066
4070
  "archived"
4067
4071
  ]);
4068
4072
  var VariantKey = external_exports.string().min(1).max(32).regex(/^[a-z0-9_-]+$/);
4073
+ var JsSource = external_exports.string().max(5e4).refine(
4074
+ (source) => {
4075
+ try {
4076
+ new Function("experiment", "variant", source);
4077
+ return true;
4078
+ } catch {
4079
+ return false;
4080
+ }
4081
+ },
4082
+ { message: "JavaScript contains a syntax error" }
4083
+ );
4084
+ var CssSource = external_exports.string().max(5e4);
4085
+ var DomOp = external_exports.discriminatedUnion("op", [
4086
+ external_exports.object({
4087
+ op: external_exports.literal("replaceText"),
4088
+ selector: external_exports.string().min(1).max(512),
4089
+ value: external_exports.string().max(1e4),
4090
+ waitForMs: external_exports.number().int().min(0).max(3e4).optional()
4091
+ }),
4092
+ external_exports.object({
4093
+ op: external_exports.literal("replaceHTML"),
4094
+ selector: external_exports.string().min(1).max(512),
4095
+ value: external_exports.string().max(5e4),
4096
+ waitForMs: external_exports.number().int().min(0).max(3e4).optional()
4097
+ }),
4098
+ external_exports.object({
4099
+ op: external_exports.literal("setAttr"),
4100
+ selector: external_exports.string().min(1).max(512),
4101
+ name: external_exports.string().min(1).max(128),
4102
+ value: external_exports.string().max(2048),
4103
+ waitForMs: external_exports.number().int().min(0).max(3e4).optional()
4104
+ }),
4105
+ external_exports.object({
4106
+ op: external_exports.literal("addClass"),
4107
+ selector: external_exports.string().min(1).max(512),
4108
+ value: external_exports.string().min(1).max(256),
4109
+ waitForMs: external_exports.number().int().min(0).max(3e4).optional()
4110
+ }),
4111
+ external_exports.object({
4112
+ op: external_exports.literal("removeClass"),
4113
+ selector: external_exports.string().min(1).max(512),
4114
+ value: external_exports.string().min(1).max(256),
4115
+ waitForMs: external_exports.number().int().min(0).max(3e4).optional()
4116
+ }),
4117
+ external_exports.object({
4118
+ op: external_exports.literal("setStyle"),
4119
+ selector: external_exports.string().min(1).max(512),
4120
+ name: external_exports.string().min(1).max(128),
4121
+ value: external_exports.string().max(2048),
4122
+ waitForMs: external_exports.number().int().min(0).max(3e4).optional()
4123
+ }),
4124
+ external_exports.object({
4125
+ op: external_exports.literal("remove"),
4126
+ selector: external_exports.string().min(1).max(512),
4127
+ waitForMs: external_exports.number().int().min(0).max(3e4).optional()
4128
+ }),
4129
+ external_exports.object({
4130
+ op: external_exports.literal("injectCSS"),
4131
+ value: external_exports.string().min(1).max(5e4)
4132
+ }),
4133
+ external_exports.object({
4134
+ op: external_exports.literal("injectHTML"),
4135
+ selector: external_exports.string().min(1).max(512),
4136
+ position: external_exports.enum(["beforeend", "afterbegin", "beforebegin", "afterend"]),
4137
+ value: external_exports.string().max(5e4),
4138
+ waitForMs: external_exports.number().int().min(0).max(3e4).optional()
4139
+ })
4140
+ ]);
4069
4141
  var Variant = external_exports.object({
4070
4142
  key: VariantKey,
4071
4143
  name: external_exports.string().min(1).max(120),
4072
4144
  /** Cumulative split weight in [0, 10000]; M1 ships even-split if all weights are 0/undefined. */
4073
4145
  weight: external_exports.number().int().min(0).max(1e4).optional(),
4074
4146
  /** Optional inline JS payload that the Web SDK eval-applies under try/catch. */
4075
- js: external_exports.string().optional(),
4147
+ js: JsSource.optional(),
4076
4148
  /** Optional inline CSS payload that the Web SDK injects via <style>. */
4077
- css: external_exports.string().optional(),
4149
+ css: CssSource.optional(),
4150
+ /** Declarative DOM ops applied by the Web SDK after assignment (Mojito-parity). */
4151
+ domOps: external_exports.array(DomOp).optional(),
4152
+ /**
4153
+ * Mojito-parity: independent gate per variant. After bucketing selects this
4154
+ * variant, a second deterministic sample compares against `recipeSampleRate`.
4155
+ * Below the threshold, the SDK is "in-test but no recipe" and emits no
4156
+ * exposure. Distinct from `weight` (bucket split) and `audience.sampleRate`
4157
+ * (test-level eligibility).
4158
+ */
4159
+ recipeSampleRate: external_exports.number().min(0).max(1).optional(),
4078
4160
  /** Arbitrary feature payload available to server SDKs. */
4079
4161
  payload: external_exports.record(external_exports.unknown()).optional()
4080
4162
  });
4163
+ var Trigger = external_exports.discriminatedUnion("kind", [
4164
+ external_exports.object({ kind: external_exports.literal("auto") }),
4165
+ external_exports.object({
4166
+ kind: external_exports.literal("urlMatch"),
4167
+ /** Substring or regex source. If `regex` is true, pattern is a JS regex source. */
4168
+ pattern: external_exports.string().min(1).max(1024),
4169
+ regex: external_exports.boolean().optional()
4170
+ }),
4171
+ external_exports.object({
4172
+ kind: external_exports.literal("waitForSelector"),
4173
+ selector: external_exports.string().min(1).max(512),
4174
+ timeoutMs: external_exports.number().int().min(0).max(6e4).default(2e3)
4175
+ }),
4176
+ external_exports.object({
4177
+ kind: external_exports.literal("event"),
4178
+ name: external_exports.string().min(1).max(128)
4179
+ })
4180
+ ]);
4181
+ var TargetingRule = external_exports.union([
4182
+ external_exports.boolean(),
4183
+ external_exports.number(),
4184
+ external_exports.string(),
4185
+ external_exports.array(external_exports.unknown()),
4186
+ external_exports.record(external_exports.unknown())
4187
+ ]);
4081
4188
  var Audience = external_exports.object({
4082
4189
  /** Sample rate in [0, 1] of eligible traffic that the experiment applies to. */
4083
4190
  sampleRate: external_exports.number().min(0).max(1).default(1),
4084
- /** Optional human-readable rule expression; M1 ignores it (always-eligible). */
4085
- rule: external_exports.string().optional()
4191
+ /**
4192
+ * Optional targeting rule — a JSONLogic-style AST evaluated against
4193
+ * `targetingContext` (browser SDK) or `ctx.user` (server SDK). When the
4194
+ * rule evaluates to `false` for the current subject, the SDK returns
4195
+ * `null` from `treatment()` and emits no exposure.
4196
+ */
4197
+ rule: TargetingRule.optional()
4086
4198
  });
4087
4199
  var MetricKind = external_exports.enum(["conversion", "count", "sum"]);
4088
4200
  var Metric = external_exports.object({
@@ -4099,7 +4211,17 @@ var Approval = external_exports.object({
4099
4211
  approvedAt: external_exports.string().datetime(),
4100
4212
  note: external_exports.string().max(2e3).optional()
4101
4213
  });
4102
- external_exports.object({
4214
+ var DatabricksWorkload = external_exports.object({
4215
+ kind: external_exports.enum(["sql", "notebook", "job", "pipeline", "model", "feature-serving"]),
4216
+ resourceId: external_exports.string().min(1).max(256),
4217
+ resourceName: external_exports.string().min(1).max(256).optional(),
4218
+ evaluationMode: external_exports.enum(["online", "offline", "shadow"]).default("online"),
4219
+ assignmentUnit: external_exports.enum(["user", "request", "job-run", "table-partition"]).default("request"),
4220
+ catalog: external_exports.string().min(1).max(255).optional(),
4221
+ schema: external_exports.string().min(1).max(255).optional(),
4222
+ tags: external_exports.record(external_exports.string()).optional()
4223
+ });
4224
+ var Experiment = external_exports.object({
4103
4225
  id: ExperimentId,
4104
4226
  name: external_exports.string().min(1).max(200),
4105
4227
  description: external_exports.string().max(4e3).optional(),
@@ -4109,23 +4231,64 @@ external_exports.object({
4109
4231
  audience: Audience,
4110
4232
  variants: external_exports.array(Variant).min(2),
4111
4233
  metrics: external_exports.array(Metric).default([]),
4234
+ /** Activation trigger for Web SDK. Defaults to `{ kind: 'auto' }`. */
4235
+ trigger: Trigger.optional(),
4236
+ /** When true, SDK assigns + applies but defers `onExposure` until host calls `client.expose(id)`. */
4237
+ manualExposure: external_exports.boolean().optional(),
4238
+ /** When set to a variant key, all eligible traffic is routed to that variant (Mojito `divertTo`). */
4239
+ divertTo: VariantKey.optional(),
4240
+ /** Mojito-parity: shared JS that runs once per (experiment, page) before any variant code. */
4241
+ sharedJs: JsSource.optional(),
4242
+ /** Mojito-parity: shared CSS injected once per (experiment, page) before any variant CSS. */
4243
+ sharedCss: CssSource.optional(),
4244
+ /** Per-experiment metadata accessible to variant code via `client.metadata(id)`. */
4245
+ metadata: external_exports.record(external_exports.unknown()).optional(),
4112
4246
  approval: Approval.nullable().default(null),
4113
4247
  killReason: external_exports.string().max(500).nullable().default(null),
4114
4248
  ownerId: external_exports.string().min(1),
4115
4249
  tenantId: external_exports.string().min(1).default("default"),
4250
+ /** Optional Mojito-style hierarchy bindings. Legacy experiments remain tenant-scoped. */
4251
+ projectId: external_exports.string().uuid().optional(),
4252
+ propertyId: external_exports.string().uuid().optional(),
4253
+ featureId: external_exports.string().uuid().optional(),
4254
+ environmentIds: external_exports.array(external_exports.string().uuid()).optional(),
4255
+ workload: DatabricksWorkload.optional(),
4116
4256
  createdAt: external_exports.string().datetime(),
4117
4257
  updatedAt: external_exports.string().datetime(),
4118
4258
  startedAt: external_exports.string().datetime().nullable().default(null),
4119
4259
  endedAt: external_exports.string().datetime().nullable().default(null)
4120
4260
  });
4121
- var ExperimentSpec = external_exports.object({
4261
+ var ExperimentSpecBase = external_exports.object({
4122
4262
  id: ExperimentId,
4123
4263
  name: external_exports.string().min(1).max(200),
4124
4264
  description: external_exports.string().max(4e3).optional(),
4265
+ projectId: external_exports.string().uuid().optional(),
4266
+ propertyId: external_exports.string().uuid().optional(),
4267
+ featureId: external_exports.string().uuid().optional(),
4268
+ environmentIds: external_exports.array(external_exports.string().uuid()).optional(),
4269
+ workload: DatabricksWorkload.optional(),
4125
4270
  salt: external_exports.string().min(1).max(64).optional(),
4126
4271
  sampleRate: external_exports.number().min(0).max(1).optional(),
4272
+ /**
4273
+ * Mojito-parity sugar: fraction of the eligible cohort held out of the test entirely.
4274
+ * `holdback: 0.1` means 10% of eligible traffic is excluded; the remainder is split
4275
+ * across variants per their weights. Compiles to `audience.sampleRate = 1 - holdback`.
4276
+ */
4277
+ holdback: external_exports.number().min(0).max(1).optional(),
4127
4278
  audience: Audience.partial().optional(),
4128
4279
  variants: external_exports.array(Variant).min(2),
4280
+ /** Mojito-parity: route all eligible traffic to a single variant key. */
4281
+ divertTo: VariantKey.optional(),
4282
+ /** Mojito-parity: defer exposure until host calls `client.expose(id)`. */
4283
+ manualExposure: external_exports.boolean().optional(),
4284
+ /** Activation trigger for Web SDK. */
4285
+ trigger: Trigger.optional(),
4286
+ /** Mojito-parity: shared JS that runs once before any variant code. */
4287
+ sharedJs: JsSource.optional(),
4288
+ /** Mojito-parity: shared CSS injected once before any variant CSS. */
4289
+ sharedCss: CssSource.optional(),
4290
+ /** Per-experiment metadata accessible via `client.metadata(id)`. */
4291
+ metadata: external_exports.record(external_exports.unknown()).optional(),
4129
4292
  metrics: external_exports.array(
4130
4293
  external_exports.object({
4131
4294
  key: external_exports.string().min(1).max(64),
@@ -4137,6 +4300,25 @@ var ExperimentSpec = external_exports.object({
4137
4300
  })
4138
4301
  ).optional()
4139
4302
  });
4303
+ var ExperimentSpec = ExperimentSpecBase.refine(
4304
+ (s) => s.holdback === void 0 || s.sampleRate === void 0,
4305
+ { message: "Use either `sampleRate` or `holdback`, not both.", path: ["holdback"] }
4306
+ ).refine((s) => s.divertTo === void 0 || s.variants.some((v) => v.key === s.divertTo), {
4307
+ message: "`divertTo` must reference an existing variant key.",
4308
+ path: ["divertTo"]
4309
+ }).refine(
4310
+ (s) => {
4311
+ const withWeight = s.variants.filter((v) => v.weight !== void 0);
4312
+ if (withWeight.length === 0) return true;
4313
+ if (withWeight.length !== s.variants.length) return false;
4314
+ const sum = withWeight.reduce((acc, v) => acc + (v.weight ?? 0), 0);
4315
+ return sum === 1e4;
4316
+ },
4317
+ {
4318
+ message: "When variant weights are set, all variants must have weights summing to 10000.",
4319
+ path: ["variants"]
4320
+ }
4321
+ );
4140
4322
  external_exports.object({
4141
4323
  experimentId: ExperimentId,
4142
4324
  subjectId: external_exports.string().min(1),
@@ -4182,7 +4364,132 @@ function canTransition(current, event2) {
4182
4364
  function isLive(state) {
4183
4365
  return state === "running" || state === "paused";
4184
4366
  }
4185
- external_exports.enum([
4367
+ var ResourceKey = external_exports.string().min(2).max(64).regex(/^[a-z][a-z0-9_-]*$/, "lowercase key, must start with a letter");
4368
+ var ResourceBase = external_exports.object({
4369
+ id: external_exports.string().uuid(),
4370
+ tenantId: external_exports.string().min(1),
4371
+ key: ResourceKey,
4372
+ name: external_exports.string().min(1).max(200),
4373
+ description: external_exports.string().max(4e3).optional(),
4374
+ createdAt: external_exports.string().datetime(),
4375
+ updatedAt: external_exports.string().datetime()
4376
+ });
4377
+ var Project = ResourceBase.extend({
4378
+ kind: external_exports.literal("project")
4379
+ });
4380
+ var Property = ResourceBase.extend({
4381
+ kind: external_exports.literal("property"),
4382
+ projectId: external_exports.string().uuid(),
4383
+ platform: external_exports.enum(["web", "server", "mobile", "databricks"]),
4384
+ origins: external_exports.array(external_exports.string().url()).default([])
4385
+ });
4386
+ var EnvironmentTier = external_exports.enum(["development", "staging", "production"]);
4387
+ var Environment = ResourceBase.extend({
4388
+ kind: external_exports.literal("environment"),
4389
+ projectId: external_exports.string().uuid(),
4390
+ tier: EnvironmentTier,
4391
+ rank: external_exports.number().int().min(0).max(100),
4392
+ requiresApproval: external_exports.boolean().default(false)
4393
+ });
4394
+ var FeatureValue = external_exports.union([
4395
+ external_exports.boolean(),
4396
+ external_exports.string(),
4397
+ external_exports.number(),
4398
+ external_exports.record(external_exports.unknown()),
4399
+ external_exports.array(external_exports.unknown())
4400
+ ]);
4401
+ var Feature = ResourceBase.extend({
4402
+ kind: external_exports.literal("feature"),
4403
+ projectId: external_exports.string().uuid(),
4404
+ propertyId: external_exports.string().uuid().optional(),
4405
+ valueType: external_exports.enum(["boolean", "string", "number", "json"]),
4406
+ defaultValue: FeatureValue,
4407
+ archived: external_exports.boolean().default(false)
4408
+ });
4409
+ var FeatureRule = external_exports.object({
4410
+ id: external_exports.string().uuid(),
4411
+ kind: external_exports.literal("rule"),
4412
+ tenantId: external_exports.string().min(1),
4413
+ featureId: external_exports.string().uuid(),
4414
+ environmentId: external_exports.string().uuid(),
4415
+ name: external_exports.string().min(1).max(200),
4416
+ enabled: external_exports.boolean().default(true),
4417
+ priority: external_exports.number().int().min(0).max(1e4),
4418
+ audience: TargetingRule.optional(),
4419
+ experimentId: ExperimentId.optional(),
4420
+ variants: external_exports.array(Variant).min(2).optional(),
4421
+ value: FeatureValue.optional(),
4422
+ rolloutPercentage: external_exports.number().min(0).max(100).default(100),
4423
+ createdAt: external_exports.string().datetime(),
4424
+ updatedAt: external_exports.string().datetime()
4425
+ });
4426
+ var EnvironmentPublication = external_exports.object({
4427
+ id: external_exports.string().uuid(),
4428
+ kind: external_exports.literal("publication"),
4429
+ tenantId: external_exports.string().min(1),
4430
+ environmentId: external_exports.string().uuid(),
4431
+ version: external_exports.number().int().positive(),
4432
+ status: external_exports.literal("published"),
4433
+ resourceHash: external_exports.string().regex(/^[0-9a-f]{64}$/),
4434
+ manifestVersion: external_exports.number().int().nonnegative(),
4435
+ publishedBy: external_exports.string().min(1),
4436
+ publishedAt: external_exports.string().datetime(),
4437
+ snapshot: external_exports.object({
4438
+ features: external_exports.array(Feature),
4439
+ rules: external_exports.array(FeatureRule)
4440
+ })
4441
+ });
4442
+ var WorkspaceResource = external_exports.discriminatedUnion("kind", [
4443
+ Project,
4444
+ Property,
4445
+ Environment,
4446
+ Feature,
4447
+ FeatureRule,
4448
+ EnvironmentPublication
4449
+ ]);
4450
+ var MutableWorkspaceResource = external_exports.discriminatedUnion("kind", [
4451
+ Project,
4452
+ Property,
4453
+ Environment,
4454
+ Feature,
4455
+ FeatureRule
4456
+ ]);
4457
+ var CreateProjectInput = Project.pick({ key: true, name: true, description: true });
4458
+ var CreatePropertyInput = Property.pick({
4459
+ key: true,
4460
+ name: true,
4461
+ description: true,
4462
+ platform: true,
4463
+ origins: true
4464
+ });
4465
+ var CreateEnvironmentInput = Environment.pick({
4466
+ key: true,
4467
+ name: true,
4468
+ description: true,
4469
+ tier: true,
4470
+ rank: true,
4471
+ requiresApproval: true
4472
+ });
4473
+ var CreateFeatureInput = Feature.pick({
4474
+ key: true,
4475
+ name: true,
4476
+ description: true,
4477
+ propertyId: true,
4478
+ valueType: true,
4479
+ defaultValue: true
4480
+ });
4481
+ var CreateFeatureRuleInput = FeatureRule.pick({
4482
+ name: true,
4483
+ environmentId: true,
4484
+ enabled: true,
4485
+ priority: true,
4486
+ audience: true,
4487
+ experimentId: true,
4488
+ variants: true,
4489
+ value: true,
4490
+ rolloutPercentage: true
4491
+ });
4492
+ var ActionId = external_exports.enum([
4186
4493
  "experiment.create",
4187
4494
  "experiment.submit_for_review",
4188
4495
  "experiment.approve",
@@ -4192,9 +4499,12 @@ external_exports.enum([
4192
4499
  "experiment.kill",
4193
4500
  "experiment.declare_winner",
4194
4501
  "experiment.update",
4195
- "experiment.guardrail_breach"
4502
+ "experiment.guardrail_breach",
4503
+ "experiment.workspace_resource_upsert",
4504
+ "experiment.environment_publish",
4505
+ "experiment.environment_promote"
4196
4506
  ]);
4197
- var CreateExperimentInput = ExperimentSpec.extend({
4507
+ var CreateExperimentInput = ExperimentSpecBase.extend({
4198
4508
  ownerId: external_exports.string().min(1),
4199
4509
  tenantId: external_exports.string().min(1).default("default")
4200
4510
  });
@@ -4229,6 +4539,21 @@ var GuardrailBreachInput = ExperimentRef.extend({
4229
4539
  /** When 'pause', the action also pauses the experiment as part of breach handling. */
4230
4540
  action: external_exports.enum(["alert", "pause"]).default("alert")
4231
4541
  });
4542
+ var UpsertWorkspaceResourceInput = external_exports.object({
4543
+ tenantId: external_exports.string().min(1),
4544
+ resource: MutableWorkspaceResource
4545
+ });
4546
+ var PublishEnvironmentInput = external_exports.object({
4547
+ tenantId: external_exports.string().min(1),
4548
+ environmentId: external_exports.string().uuid(),
4549
+ publishedBy: external_exports.string().min(1)
4550
+ });
4551
+ var PromoteEnvironmentInput = external_exports.object({
4552
+ tenantId: external_exports.string().min(1),
4553
+ sourceEnvironmentId: external_exports.string().uuid(),
4554
+ targetEnvironmentId: external_exports.string().uuid(),
4555
+ promotedBy: external_exports.string().min(1)
4556
+ });
4232
4557
  external_exports.enum([
4233
4558
  "experiment.created",
4234
4559
  "experiment.submitted_for_review",
@@ -4244,7 +4569,11 @@ external_exports.enum([
4244
4569
  "experiment.variant_updated",
4245
4570
  "manifest.published",
4246
4571
  "guardrail.breached",
4247
- "analysis.completed"
4572
+ "analysis.completed",
4573
+ "experiment.preview_signed",
4574
+ "workspace_resource.upserted",
4575
+ "environment.published",
4576
+ "environment.promoted"
4248
4577
  ]);
4249
4578
  var DomainError = class extends Error {
4250
4579
  constructor(message, code, details) {
@@ -4287,6 +4616,8 @@ var ManifestVariant = Variant.pick({
4287
4616
  weight: true,
4288
4617
  js: true,
4289
4618
  css: true,
4619
+ domOps: true,
4620
+ recipeSampleRate: true,
4290
4621
  payload: true
4291
4622
  });
4292
4623
  var ManifestExperiment = external_exports.object({
@@ -4301,7 +4632,25 @@ var ManifestExperiment = external_exports.object({
4301
4632
  /** Killed-or-paused short-circuit: when true, SDK must NOT execute variant code. */
4302
4633
  applyVariants: external_exports.boolean(),
4303
4634
  /** Optional default variant to return when paused. */
4304
- defaultVariantKey: VariantKey.optional()
4635
+ defaultVariantKey: VariantKey.optional(),
4636
+ /** Activation trigger; absent means `auto`. */
4637
+ trigger: Trigger.optional(),
4638
+ /** Defer exposure until host calls `client.expose(id)`. */
4639
+ manualExposure: external_exports.boolean().optional(),
4640
+ /** Route all eligible traffic to a single variant key. */
4641
+ divertTo: VariantKey.optional(),
4642
+ /** Shared JS that runs once before any variant code. */
4643
+ sharedJs: external_exports.string().optional(),
4644
+ /** Shared CSS injected once before any variant CSS. */
4645
+ sharedCss: external_exports.string().optional(),
4646
+ /** Per-experiment metadata accessible via `client.metadata(id)`. */
4647
+ metadata: external_exports.record(external_exports.unknown()).optional(),
4648
+ /**
4649
+ * Targeting rule (JSONLogic-style AST) evaluated against `targetingContext`
4650
+ * by the SDK. When false, the subject is ineligible — `treatment()` returns
4651
+ * null and no exposure is recorded.
4652
+ */
4653
+ targetingRule: external_exports.unknown().optional()
4305
4654
  });
4306
4655
  var ManifestSignature = external_exports.object({
4307
4656
  keyId: external_exports.string().min(1).max(128),
@@ -4364,7 +4713,7 @@ function buildManifest(args) {
4364
4713
  return Manifest.parse(manifest);
4365
4714
  }
4366
4715
  function toManifestExperiment(e) {
4367
- return {
4716
+ const out = {
4368
4717
  id: e.id,
4369
4718
  name: e.name,
4370
4719
  state: e.state === "running" ? "running" : "paused",
@@ -4376,11 +4725,21 @@ function toManifestExperiment(e) {
4376
4725
  weight: v.weight,
4377
4726
  js: v.js,
4378
4727
  css: v.css,
4728
+ domOps: v.domOps,
4729
+ recipeSampleRate: v.recipeSampleRate,
4379
4730
  payload: v.payload
4380
4731
  })),
4381
4732
  applyVariants: e.state === "running",
4382
4733
  defaultVariantKey: e.variants[0]?.key
4383
4734
  };
4735
+ if (e.trigger) out.trigger = e.trigger;
4736
+ if (e.manualExposure) out.manualExposure = true;
4737
+ if (e.divertTo) out.divertTo = e.divertTo;
4738
+ if (e.sharedJs) out.sharedJs = e.sharedJs;
4739
+ if (e.sharedCss) out.sharedCss = e.sharedCss;
4740
+ if (e.metadata) out.metadata = e.metadata;
4741
+ if (e.audience.rule !== void 0) out.targetingRule = e.audience.rule;
4742
+ return out;
4384
4743
  }
4385
4744
 
4386
4745
  // ../module/dist/index.js
@@ -4393,9 +4752,22 @@ var FileStore = class {
4393
4752
  const fs = await import('fs/promises');
4394
4753
  try {
4395
4754
  const text = await fs.readFile(this.path, "utf8");
4396
- return JSON.parse(text);
4755
+ const parsed = JSON.parse(text);
4756
+ return {
4757
+ experiments: parsed.experiments ?? {},
4758
+ events: parsed.events ?? [],
4759
+ manifestVersions: parsed.manifestVersions ?? {},
4760
+ resources: parsed.resources ?? {},
4761
+ resourceVersions: parsed.resourceVersions ?? {}
4762
+ };
4397
4763
  } catch {
4398
- return { experiments: {}, events: [], manifestVersions: {} };
4764
+ return {
4765
+ experiments: {},
4766
+ events: [],
4767
+ manifestVersions: {},
4768
+ resources: {},
4769
+ resourceVersions: {}
4770
+ };
4399
4771
  }
4400
4772
  }
4401
4773
  async save(state) {
@@ -4439,7 +4811,192 @@ var FileStore = class {
4439
4811
  await this.save(s);
4440
4812
  return v;
4441
4813
  }
4814
+ async getResource(tenantId, kind, id) {
4815
+ const s = await this.load();
4816
+ return s.resources[`${tenantId}/${kind}/${id}`] ?? null;
4817
+ }
4818
+ async listResources(tenantId, kind) {
4819
+ const s = await this.load();
4820
+ return Object.values(s.resources).filter(
4821
+ (resource) => resource.tenantId === tenantId && resource.kind === kind
4822
+ );
4823
+ }
4824
+ async putResource(resource) {
4825
+ const s = await this.load();
4826
+ s.resources[`${resource.tenantId}/${resource.kind}/${resource.id}`] = resource;
4827
+ await this.save(s);
4828
+ }
4829
+ async nextResourceVersion(tenantId, scope) {
4830
+ const s = await this.load();
4831
+ const key = `${tenantId}/${scope}`;
4832
+ const version = (s.resourceVersions[key] ?? 0) + 1;
4833
+ s.resourceVersions[key] = version;
4834
+ await this.save(s);
4835
+ return version;
4836
+ }
4837
+ };
4838
+ var experimentStateMachine = {
4839
+ transitions: [
4840
+ { from: "draft", to: "review", causedByAction: "experiment.submit_for_review" },
4841
+ { from: "review", to: "approved", causedByAction: "experiment.approve" },
4842
+ { from: "approved", to: "running", causedByAction: "experiment.start" },
4843
+ { from: "running", to: "paused", causedByAction: "experiment.pause" },
4844
+ { from: "paused", to: "running", causedByAction: "experiment.resume" },
4845
+ { from: "running", to: "killed", causedByAction: "experiment.kill" },
4846
+ { from: "paused", to: "killed", causedByAction: "experiment.kill" },
4847
+ { from: "running", to: "concluded", causedByAction: "experiment.declare_winner" }
4848
+ ]
4849
+ };
4850
+ var separationOfDuties = {
4851
+ policyId: "experiment.separation_of_duties.v1",
4852
+ version: 1,
4853
+ kind: "code",
4854
+ previewSafe: true,
4855
+ async evaluate(ctx) {
4856
+ const params = actionParams(ctx);
4857
+ const experiment = await findExperiment(ctx, params);
4858
+ const blocked = Boolean(
4859
+ experiment && typeof params.approverId === "string" && experiment.ownerId === params.approverId
4860
+ );
4861
+ return outcome(this, blocked, "The experiment owner cannot approve their own experiment.");
4862
+ }
4442
4863
  };
4864
+ var approvedToStart = {
4865
+ policyId: "experiment.approved_to_start.v1",
4866
+ version: 1,
4867
+ kind: "code",
4868
+ previewSafe: true,
4869
+ async evaluate(ctx) {
4870
+ const experiment = await findExperiment(ctx, actionParams(ctx));
4871
+ return outcome(
4872
+ this,
4873
+ Boolean(experiment && !experiment.approval),
4874
+ "An approval is required before start."
4875
+ );
4876
+ }
4877
+ };
4878
+ var variantSetFrozen = {
4879
+ policyId: "experiment.freeze_variant_set.v1",
4880
+ version: 1,
4881
+ kind: "code",
4882
+ previewSafe: true,
4883
+ async evaluate(ctx) {
4884
+ const params = actionParams(ctx);
4885
+ const experiment = await findExperiment(ctx, params);
4886
+ const variants = isRecord(params.spec) && Array.isArray(params.spec.variants) ? params.spec.variants : [];
4887
+ if (!experiment || !["running", "paused", "concluded"].includes(experiment.state)) {
4888
+ return outcome(this, false, "Variant identities are mutable before the experiment starts.");
4889
+ }
4890
+ const current = new Set(experiment.variants.map((variant) => variant.key));
4891
+ const next = new Set(
4892
+ variants.filter(isRecord).map((variant) => variant.key).filter((key) => typeof key === "string")
4893
+ );
4894
+ const changed = current.size !== next.size || [...current].some((variantKey) => !next.has(variantKey));
4895
+ return outcome(this, changed, "Variant set cannot change after start or exposure begins.");
4896
+ }
4897
+ };
4898
+ var experimentPolicies = [separationOfDuties, approvedToStart, variantSetFrozen];
4899
+ var policiesById = new Map(experimentPolicies.map((policy) => [policy.policyId, policy]));
4900
+ async function executeGovernedExperimentAction(definition, parameters, ctx) {
4901
+ const policyOutcomes = [];
4902
+ for (const policyId of definition.policies ?? []) {
4903
+ const policy = policiesById.get(policyId);
4904
+ if (!policy) {
4905
+ return { success: false, error: `Required policy is not registered: ${policyId}` };
4906
+ }
4907
+ policyOutcomes.push(
4908
+ await policy.evaluate({
4909
+ tenantId: ctx.tenantId,
4910
+ spaceId: ctx.spaceId,
4911
+ actionInvocationId: ctx.actionInvocationId,
4912
+ actionId: definition.actionId,
4913
+ parameters,
4914
+ db: ctx.db,
4915
+ services: ctx.services,
4916
+ mode: "execute"
4917
+ })
4918
+ );
4919
+ }
4920
+ if (policyOutcomes.length > 0) {
4921
+ await appendGovernanceEvent(ctx, parameters, "policy.evaluated", {
4922
+ actionId: definition.actionId,
4923
+ outcomes: policyOutcomes
4924
+ });
4925
+ const blocked = policyOutcomes.find((policy) => policy.result === "block");
4926
+ if (blocked) {
4927
+ return {
4928
+ success: false,
4929
+ error: `Policy ${blocked.policyId} blocked ${definition.actionId}: ${blocked.reason ?? "denied"}`
4930
+ };
4931
+ }
4932
+ }
4933
+ if (definition.stateMachine) {
4934
+ const transitionError = await validateCurrentTransition(definition, parameters, ctx);
4935
+ if (transitionError) {
4936
+ await appendGovernanceEvent(ctx, parameters, "state_transition.rejected", {
4937
+ actionId: definition.actionId,
4938
+ error: transitionError
4939
+ });
4940
+ return { success: false, error: transitionError };
4941
+ }
4942
+ }
4943
+ if (!definition.handler) {
4944
+ return { success: false, error: `Action ${definition.actionId} has no handler` };
4945
+ }
4946
+ return definition.handler(ctx, parameters);
4947
+ }
4948
+ async function validateCurrentTransition(definition, parameters, ctx) {
4949
+ const binding = definition.stateMachine;
4950
+ if (!binding) return null;
4951
+ const entityId = binding.getEntityId(parameters);
4952
+ if (!entityId) return `Action ${definition.actionId} did not identify an experiment`;
4953
+ const params = actionParams({ parameters });
4954
+ const tenantId = typeof params.tenantId === "string" ? params.tenantId : ctx.tenantId;
4955
+ const experiment = await ctx.db.store.getExperiment(tenantId, entityId);
4956
+ if (!experiment) return null;
4957
+ const target = typeof binding.targetState === "function" ? binding.targetState(parameters) : binding.targetState;
4958
+ const valid = experimentStateMachine.transitions.some(
4959
+ (transition2) => transition2.from === experiment.state && transition2.to === target && transition2.causedByAction === definition.actionId
4960
+ );
4961
+ return valid ? null : `Transition from "${experiment.state}" to "${target}" via action "${definition.actionId}" is not defined for Experiment.`;
4962
+ }
4963
+ async function findExperiment(ctx, params) {
4964
+ if (typeof params.experimentId !== "string") return null;
4965
+ const tenantId = typeof params.tenantId === "string" ? params.tenantId : ctx.tenantId;
4966
+ return ctx.db.store.getExperiment(tenantId, params.experimentId);
4967
+ }
4968
+ function actionParams(ctx) {
4969
+ return isRecord(ctx.parameters) ? ctx.parameters : {};
4970
+ }
4971
+ function outcome(policy, blocked, reason) {
4972
+ return {
4973
+ policyId: policy.policyId,
4974
+ policyVersion: policy.version,
4975
+ policyKind: "code",
4976
+ result: blocked ? "block" : "pass",
4977
+ reason
4978
+ };
4979
+ }
4980
+ async function appendGovernanceEvent(ctx, parameters, type, payload) {
4981
+ const params = isRecord(parameters) ? parameters : {};
4982
+ await ctx.db.store.appendEvent({
4983
+ id: crypto$1.randomUUID(),
4984
+ type,
4985
+ tenantId: typeof params.tenantId === "string" ? params.tenantId : ctx.tenantId,
4986
+ experimentId: typeof params.experimentId === "string" ? params.experimentId : "*",
4987
+ actorId: ctx.actorId,
4988
+ at: (/* @__PURE__ */ new Date()).toISOString(),
4989
+ payload: {
4990
+ actionInvocationId: ctx.actionInvocationId,
4991
+ correlationId: ctx.correlationId,
4992
+ actorType: ctx.actorType,
4993
+ ...payload
4994
+ }
4995
+ });
4996
+ }
4997
+ function isRecord(value) {
4998
+ return value !== null && typeof value === "object" && !Array.isArray(value);
4999
+ }
4443
5000
  var Invoker = class {
4444
5001
  constructor(services) {
4445
5002
  this.services = services;
@@ -4478,17 +5035,198 @@ var Invoker = class {
4478
5035
  correlationId: options.correlationId ?? (this.services.uuid ?? crypto$1.randomUUID)(),
4479
5036
  db: this.services
4480
5037
  };
4481
- if (!def.handler) {
4482
- return { success: false, error: `Action ${actionId} has no handler` };
4483
- }
4484
5038
  try {
4485
- return await def.handler(ctx, parsed.data);
5039
+ return await executeGovernedExperimentAction(def, parsed.data, ctx);
4486
5040
  } catch (e) {
4487
5041
  const err = e;
4488
5042
  return { success: false, error: err.message ?? String(e) };
4489
5043
  }
4490
5044
  }
4491
5045
  };
5046
+ function requireResourceStore(store) {
5047
+ if (!store.getResource || !store.listResources || !store.putResource) {
5048
+ throw new Error("Control-plane store does not support workspace resources");
5049
+ }
5050
+ return {
5051
+ get: store.getResource.bind(store),
5052
+ list: store.listResources.bind(store),
5053
+ put: store.putResource.bind(store),
5054
+ nextVersion: store.nextResourceVersion?.bind(store)
5055
+ };
5056
+ }
5057
+ var upsertWorkspaceResource = {
5058
+ actionId: "experiment.workspace_resource_upsert",
5059
+ namespace: "experiment",
5060
+ version: 1,
5061
+ schema: UpsertWorkspaceResourceInput,
5062
+ emitsEvents: ["workspace_resource.upserted"],
5063
+ idempotent: true,
5064
+ mutatesDomain: true,
5065
+ async handler(ctx, params) {
5066
+ const input = UpsertWorkspaceResourceInput.parse(params);
5067
+ const resource = WorkspaceResource.parse({ ...input.resource, tenantId: input.tenantId });
5068
+ const store = requireResourceStore(ctx.db.store);
5069
+ await store.put(resource);
5070
+ await ctx.db.store.appendEvent({
5071
+ id: crypto$1.randomUUID(),
5072
+ type: "workspace_resource.upserted",
5073
+ tenantId: input.tenantId,
5074
+ experimentId: `workspace:${resource.kind}:${resource.id}`,
5075
+ actorId: ctx.actorId,
5076
+ at: (/* @__PURE__ */ new Date()).toISOString(),
5077
+ payload: {
5078
+ actionInvocationId: ctx.actionInvocationId,
5079
+ correlationId: ctx.correlationId,
5080
+ actorType: ctx.actorType,
5081
+ resourceKind: resource.kind,
5082
+ resourceId: resource.id
5083
+ }
5084
+ });
5085
+ return { success: true, data: { resource } };
5086
+ }
5087
+ };
5088
+ var publishEnvironment = {
5089
+ actionId: "experiment.environment_publish",
5090
+ namespace: "experiment",
5091
+ version: 1,
5092
+ schema: PublishEnvironmentInput,
5093
+ emitsEvents: ["environment.published"],
5094
+ idempotent: false,
5095
+ mutatesDomain: true,
5096
+ async handler(ctx, params) {
5097
+ const input = PublishEnvironmentInput.parse(params);
5098
+ const store = requireResourceStore(ctx.db.store);
5099
+ if (!store.nextVersion)
5100
+ throw new Error("Control-plane store does not support resource versions");
5101
+ const environment = Environment.parse(
5102
+ await store.get(input.tenantId, "environment", input.environmentId)
5103
+ );
5104
+ const features = (await store.list(input.tenantId, "feature")).filter((resource) => resource.kind === "feature").filter((feature) => feature.projectId === environment.projectId && !feature.archived);
5105
+ const featureIds = new Set(features.map((feature) => feature.id));
5106
+ const rules = (await store.list(input.tenantId, "rule")).filter((resource) => resource.kind === "rule").filter(
5107
+ (rule) => rule.environmentId === environment.id && featureIds.has(rule.featureId) && rule.enabled
5108
+ ).sort((a, b) => a.priority - b.priority || a.id.localeCompare(b.id));
5109
+ const snapshot = { features, rules };
5110
+ const resourceHash = crypto$1.createHash("sha256").update(stableJson(snapshot)).digest("hex");
5111
+ const version = await store.nextVersion(input.tenantId, `environment:${environment.id}`);
5112
+ const publication = {
5113
+ id: crypto$1.randomUUID(),
5114
+ kind: "publication",
5115
+ tenantId: input.tenantId,
5116
+ environmentId: environment.id,
5117
+ version,
5118
+ status: "published",
5119
+ resourceHash,
5120
+ manifestVersion: await ctx.db.store.currentManifestVersion(input.tenantId),
5121
+ publishedBy: input.publishedBy,
5122
+ publishedAt: (/* @__PURE__ */ new Date()).toISOString(),
5123
+ snapshot
5124
+ };
5125
+ await store.put(publication);
5126
+ await ctx.db.store.appendEvent({
5127
+ id: crypto$1.randomUUID(),
5128
+ type: "environment.published",
5129
+ tenantId: input.tenantId,
5130
+ experimentId: `workspace:environment:${environment.id}`,
5131
+ actorId: ctx.actorId,
5132
+ at: publication.publishedAt,
5133
+ payload: {
5134
+ actionInvocationId: ctx.actionInvocationId,
5135
+ correlationId: ctx.correlationId,
5136
+ actorType: ctx.actorType,
5137
+ environmentId: environment.id,
5138
+ version,
5139
+ resourceHash,
5140
+ featureCount: features.length,
5141
+ ruleCount: rules.length
5142
+ }
5143
+ });
5144
+ return { success: true, data: { publication } };
5145
+ }
5146
+ };
5147
+ var promoteEnvironment = {
5148
+ actionId: "experiment.environment_promote",
5149
+ namespace: "experiment",
5150
+ version: 1,
5151
+ schema: PromoteEnvironmentInput,
5152
+ emitsEvents: ["environment.promoted"],
5153
+ idempotent: false,
5154
+ mutatesDomain: true,
5155
+ async handler(ctx, params) {
5156
+ const input = PromoteEnvironmentInput.parse(params);
5157
+ const store = requireResourceStore(ctx.db.store);
5158
+ const source = Environment.parse(
5159
+ await store.get(input.tenantId, "environment", input.sourceEnvironmentId)
5160
+ );
5161
+ const target = Environment.parse(
5162
+ await store.get(input.tenantId, "environment", input.targetEnvironmentId)
5163
+ );
5164
+ if (source.projectId !== target.projectId) {
5165
+ throw new Error("Source and target environments must belong to the same project");
5166
+ }
5167
+ if (target.rank <= source.rank) {
5168
+ throw new Error("Promotions must move to a higher-ranked environment");
5169
+ }
5170
+ const publications = (await store.list(input.tenantId, "publication")).filter(
5171
+ (resource) => resource.kind === "publication" && resource.environmentId === source.id
5172
+ ).sort((a, b) => b.version - a.version);
5173
+ const sourcePublication = publications[0];
5174
+ if (!sourcePublication) throw new Error("Source environment has no published version");
5175
+ const currentTargetRules = (await store.list(input.tenantId, "rule")).filter(
5176
+ (resource) => resource.kind === "rule" && resource.environmentId === target.id && resource.enabled
5177
+ );
5178
+ const at = (/* @__PURE__ */ new Date()).toISOString();
5179
+ for (const rule of currentTargetRules) {
5180
+ await store.put({ ...rule, enabled: false, updatedAt: at });
5181
+ }
5182
+ const promotedRules = sourcePublication.snapshot.rules.map((rule) => ({
5183
+ ...rule,
5184
+ id: crypto$1.randomUUID(),
5185
+ environmentId: target.id,
5186
+ createdAt: at,
5187
+ updatedAt: at
5188
+ }));
5189
+ for (const rule of promotedRules) await store.put(rule);
5190
+ await ctx.db.store.appendEvent({
5191
+ id: crypto$1.randomUUID(),
5192
+ type: "environment.promoted",
5193
+ tenantId: input.tenantId,
5194
+ experimentId: `workspace:environment:${target.id}`,
5195
+ actorId: ctx.actorId,
5196
+ at,
5197
+ payload: {
5198
+ actionInvocationId: ctx.actionInvocationId,
5199
+ correlationId: ctx.correlationId,
5200
+ actorType: ctx.actorType,
5201
+ sourceEnvironmentId: source.id,
5202
+ sourceVersion: sourcePublication.version,
5203
+ targetEnvironmentId: target.id,
5204
+ promotedRuleCount: promotedRules.length
5205
+ }
5206
+ });
5207
+ return {
5208
+ success: true,
5209
+ data: {
5210
+ sourceEnvironmentId: source.id,
5211
+ sourceVersion: sourcePublication.version,
5212
+ targetEnvironmentId: target.id,
5213
+ promotedRuleCount: promotedRules.length
5214
+ }
5215
+ };
5216
+ }
5217
+ };
5218
+ function stableJson(value) {
5219
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
5220
+ if (value && typeof value === "object") {
5221
+ return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, nested]) => `${JSON.stringify(key)}:${stableJson(nested)}`).join(",")}}`;
5222
+ }
5223
+ return JSON.stringify(value);
5224
+ }
5225
+ var workspaceActions = [
5226
+ upsertWorkspaceResource,
5227
+ publishEnvironment,
5228
+ promoteEnvironment
5229
+ ];
4492
5230
  var NAMESPACE = "experiment";
4493
5231
  var VERSION = 1;
4494
5232
  var now = () => (/* @__PURE__ */ new Date()).toISOString();
@@ -4535,6 +5273,10 @@ var createExperiment = {
4535
5273
  });
4536
5274
  }
4537
5275
  const ts = now();
5276
+ const compiledSampleRate = input.sampleRate ?? (input.holdback !== void 0 ? 1 - input.holdback : void 0) ?? input.audience?.sampleRate ?? 1;
5277
+ if (input.divertTo && !input.variants.some((v) => v.key === input.divertTo)) {
5278
+ throw new ValidationFailed(`divertTo references unknown variant: ${input.divertTo}`);
5279
+ }
4538
5280
  const experiment = {
4539
5281
  id: input.id,
4540
5282
  name: input.name,
@@ -4542,7 +5284,7 @@ var createExperiment = {
4542
5284
  state: "draft",
4543
5285
  salt: input.salt ?? input.id,
4544
5286
  audience: {
4545
- sampleRate: input.sampleRate ?? input.audience?.sampleRate ?? 1,
5287
+ sampleRate: compiledSampleRate,
4546
5288
  rule: input.audience?.rule
4547
5289
  },
4548
5290
  variants: input.variants,
@@ -4554,17 +5296,30 @@ var createExperiment = {
4554
5296
  isPrimary: m.isPrimary ?? false,
4555
5297
  isGuardrail: m.isGuardrail ?? false
4556
5298
  })),
5299
+ trigger: input.trigger,
5300
+ manualExposure: input.manualExposure,
5301
+ divertTo: input.divertTo,
5302
+ sharedJs: input.sharedJs,
5303
+ sharedCss: input.sharedCss,
5304
+ metadata: input.metadata,
4557
5305
  approval: null,
4558
5306
  killReason: null,
4559
5307
  ownerId: input.ownerId,
4560
5308
  tenantId,
5309
+ projectId: input.projectId,
5310
+ propertyId: input.propertyId,
5311
+ featureId: input.featureId,
5312
+ environmentIds: input.environmentIds,
5313
+ workload: input.workload,
4561
5314
  createdAt: ts,
4562
5315
  updatedAt: ts,
4563
5316
  startedAt: null,
4564
5317
  endedAt: null
4565
5318
  };
4566
5319
  await store.putExperiment(experiment);
4567
- await store.appendEvent(event("experiment.created", experiment, ctx, { name: experiment.name }));
5320
+ await store.appendEvent(
5321
+ event("experiment.created", experiment, ctx, { name: experiment.name })
5322
+ );
4568
5323
  return { success: true, data: { experimentId: experiment.id } };
4569
5324
  }
4570
5325
  };
@@ -4577,6 +5332,14 @@ function lifecycle(actionId, schema, evt, fn, options = {}) {
4577
5332
  emitsEvents: [evt],
4578
5333
  idempotent: false,
4579
5334
  mutatesDomain: true,
5335
+ ...options.platformPolicies ? { policies: options.platformPolicies } : {},
5336
+ ...options.targetState ? {
5337
+ stateMachine: {
5338
+ entityType: "Experiment",
5339
+ targetState: options.targetState,
5340
+ getEntityId: (params) => params.experimentId
5341
+ }
5342
+ } : {},
4580
5343
  async handler(ctx, params) {
4581
5344
  const p = params;
4582
5345
  const store = ctx.db.store;
@@ -4596,7 +5359,8 @@ var submitForReview = lifecycle(
4596
5359
  "experiment.submit_for_review",
4597
5360
  SubmitForReviewInput,
4598
5361
  "experiment.submitted_for_review",
4599
- (e) => transition(e, "submitForReview")
5362
+ (e) => transition(e, "submitForReview"),
5363
+ { targetState: "review" }
4600
5364
  );
4601
5365
  var approve = lifecycle(
4602
5366
  "experiment.approve",
@@ -4611,6 +5375,8 @@ var approve = lifecycle(
4611
5375
  }
4612
5376
  }),
4613
5377
  {
5378
+ targetState: "approved",
5379
+ platformPolicies: ["experiment.separation_of_duties.v1"],
4614
5380
  policy(e, p) {
4615
5381
  if (e.ownerId === p.approverId) {
4616
5382
  throw new PolicyDenied("approver cannot be the experiment owner", {
@@ -4629,6 +5395,8 @@ var start = lifecycle(
4629
5395
  startedAt: now()
4630
5396
  }),
4631
5397
  {
5398
+ targetState: "running",
5399
+ platformPolicies: ["experiment.approved_to_start.v1"],
4632
5400
  policy(e) {
4633
5401
  if (!e.approval) {
4634
5402
  throw new PolicyDenied("experiment must be approved before starting");
@@ -4640,13 +5408,15 @@ var pauseAction = lifecycle(
4640
5408
  "experiment.pause",
4641
5409
  PauseInput,
4642
5410
  "experiment.paused",
4643
- (e) => transition(e, "pause")
5411
+ (e) => transition(e, "pause"),
5412
+ { targetState: "paused" }
4644
5413
  );
4645
5414
  var resume = lifecycle(
4646
5415
  "experiment.resume",
4647
5416
  ResumeInput,
4648
5417
  "experiment.resumed",
4649
- (e) => transition(e, "resume")
5418
+ (e) => transition(e, "resume"),
5419
+ { targetState: "running" }
4650
5420
  );
4651
5421
  var kill = lifecycle(
4652
5422
  "experiment.kill",
@@ -4656,7 +5426,8 @@ var kill = lifecycle(
4656
5426
  ...transition(e, "kill"),
4657
5427
  killReason: p.reason ?? "unspecified",
4658
5428
  endedAt: now()
4659
- })
5429
+ }),
5430
+ { targetState: "killed" }
4660
5431
  );
4661
5432
  var declareWinner = lifecycle(
4662
5433
  "experiment.declare_winner",
@@ -4667,7 +5438,8 @@ var declareWinner = lifecycle(
4667
5438
  throw new ValidationFailed(`unknown winningVariant: ${p.winningVariant}`);
4668
5439
  }
4669
5440
  return { ...transition(e, "declareWinner"), endedAt: now() };
4670
- }
5441
+ },
5442
+ { targetState: "concluded" }
4671
5443
  );
4672
5444
  var update = {
4673
5445
  actionId: "experiment.update",
@@ -4677,6 +5449,7 @@ var update = {
4677
5449
  emitsEvents: ["experiment.updated", "experiment.metrics_updated", "experiment.variant_updated"],
4678
5450
  idempotent: false,
4679
5451
  mutatesDomain: true,
5452
+ policies: ["experiment.freeze_variant_set.v1"],
4680
5453
  async handler(ctx, params) {
4681
5454
  const p = params;
4682
5455
  const store = ctx.db.store;
@@ -4693,15 +5466,30 @@ var update = {
4693
5466
  );
4694
5467
  }
4695
5468
  }
5469
+ if (p.spec.divertTo && !p.spec.variants.some((v) => v.key === p.spec.divertTo)) {
5470
+ throw new ValidationFailed(`divertTo references unknown variant: ${p.spec.divertTo}`);
5471
+ }
5472
+ const compiledSampleRate = p.spec.sampleRate ?? (p.spec.holdback !== void 0 ? 1 - p.spec.holdback : void 0) ?? p.spec.audience?.sampleRate ?? e.audience.sampleRate;
4696
5473
  const updated = {
4697
5474
  ...e,
4698
5475
  name: p.spec.name,
4699
5476
  description: p.spec.description,
5477
+ projectId: p.spec.projectId ?? e.projectId,
5478
+ propertyId: p.spec.propertyId ?? e.propertyId,
5479
+ featureId: p.spec.featureId ?? e.featureId,
5480
+ environmentIds: p.spec.environmentIds ?? e.environmentIds,
5481
+ workload: p.spec.workload ?? e.workload,
4700
5482
  audience: {
4701
5483
  ...e.audience,
4702
- sampleRate: p.spec.sampleRate ?? p.spec.audience?.sampleRate ?? e.audience.sampleRate
5484
+ sampleRate: compiledSampleRate
4703
5485
  },
4704
5486
  variants: p.spec.variants,
5487
+ trigger: p.spec.trigger ?? e.trigger,
5488
+ manualExposure: p.spec.manualExposure ?? e.manualExposure,
5489
+ divertTo: p.spec.divertTo ?? e.divertTo,
5490
+ sharedJs: p.spec.sharedJs ?? e.sharedJs,
5491
+ sharedCss: p.spec.sharedCss ?? e.sharedCss,
5492
+ metadata: p.spec.metadata ?? e.metadata,
4705
5493
  metrics: (p.spec.metrics ?? e.metrics).map((m) => ({
4706
5494
  key: m.key,
4707
5495
  name: m.name,
@@ -4767,7 +5555,8 @@ var experimentActions = [
4767
5555
  kill,
4768
5556
  declareWinner,
4769
5557
  update,
4770
- guardrailBreach
5558
+ guardrailBreach,
5559
+ ...workspaceActions
4771
5560
  ];
4772
5561
  function createExperimentModule(args) {
4773
5562
  const services = { store: args.store };
@@ -4957,8 +5746,7 @@ async function loadExperimentDir(dir) {
4957
5746
  }
4958
5747
  async function loadExperimentFile(path) {
4959
5748
  const text = await promises.readFile(path, "utf8");
4960
- const parsed = yaml.parse(text);
4961
- return ExperimentSpec.parse(parsed);
5749
+ return experimentsYaml.parseExperimentYamlTextOrThrow(text);
4962
5750
  }
4963
5751
  async function cmdValidate(dir) {
4964
5752
  const abs = path.resolve(dir);
@@ -5027,7 +5815,7 @@ function compareSpecToCurrent(spec, current) {
5027
5815
  to: spec.description ?? null
5028
5816
  });
5029
5817
  }
5030
- const specSampleRate = spec.sampleRate ?? spec.audience?.sampleRate ?? 1;
5818
+ const specSampleRate = spec.sampleRate ?? (spec.holdback !== void 0 ? 1 - spec.holdback : void 0) ?? spec.audience?.sampleRate ?? 1;
5031
5819
  if (specSampleRate !== current.audience.sampleRate) {
5032
5820
  changes.push({
5033
5821
  kind: "changed",
@@ -5036,6 +5824,54 @@ function compareSpecToCurrent(spec, current) {
5036
5824
  to: specSampleRate
5037
5825
  });
5038
5826
  }
5827
+ if ((spec.divertTo ?? null) !== (current.divertTo ?? null)) {
5828
+ changes.push({
5829
+ kind: "changed",
5830
+ path: "divertTo",
5831
+ from: current.divertTo ?? null,
5832
+ to: spec.divertTo ?? null
5833
+ });
5834
+ }
5835
+ if ((spec.manualExposure ?? false) !== (current.manualExposure ?? false)) {
5836
+ changes.push({
5837
+ kind: "changed",
5838
+ path: "manualExposure",
5839
+ from: current.manualExposure ?? false,
5840
+ to: spec.manualExposure ?? false
5841
+ });
5842
+ }
5843
+ if (JSON.stringify(spec.trigger ?? null) !== JSON.stringify(current.trigger ?? null)) {
5844
+ changes.push({
5845
+ kind: "changed",
5846
+ path: "trigger",
5847
+ from: current.trigger ?? null,
5848
+ to: spec.trigger ?? null
5849
+ });
5850
+ }
5851
+ if ((spec.sharedJs ?? null) !== (current.sharedJs ?? null)) {
5852
+ changes.push({
5853
+ kind: "changed",
5854
+ path: "sharedJs",
5855
+ from: current.sharedJs ?? null,
5856
+ to: spec.sharedJs ?? null
5857
+ });
5858
+ }
5859
+ if ((spec.sharedCss ?? null) !== (current.sharedCss ?? null)) {
5860
+ changes.push({
5861
+ kind: "changed",
5862
+ path: "sharedCss",
5863
+ from: current.sharedCss ?? null,
5864
+ to: spec.sharedCss ?? null
5865
+ });
5866
+ }
5867
+ if (JSON.stringify(spec.metadata ?? null) !== JSON.stringify(current.metadata ?? null)) {
5868
+ changes.push({
5869
+ kind: "changed",
5870
+ path: "metadata",
5871
+ from: current.metadata ?? null,
5872
+ to: spec.metadata ?? null
5873
+ });
5874
+ }
5039
5875
  const specByKey = new Map(spec.variants.map((v) => [v.key, v]));
5040
5876
  const curByKey = new Map(current.variants.map((v) => [v.key, v]));
5041
5877
  for (const v of spec.variants) {
@@ -5066,7 +5902,28 @@ function compareVariant(spec, cur, prefix) {
5066
5902
  out.push({ kind: "changed", path: `${prefix}.js`, from: cur.js ?? null, to: spec.js ?? null });
5067
5903
  }
5068
5904
  if ((spec.css ?? null) !== (cur.css ?? null)) {
5069
- out.push({ kind: "changed", path: `${prefix}.css`, from: cur.css ?? null, to: spec.css ?? null });
5905
+ out.push({
5906
+ kind: "changed",
5907
+ path: `${prefix}.css`,
5908
+ from: cur.css ?? null,
5909
+ to: spec.css ?? null
5910
+ });
5911
+ }
5912
+ if (JSON.stringify(spec.domOps ?? null) !== JSON.stringify(cur.domOps ?? null)) {
5913
+ out.push({
5914
+ kind: "changed",
5915
+ path: `${prefix}.domOps`,
5916
+ from: cur.domOps ?? null,
5917
+ to: spec.domOps ?? null
5918
+ });
5919
+ }
5920
+ if ((spec.recipeSampleRate ?? null) !== (cur.recipeSampleRate ?? null)) {
5921
+ out.push({
5922
+ kind: "changed",
5923
+ path: `${prefix}.recipeSampleRate`,
5924
+ from: cur.recipeSampleRate ?? null,
5925
+ to: spec.recipeSampleRate ?? null
5926
+ });
5070
5927
  }
5071
5928
  if (JSON.stringify(spec.payload ?? null) !== JSON.stringify(cur.payload ?? null)) {
5072
5929
  out.push({
@@ -5105,7 +5962,7 @@ function plan(args) {
5105
5962
  if (d.breaking) {
5106
5963
  blocked.push({
5107
5964
  id: d.id,
5108
- reason: `Variant set changed after start; create a new experiment id instead.`
5965
+ reason: "Variant set changed after start; create a new experiment id instead."
5109
5966
  });
5110
5967
  continue;
5111
5968
  }
@@ -5117,7 +5974,7 @@ function plan(args) {
5117
5974
  if (!args.allowDeletes) {
5118
5975
  blocked.push({
5119
5976
  id: d.id,
5120
- reason: `Removed from YAML; pass --allow-deletes to kill in control plane.`
5977
+ reason: "Removed from YAML; pass --allow-deletes to kill in control plane."
5121
5978
  });
5122
5979
  continue;
5123
5980
  }
@@ -5159,14 +6016,12 @@ function formatPlan(p) {
5159
6016
  function renderDiff(d) {
5160
6017
  if (d.kind === "noop") return [];
5161
6018
  if (d.kind === "create") return [` + ${d.spec.id} ${d.spec.name} (create)`];
5162
- if (d.kind === "delete")
5163
- return [` - ${d.id} (in control plane but not in YAML; will kill)`];
6019
+ if (d.kind === "delete") return [` - ${d.id} (in control plane but not in YAML; will kill)`];
5164
6020
  const out = [` ~ ${d.id} ${d.spec.name} (update${d.breaking ? " \u2014 BLOCKED" : ""})`];
5165
6021
  for (const c of d.changes) {
5166
6022
  if (c.kind === "added") out.push(` + ${c.path}: ${jsonish(c.value)}`);
5167
6023
  else if (c.kind === "removed") out.push(` - ${c.path}: ${jsonish(c.value)}`);
5168
- else
5169
- out.push(` ~ ${c.path}: ${jsonish(c.from)} \u2192 ${jsonish(c.to)}`);
6024
+ else out.push(` ~ ${c.path}: ${jsonish(c.from)} \u2192 ${jsonish(c.to)}`);
5170
6025
  }
5171
6026
  return out;
5172
6027
  }
@@ -5204,9 +6059,7 @@ async function cmdApply(dir, options = {}) {
5204
6059
  process.stdout.write(formatPlan(p));
5205
6060
  process.stdout.write("\n");
5206
6061
  if (p.blocked.length > 0) {
5207
- process.stderr.write(`
5208
- Apply blocked. Resolve the issues above and re-run.
5209
- `);
6062
+ process.stderr.write("\nApply blocked. Resolve the issues above and re-run.\n");
5210
6063
  return 2;
5211
6064
  }
5212
6065
  if (options.dryRun || p.actions.length === 0) {
@@ -5234,11 +6087,11 @@ async function invokePlanned(ws, a, ownerId, approverId) {
5234
6087
  );
5235
6088
  }
5236
6089
  if (a.actionId === "experiment.submit_for_review" || a.actionId === "experiment.start") {
5237
- return ws.module.invoker.invoke(
5238
- a.actionId,
5239
- a.params,
5240
- { tenantId: a.params.tenantId, actorId: ownerId, actorType: "natural_person" }
5241
- );
6090
+ return ws.module.invoker.invoke(a.actionId, a.params, {
6091
+ tenantId: a.params.tenantId,
6092
+ actorId: ownerId,
6093
+ actorType: "natural_person"
6094
+ });
5242
6095
  }
5243
6096
  if (a.actionId === "experiment.approve") {
5244
6097
  return ws.module.invoker.invoke(
@@ -5248,17 +6101,17 @@ async function invokePlanned(ws, a, ownerId, approverId) {
5248
6101
  );
5249
6102
  }
5250
6103
  if (a.actionId === "experiment.update") {
5251
- return ws.module.invoker.invoke(
5252
- "experiment.update",
5253
- a.params,
5254
- { tenantId: a.params.tenantId, actorId: ownerId, actorType: "natural_person" }
5255
- );
6104
+ return ws.module.invoker.invoke("experiment.update", a.params, {
6105
+ tenantId: a.params.tenantId,
6106
+ actorId: ownerId,
6107
+ actorType: "natural_person"
6108
+ });
5256
6109
  }
5257
- return ws.module.invoker.invoke(
5258
- "experiment.kill",
5259
- a.params,
5260
- { tenantId: a.params.tenantId, actorId: ownerId, actorType: "natural_person" }
5261
- );
6110
+ return ws.module.invoker.invoke("experiment.kill", a.params, {
6111
+ tenantId: a.params.tenantId,
6112
+ actorId: ownerId,
6113
+ actorType: "natural_person"
6114
+ });
5262
6115
  }
5263
6116
  function assertOk(label, result) {
5264
6117
  if (!result.success) throw new Error(`${label}: ${result.error}`);
@@ -5283,8 +6136,8 @@ function twoSidedPFromZ(z) {
5283
6136
  }
5284
6137
  function probit(p) {
5285
6138
  if (p <= 0 || p >= 1) {
5286
- if (p === 0) return -Infinity;
5287
- if (p === 1) return Infinity;
6139
+ if (p === 0) return Number.NEGATIVE_INFINITY;
6140
+ if (p === 1) return Number.POSITIVE_INFINITY;
5288
6141
  throw new Error(`probit: p out of range: ${p}`);
5289
6142
  }
5290
6143
  const a = [
@@ -5310,12 +6163,7 @@ function probit(p) {
5310
6163
  4.374664141464968,
5311
6164
  2.938163982698783
5312
6165
  ];
5313
- const d = [
5314
- 0.007784695709041462,
5315
- 0.3224671290700398,
5316
- 2.445134137142996,
5317
- 3.754408661907416
5318
- ];
6166
+ const d = [0.007784695709041462, 0.3224671290700398, 2.445134137142996, 3.754408661907416];
5319
6167
  const pLow = 0.02425;
5320
6168
  const pHigh = 1 - pLow;
5321
6169
  let q;
@@ -5366,14 +6214,10 @@ function twoProportionZ(control, treatment, level = 0.95) {
5366
6214
  const p1 = control.successes / control.trials;
5367
6215
  const p2 = treatment.successes / treatment.trials;
5368
6216
  const pPooled = (control.successes + treatment.successes) / (control.trials + treatment.trials);
5369
- const seZ = Math.sqrt(
5370
- pPooled * (1 - pPooled) * (1 / control.trials + 1 / treatment.trials)
5371
- );
6217
+ const seZ = Math.sqrt(pPooled * (1 - pPooled) * (1 / control.trials + 1 / treatment.trials));
5372
6218
  const z = seZ === 0 ? 0 : (p2 - p1) / seZ;
5373
6219
  const pValue = twoSidedPFromZ(z);
5374
- const seCi = Math.sqrt(
5375
- p1 * (1 - p1) / control.trials + p2 * (1 - p2) / treatment.trials
5376
- );
6220
+ const seCi = Math.sqrt(p1 * (1 - p1) / control.trials + p2 * (1 - p2) / treatment.trials);
5377
6221
  const zs = zStar(level);
5378
6222
  const lift = p2 - p1;
5379
6223
  return {
@@ -5471,11 +6315,11 @@ function lnGamma(z) {
5471
6315
  if (z < 0.5) {
5472
6316
  return Math.log(Math.PI / Math.sin(Math.PI * z)) - lnGamma(1 - z);
5473
6317
  }
5474
- z -= 1;
6318
+ const zz = z - 1;
5475
6319
  let x = c[0];
5476
- for (let i = 1; i < g + 2; i++) x += c[i] / (z + i);
5477
- const t = z + g + 0.5;
5478
- return 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(x);
6320
+ for (let i = 1; i < g + 2; i++) x += c[i] / (zz + i);
6321
+ const t = zz + g + 0.5;
6322
+ return 0.5 * Math.log(2 * Math.PI) + (zz + 0.5) * Math.log(t) - t + Math.log(x);
5479
6323
  }
5480
6324
  function buildReport(args) {
5481
6325
  const level = args.level ?? 0.95;
@@ -5503,9 +6347,7 @@ function buildReport(args) {
5503
6347
  });
5504
6348
  const totalExposures = args.rows.reduce((s, r) => s + r.exposureCount, 0);
5505
6349
  const totalConversions = args.rows.reduce((s, r) => s + r.conversionCount, 0);
5506
- const expected = args.rows.map(
5507
- (r) => args.expectedSplit?.[r.variantKey] ?? 1 / args.rows.length
5508
- );
6350
+ const expected = args.rows.map((r) => args.expectedSplit?.[r.variantKey] ?? 1 / args.rows.length);
5509
6351
  const sumExp = expected.reduce((a, b) => a + b, 0);
5510
6352
  const normalizedExpected = expected.map((e) => e / sumExp);
5511
6353
  const srm = srmChiSquare({
@@ -5588,7 +6430,8 @@ Experiment: ${exp.name} (${exp.id})
5588
6430
  printTable(lines);
5589
6431
  process.stdout.write(
5590
6432
  `
5591
- SRM \u03C7\xB2=${report.srm.chiSquare.toFixed(3)} df=${report.srm.degreesOfFreedom} p=${formatP(report.srm.pValue)}` + (report.srmAlert ? " \u26A0\uFE0F SRM ALERT \u2014 investigate randomization" : "") + "\n"
6433
+ SRM \u03C7\xB2=${report.srm.chiSquare.toFixed(3)} df=${report.srm.degreesOfFreedom} p=${formatP(report.srm.pValue)}${report.srmAlert ? " \u26A0\uFE0F SRM ALERT \u2014 investigate randomization" : ""}
6434
+ `
5592
6435
  );
5593
6436
  return 0;
5594
6437
  }
@@ -5682,13 +6525,17 @@ async function cmdDev(options = {}) {
5682
6525
  res.statusCode = 400;
5683
6526
  res.setHeader("content-type", "application/json");
5684
6527
  res.end(JSON.stringify({ error: "invalid exposure", issues: parsed.error.issues }));
5685
- log(`POST /v1/exposure 400 invalid: ${parsed.error.issues.map((i) => i.path.join(".")).join(",")}`);
6528
+ log(
6529
+ `POST /v1/exposure 400 invalid: ${parsed.error.issues.map((i) => i.path.join(".")).join(",")}`
6530
+ );
5686
6531
  return;
5687
6532
  }
5688
6533
  await ws.warehouse.recordExposures([parsed.data]);
5689
6534
  res.statusCode = 204;
5690
6535
  res.end();
5691
- log(`POST /v1/exposure ${parsed.data.experimentId} ${parsed.data.variantKey} ${parsed.data.subjectId}`);
6536
+ log(
6537
+ `POST /v1/exposure ${parsed.data.experimentId} ${parsed.data.variantKey} ${parsed.data.subjectId}`
6538
+ );
5692
6539
  return;
5693
6540
  }
5694
6541
  if (req.method === "POST" && url.pathname === "/v1/conversion") {
@@ -5702,7 +6549,9 @@ async function cmdDev(options = {}) {
5702
6549
  res.statusCode = 400;
5703
6550
  res.setHeader("content-type", "application/json");
5704
6551
  res.end(JSON.stringify({ error: "invalid conversion", issues: parsed.error.issues }));
5705
- log(`POST /v1/conversion 400 invalid: ${parsed.error.issues.map((i) => i.path.join(".")).join(",")}`);
6552
+ log(
6553
+ `POST /v1/conversion 400 invalid: ${parsed.error.issues.map((i) => i.path.join(".")).join(",")}`
6554
+ );
5706
6555
  return;
5707
6556
  }
5708
6557
  await ws.warehouse.recordConversions([parsed.data]);
@@ -5725,13 +6574,37 @@ async function cmdDev(options = {}) {
5725
6574
  log(`ERR ${err.message}`);
5726
6575
  }
5727
6576
  });
5728
- await new Promise(
5729
- (resolveStart) => server.listen(port, "127.0.0.1", () => resolveStart())
5730
- );
6577
+ try {
6578
+ await new Promise((resolveStart, rejectStart) => {
6579
+ server.once("error", rejectStart);
6580
+ server.listen(port, "127.0.0.1", () => {
6581
+ server.off("error", rejectStart);
6582
+ resolveStart();
6583
+ });
6584
+ });
6585
+ } catch (e) {
6586
+ const err = e;
6587
+ if (err.code === "EADDRINUSE") {
6588
+ process.stderr.write(
6589
+ `fx dev: port ${port} is already in use.
6590
+
6591
+ Another fx dev server may already be running. Either stop that process or choose another port:
6592
+
6593
+ fx dev --port ${port + 1}
6594
+
6595
+ To find the process on Linux/macOS:
6596
+
6597
+ lsof -nP -iTCP:${port} -sTCP:LISTEN
6598
+ `
6599
+ );
6600
+ return 1;
6601
+ }
6602
+ throw e;
6603
+ }
5731
6604
  log(`fx dev \u2014 listening on http://127.0.0.1:${port}`);
5732
- log(` GET /manifest`);
5733
- log(` POST /v1/exposure`);
5734
- log(` POST /v1/conversion`);
6605
+ log(" GET /manifest");
6606
+ log(" POST /v1/exposure");
6607
+ log(" POST /v1/conversion");
5735
6608
  log(` workspace=${ws.root}`);
5736
6609
  await new Promise((resolveStop) => {
5737
6610
  const stop = () => {
@@ -5822,8 +6695,8 @@ function hexEncode(bytes) {
5822
6695
  }
5823
6696
  async function getSubtle() {
5824
6697
  if (typeof crypto !== "undefined" && crypto.subtle) return crypto.subtle;
5825
- const { webcrypto } = await import('crypto');
5826
- return webcrypto.subtle;
6698
+ const { webcrypto: webcrypto2 } = await import('crypto');
6699
+ return webcrypto2.subtle;
5827
6700
  }
5828
6701
  async function signManifest(manifest, key) {
5829
6702
  const subtle = await getSubtle2();
@@ -5847,13 +6720,13 @@ async function signManifest(manifest, key) {
5847
6720
  }
5848
6721
  async function getSubtle2() {
5849
6722
  if (typeof crypto !== "undefined" && crypto.subtle) return crypto.subtle;
5850
- const { webcrypto } = await import('crypto');
5851
- return webcrypto.subtle;
6723
+ const { webcrypto: webcrypto2 } = await import('crypto');
6724
+ return webcrypto2.subtle;
5852
6725
  }
5853
6726
  function hexDecode(hex) {
5854
6727
  if (hex.length % 2 !== 0) throw new Error("hexDecode: odd length");
5855
6728
  const out = new Uint8Array(hex.length / 2);
5856
- for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
6729
+ for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
5857
6730
  return out;
5858
6731
  }
5859
6732
  function ed25519PrivateKeyToPkcs8(seed) {
@@ -5898,8 +6771,8 @@ async function generateKeypair(keyId) {
5898
6771
  }
5899
6772
  async function getSubtle4() {
5900
6773
  if (typeof crypto !== "undefined" && crypto.subtle) return crypto.subtle;
5901
- const { webcrypto } = await import('crypto');
5902
- return webcrypto.subtle;
6774
+ const { webcrypto: webcrypto2 } = await import('crypto');
6775
+ return webcrypto2.subtle;
5903
6776
  }
5904
6777
 
5905
6778
  // src/commands/publish.ts
@@ -5949,8 +6822,46 @@ async function cmdPublish(options = {}) {
5949
6822
  process.stdout.write(`Published to ${options.remoteUrl}
5950
6823
  `);
5951
6824
  }
6825
+ if (options.staticDir) {
6826
+ const out = path.resolve(options.staticDir);
6827
+ await promises.mkdir(out, { recursive: true });
6828
+ await promises.writeFile(path.join(out, "manifest.json"), JSON.stringify(signed), "utf8");
6829
+ const tagLoader = await locateTagLoaderBundle();
6830
+ if (tagLoader) {
6831
+ await promises.copyFile(tagLoader.js, path.join(out, "experiments.tag.global.js"));
6832
+ if (tagLoader.map) {
6833
+ await promises.copyFile(tagLoader.map, path.join(out, "experiments.tag.global.js.map"));
6834
+ }
6835
+ process.stdout.write(
6836
+ `Static export written to ${out} (manifest.json + experiments.tag.global.js)
6837
+ `
6838
+ );
6839
+ } else {
6840
+ process.stderr.write(
6841
+ `Static export wrote manifest.json to ${out}, but could not locate experiments.tag.global.js. Install or build @fabricorg/experiments-web first, then re-run.
6842
+ `
6843
+ );
6844
+ }
6845
+ }
5952
6846
  return 0;
5953
6847
  }
6848
+ async function locateTagLoaderBundle() {
6849
+ const req = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
6850
+ try {
6851
+ const js = req.resolve("@fabricorg/experiments-web/tag-loader");
6852
+ await promises.stat(js);
6853
+ let map = null;
6854
+ try {
6855
+ const m = req.resolve("@fabricorg/experiments-web/tag-loader.map");
6856
+ await promises.stat(m);
6857
+ map = m;
6858
+ } catch {
6859
+ }
6860
+ return { js, map };
6861
+ } catch {
6862
+ return null;
6863
+ }
6864
+ }
5954
6865
  async function loadOrCreateKey(fxDir, keyId) {
5955
6866
  const path$1 = path.join(fxDir, "keys", `${keyId}.json`);
5956
6867
  try {
@@ -5960,25 +6871,1265 @@ async function loadOrCreateKey(fxDir, keyId) {
5960
6871
  const kp = await generateKeypair(keyId);
5961
6872
  await promises.mkdir(path.dirname(path$1), { recursive: true });
5962
6873
  await promises.writeFile(path$1, JSON.stringify(kp, null, 2), "utf8");
5963
- await promises.writeFile(
5964
- path.join(fxDir, "keys", `${keyId}.pub`),
5965
- `${kp.publicKeyHex}
6874
+ await promises.writeFile(path.join(fxDir, "keys", `${keyId}.pub`), `${kp.publicKeyHex}
6875
+ `, "utf8");
6876
+ return kp;
6877
+ }
6878
+ }
6879
+ async function cmdImportMojito(inputDir, options = {}) {
6880
+ const root = path.resolve(inputDir);
6881
+ const outDir = path.resolve(options.outputDir ?? path.join(root, "converted"));
6882
+ await promises.mkdir(outDir, { recursive: true });
6883
+ const waves = await findWaves(root);
6884
+ if (waves.length === 0) {
6885
+ process.stderr.write(`No Mojito waves found under ${root}.
6886
+ `);
6887
+ return 1;
6888
+ }
6889
+ const results = [];
6890
+ for (const waveDir of waves) {
6891
+ try {
6892
+ const r = await convertWave(waveDir, outDir);
6893
+ results.push(r);
6894
+ } catch (e) {
6895
+ results.push({
6896
+ source: waveDir,
6897
+ target: "",
6898
+ warnings: [`failed to convert: ${e.message}`]
6899
+ });
6900
+ }
6901
+ }
6902
+ process.stdout.write(
6903
+ `Converted ${results.length} wave${results.length === 1 ? "" : "s"} \u2192 ${outDir}
6904
+
6905
+ `
6906
+ );
6907
+ for (const r of results) {
6908
+ process.stdout.write(
6909
+ ` ${path.basename(r.source)} \u2192 ${r.target ? path.basename(r.target) : "(failed)"}
6910
+ `
6911
+ );
6912
+ for (const w of r.warnings) process.stdout.write(` ! ${w}
6913
+ `);
6914
+ }
6915
+ const failed = results.filter((r) => !r.target).length;
6916
+ return failed === 0 ? 0 : 2;
6917
+ }
6918
+ async function findWaves(root) {
6919
+ const out = [];
6920
+ const entries = await promises.readdir(root, { withFileTypes: true });
6921
+ for (const e of entries) {
6922
+ if (!e.isDirectory()) continue;
6923
+ const dir = path.join(root, e.name);
6924
+ try {
6925
+ const st = await promises.stat(path.join(dir, "config.yml"));
6926
+ if (st.isFile()) out.push(dir);
6927
+ } catch {
6928
+ }
6929
+ }
6930
+ return out;
6931
+ }
6932
+ async function convertWave(waveDir, outDir) {
6933
+ const warnings = [];
6934
+ const cfgText = await promises.readFile(path.join(waveDir, "config.yml"), "utf8");
6935
+ const cfg = yaml.parse(cfgText);
6936
+ if (!cfg.id || !cfg.name || !cfg.recipes) {
6937
+ throw new Error("config.yml missing id, name, or recipes");
6938
+ }
6939
+ const variants = [];
6940
+ const recipeRates = Object.values(cfg.recipes).map((r) => r.sampleRate).filter((v) => typeof v === "number");
6941
+ const allRecipesWeighted = recipeRates.length > 0 && recipeRates.length === Object.keys(cfg.recipes).length;
6942
+ for (const [key, recipe] of Object.entries(cfg.recipes)) {
6943
+ const variant = {
6944
+ key: normalizeKey(key),
6945
+ name: recipe.name ?? key
6946
+ };
6947
+ if (typeof recipe.sampleRate === "number") {
6948
+ if (allRecipesWeighted) {
6949
+ variant.weight = Math.round(recipe.sampleRate * 1e4);
6950
+ } else {
6951
+ variant.recipeSampleRate = recipe.sampleRate;
6952
+ }
6953
+ }
6954
+ if (recipe.js) {
6955
+ try {
6956
+ variant.js = await promises.readFile(path.join(waveDir, recipe.js), "utf8");
6957
+ } catch {
6958
+ warnings.push(`recipe ${key}: js file not found: ${recipe.js}`);
6959
+ }
6960
+ }
6961
+ if (recipe.css) {
6962
+ try {
6963
+ variant.css = await promises.readFile(path.join(waveDir, recipe.css), "utf8");
6964
+ } catch {
6965
+ warnings.push(`recipe ${key}: css file not found: ${recipe.css}`);
6966
+ }
6967
+ }
6968
+ variants.push(variant);
6969
+ }
6970
+ let triggerNote = null;
6971
+ if (cfg.trigger) {
6972
+ triggerNote = await promises.readFile(path.join(waveDir, cfg.trigger), "utf8").catch(() => "");
6973
+ if (triggerNote) {
6974
+ warnings.push(
6975
+ "trigger.js was not auto-converted \u2014 review and translate to a Trigger DSL or host-supplied trigger override."
6976
+ );
6977
+ }
6978
+ }
6979
+ let sharedJs;
6980
+ let sharedCss;
6981
+ if (cfg.js) {
6982
+ sharedJs = await promises.readFile(path.join(waveDir, cfg.js), "utf8").catch(() => {
6983
+ warnings.push(`shared js file not found: ${cfg.js}`);
6984
+ return void 0;
6985
+ });
6986
+ }
6987
+ if (cfg.css) {
6988
+ sharedCss = await promises.readFile(path.join(waveDir, cfg.css), "utf8").catch(() => {
6989
+ warnings.push(`shared css file not found: ${cfg.css}`);
6990
+ return void 0;
6991
+ });
6992
+ }
6993
+ const spec = {
6994
+ id: cfg.id.toLowerCase(),
6995
+ name: cfg.name,
6996
+ sampleRate: cfg.sampleRate ?? 1,
6997
+ variants
6998
+ };
6999
+ if (cfg.divertTo) spec.divertTo = normalizeKey(cfg.divertTo);
7000
+ if (cfg.manualExposure) spec.manualExposure = true;
7001
+ if (sharedJs) spec.sharedJs = sharedJs;
7002
+ if (sharedCss) spec.sharedCss = sharedCss;
7003
+ if (triggerNote) spec.trigger = { kind: "auto" };
7004
+ const header = [
7005
+ "# Imported from Mojito wave",
7006
+ `# Source: ${waveDir}`,
7007
+ cfg.state ? `# Original state: ${cfg.state}` : null,
7008
+ triggerNote ? "#" : null,
7009
+ triggerNote ? "# Original trigger.js (NOT auto-applied):" : null,
7010
+ triggerNote ? triggerNote.split("\n").map((l) => `# ${l}`).join("\n") : null
7011
+ ].filter((l) => l !== null).join("\n");
7012
+ const yamlBody = yaml.stringify(spec);
7013
+ const target = path.join(outDir, `${spec.id}.yaml`);
7014
+ await promises.writeFile(target, `${header}
7015
+ ${yamlBody}`, "utf8");
7016
+ return { source: waveDir, target, warnings };
7017
+ }
7018
+ function normalizeKey(k) {
7019
+ return k.toLowerCase().replace(/[^a-z0-9_-]/g, "-");
7020
+ }
7021
+
7022
+ // ../api-protocol/dist/index.js
7023
+ var Empty = external_exports.object({});
7024
+ var TenantSelf = external_exports.object({
7025
+ organization: external_exports.object({
7026
+ id: external_exports.string(),
7027
+ name: external_exports.string(),
7028
+ slug: external_exports.string(),
7029
+ createdAt: external_exports.string().datetime()
7030
+ }),
7031
+ member: external_exports.object({
7032
+ role: external_exports.enum(["owner", "admin", "experimenter", "viewer"])
7033
+ }),
7034
+ user: external_exports.object({
7035
+ id: external_exports.string(),
7036
+ email: external_exports.string().email(),
7037
+ name: external_exports.string().nullable()
7038
+ })
7039
+ });
7040
+ var ProjectListResponse = external_exports.object({ projects: external_exports.array(Project) });
7041
+ var PropertyListResponse = external_exports.object({ properties: external_exports.array(Property) });
7042
+ var EnvironmentListResponse = external_exports.object({ environments: external_exports.array(Environment) });
7043
+ var FeatureListResponse = external_exports.object({ features: external_exports.array(Feature) });
7044
+ var FeatureRuleListResponse = external_exports.object({ rules: external_exports.array(FeatureRule) });
7045
+ var PublicationListResponse = external_exports.object({ publications: external_exports.array(EnvironmentPublication) });
7046
+ var PromoteEnvironmentInput2 = external_exports.object({ sourceEnvironmentId: external_exports.string().uuid() });
7047
+ var PromoteEnvironmentResponse = external_exports.object({
7048
+ sourceEnvironmentId: external_exports.string().uuid(),
7049
+ sourceVersion: external_exports.number().int().positive(),
7050
+ targetEnvironmentId: external_exports.string().uuid(),
7051
+ promotedRuleCount: external_exports.number().int().nonnegative()
7052
+ });
7053
+ var ExperimentSummary = external_exports.object({
7054
+ id: Experiment.shape.id,
7055
+ name: Experiment.shape.name,
7056
+ state: ExperimentState,
7057
+ updatedAt: external_exports.string().datetime()
7058
+ });
7059
+ var ExperimentListResponse = external_exports.object({
7060
+ experiments: external_exports.array(ExperimentSummary)
7061
+ });
7062
+ var CreateExperimentInput2 = ExperimentSpecBase;
7063
+ var CreateExperimentResponse = external_exports.object({
7064
+ experimentId: ExperimentId,
7065
+ idempotent: external_exports.boolean().optional()
7066
+ });
7067
+ var AggregateRow = external_exports.object({
7068
+ variantKey: external_exports.string(),
7069
+ exposureCount: external_exports.number().int().nonnegative(),
7070
+ conversionCount: external_exports.number().int().nonnegative(),
7071
+ conversionSum: external_exports.number(),
7072
+ failureCount: external_exports.number().int().nonnegative().default(0)
7073
+ });
7074
+ var AggregateInput = external_exports.object({
7075
+ metric: external_exports.string().min(1).max(120),
7076
+ fromIso: external_exports.string().datetime().optional(),
7077
+ untilIso: external_exports.string().datetime().optional()
7078
+ });
7079
+ var AggregateResponse = external_exports.object({
7080
+ experimentId: ExperimentId,
7081
+ metric: external_exports.string(),
7082
+ rows: external_exports.array(AggregateRow),
7083
+ /** ISO datetime — when this aggregate was computed. SDKs may cache by this. */
7084
+ computedAt: external_exports.string().datetime()
7085
+ });
7086
+ var InvokeActionInput = external_exports.object({
7087
+ actionId: ActionId,
7088
+ params: external_exports.record(external_exports.unknown()),
7089
+ /** Optional client-supplied idempotency key. */
7090
+ idempotencyKey: external_exports.string().min(8).max(128).optional()
7091
+ });
7092
+ var InvokeActionResponse = external_exports.object({
7093
+ success: external_exports.boolean(),
7094
+ data: external_exports.record(external_exports.unknown()).optional(),
7095
+ error: external_exports.string().optional()
7096
+ });
7097
+ var EdgePushResult = external_exports.object({
7098
+ pushed: external_exports.boolean(),
7099
+ reason: external_exports.string().optional(),
7100
+ status: external_exports.number().int().optional()
7101
+ });
7102
+ var PublishManifestResponse = external_exports.object({
7103
+ manifestVersion: external_exports.number().int().nonnegative(),
7104
+ contentHash: external_exports.string().regex(/^[0-9a-f]{64}$/),
7105
+ experimentCount: external_exports.number().int().nonnegative(),
7106
+ /** Edge push status. `pushed: false` with `reason: 'unconfigured'` is normal in local dev. */
7107
+ edgePush: EdgePushResult
7108
+ });
7109
+ var ManifestKey = external_exports.object({
7110
+ keyId: external_exports.string(),
7111
+ publicKeyHex: external_exports.string().regex(/^[0-9a-f]+$/),
7112
+ status: external_exports.enum(["active", "retiring", "retired"]),
7113
+ createdAt: external_exports.string().datetime(),
7114
+ retiredAt: external_exports.string().datetime().nullable()
7115
+ });
7116
+ var ManifestKeysResponse = external_exports.object({ keys: external_exports.array(ManifestKey) });
7117
+ var PreviewSignInput = external_exports.object({
7118
+ experimentId: ExperimentId,
7119
+ variantKey: external_exports.string().min(1).max(32),
7120
+ /** Token TTL in seconds. Clamped server-side to [60, 3600]; default 900. */
7121
+ ttlSeconds: external_exports.number().int().min(60).max(3600).optional()
7122
+ });
7123
+ var PreviewSignResponse = external_exports.object({
7124
+ token: external_exports.string(),
7125
+ /** ISO datetime when the token expires. */
7126
+ expiresAt: external_exports.string().datetime(),
7127
+ /** ID of the public JWKS key used to sign — exposed for debugging only. */
7128
+ keyId: external_exports.string(),
7129
+ /** Unique JWT id for audit/debugging and future replay controls. */
7130
+ jti: external_exports.string()
7131
+ });
7132
+ var AuditEvent = external_exports.object({
7133
+ id: external_exports.string(),
7134
+ type: external_exports.string(),
7135
+ experimentId: external_exports.string(),
7136
+ actorId: external_exports.string(),
7137
+ at: external_exports.string().datetime(),
7138
+ payload: external_exports.record(external_exports.unknown())
7139
+ });
7140
+ var AuditListResponse = external_exports.object({ events: external_exports.array(AuditEvent) });
7141
+ var AuditExport = external_exports.object({
7142
+ id: external_exports.string(),
7143
+ destinationKind: external_exports.enum(["s3", "r2", "splunk-hec"]),
7144
+ status: external_exports.enum(["active", "paused", "failed"]),
7145
+ lastCursorAt: external_exports.string().datetime().nullable()
7146
+ });
7147
+ var AuditExportListResponse = external_exports.object({ exports: external_exports.array(AuditExport) });
7148
+ var CreateAuditExportInput = external_exports.object({
7149
+ destinationKind: external_exports.enum(["s3", "r2", "splunk-hec"]),
7150
+ /** Free-form config; encrypted at rest. Schema enforced by destination kind. */
7151
+ config: external_exports.record(external_exports.unknown())
7152
+ });
7153
+ var ApiKeySummary = external_exports.object({
7154
+ id: external_exports.string(),
7155
+ name: external_exports.string(),
7156
+ prefix: external_exports.string(),
7157
+ role: external_exports.enum(["owner", "admin", "experimenter", "viewer"]),
7158
+ scopes: external_exports.array(external_exports.enum(["read", "write", "admin"])),
7159
+ createdAt: external_exports.string().datetime(),
7160
+ lastUsedAt: external_exports.string().datetime().nullable(),
7161
+ expiresAt: external_exports.string().datetime().nullable()
7162
+ });
7163
+ var ApiKeyListResponse = external_exports.object({ keys: external_exports.array(ApiKeySummary) });
7164
+ var CreateApiKeyInput = external_exports.object({
7165
+ name: external_exports.string().min(1).max(120),
7166
+ /** ISO datetime of expiry; null for non-expiring (not recommended in prod). */
7167
+ expiresAt: external_exports.string().datetime().nullable(),
7168
+ /** Role assigned to the key. Defaults to the creator's role. */
7169
+ role: external_exports.enum(["owner", "admin", "experimenter", "viewer"]).optional(),
7170
+ /** Permission scopes assigned to the key. Defaults are derived from role. */
7171
+ scopes: external_exports.array(external_exports.enum(["read", "write", "admin"])).optional()
7172
+ });
7173
+ var CreateApiKeyResponse = ApiKeySummary.extend({
7174
+ /** Plaintext key, returned exactly once at creation time. */
7175
+ key: external_exports.string()
7176
+ });
7177
+ var SamlConfig = external_exports.object({
7178
+ enabled: external_exports.boolean(),
7179
+ connectionId: external_exports.string().min(1).max(200).nullable(),
7180
+ issuer: external_exports.string().min(1).max(500).nullable(),
7181
+ ssoUrl: external_exports.string().url().nullable(),
7182
+ certificate: external_exports.string().min(1).max(1e4).nullable()
7183
+ }).refine(
7184
+ (value) => !value.enabled || Boolean(value.connectionId && value.issuer && value.ssoUrl && value.certificate),
7185
+ {
7186
+ message: "connectionId, issuer, ssoUrl, certificate required when SAML is enabled"
7187
+ }
7188
+ );
7189
+ var endpoints = {
7190
+ "tenants.me": {
7191
+ method: "GET",
7192
+ path: "/v1/tenants/me",
7193
+ params: Empty,
7194
+ response: TenantSelf,
7195
+ mutates: false,
7196
+ requiresRole: null
7197
+ },
7198
+ "experiments.list": {
7199
+ method: "GET",
7200
+ path: "/v1/orgs/:orgId/experiments",
7201
+ params: Empty,
7202
+ response: ExperimentListResponse,
7203
+ mutates: false,
7204
+ requiresRole: "viewer"
7205
+ },
7206
+ "experiments.create": {
7207
+ method: "POST",
7208
+ path: "/v1/orgs/:orgId/experiments",
7209
+ params: CreateExperimentInput2,
7210
+ response: CreateExperimentResponse,
7211
+ mutates: true,
7212
+ requiresRole: "experimenter"
7213
+ },
7214
+ "experiments.get": {
7215
+ method: "GET",
7216
+ path: "/v1/orgs/:orgId/experiments/:experimentId",
7217
+ params: Empty,
7218
+ response: Experiment,
7219
+ mutates: false,
7220
+ requiresRole: "viewer"
7221
+ },
7222
+ "experiments.invokeAction": {
7223
+ method: "POST",
7224
+ path: "/v1/orgs/:orgId/experiments/actions",
7225
+ params: InvokeActionInput,
7226
+ response: InvokeActionResponse,
7227
+ mutates: true,
7228
+ requiresRole: "experimenter"
7229
+ },
7230
+ "experiments.aggregate": {
7231
+ method: "GET",
7232
+ path: "/v1/orgs/:orgId/experiments/:experimentId/aggregate",
7233
+ params: AggregateInput,
7234
+ response: AggregateResponse,
7235
+ mutates: false,
7236
+ requiresRole: "viewer"
7237
+ },
7238
+ "projects.list": {
7239
+ method: "GET",
7240
+ path: "/v1/orgs/:orgId/projects",
7241
+ params: Empty,
7242
+ response: ProjectListResponse,
7243
+ mutates: false,
7244
+ requiresRole: "viewer"
7245
+ },
7246
+ "projects.create": {
7247
+ method: "POST",
7248
+ path: "/v1/orgs/:orgId/projects",
7249
+ params: CreateProjectInput,
7250
+ response: Project,
7251
+ mutates: true,
7252
+ requiresRole: "experimenter"
7253
+ },
7254
+ "properties.list": {
7255
+ method: "GET",
7256
+ path: "/v1/orgs/:orgId/projects/:projectId/properties",
7257
+ params: Empty,
7258
+ response: PropertyListResponse,
7259
+ mutates: false,
7260
+ requiresRole: "viewer"
7261
+ },
7262
+ "properties.create": {
7263
+ method: "POST",
7264
+ path: "/v1/orgs/:orgId/projects/:projectId/properties",
7265
+ params: CreatePropertyInput,
7266
+ response: Property,
7267
+ mutates: true,
7268
+ requiresRole: "experimenter"
7269
+ },
7270
+ "environments.list": {
7271
+ method: "GET",
7272
+ path: "/v1/orgs/:orgId/projects/:projectId/environments",
7273
+ params: Empty,
7274
+ response: EnvironmentListResponse,
7275
+ mutates: false,
7276
+ requiresRole: "viewer"
7277
+ },
7278
+ "environments.create": {
7279
+ method: "POST",
7280
+ path: "/v1/orgs/:orgId/projects/:projectId/environments",
7281
+ params: CreateEnvironmentInput,
7282
+ response: Environment,
7283
+ mutates: true,
7284
+ requiresRole: "experimenter"
7285
+ },
7286
+ "features.list": {
7287
+ method: "GET",
7288
+ path: "/v1/orgs/:orgId/projects/:projectId/features",
7289
+ params: Empty,
7290
+ response: FeatureListResponse,
7291
+ mutates: false,
7292
+ requiresRole: "viewer"
7293
+ },
7294
+ "features.create": {
7295
+ method: "POST",
7296
+ path: "/v1/orgs/:orgId/projects/:projectId/features",
7297
+ params: CreateFeatureInput,
7298
+ response: Feature,
7299
+ mutates: true,
7300
+ requiresRole: "experimenter"
7301
+ },
7302
+ "rules.list": {
7303
+ method: "GET",
7304
+ path: "/v1/orgs/:orgId/features/:featureId/rules",
7305
+ params: Empty,
7306
+ response: FeatureRuleListResponse,
7307
+ mutates: false,
7308
+ requiresRole: "viewer"
7309
+ },
7310
+ "rules.create": {
7311
+ method: "POST",
7312
+ path: "/v1/orgs/:orgId/features/:featureId/rules",
7313
+ params: CreateFeatureRuleInput,
7314
+ response: FeatureRule,
7315
+ mutates: true,
7316
+ requiresRole: "experimenter"
7317
+ },
7318
+ "environments.publish": {
7319
+ method: "POST",
7320
+ path: "/v1/orgs/:orgId/environments/:environmentId/publish",
7321
+ params: Empty,
7322
+ response: EnvironmentPublication,
7323
+ mutates: true,
7324
+ requiresRole: "experimenter"
7325
+ },
7326
+ "environments.publications": {
7327
+ method: "GET",
7328
+ path: "/v1/orgs/:orgId/environments/:environmentId/publications",
7329
+ params: Empty,
7330
+ response: PublicationListResponse,
7331
+ mutates: false,
7332
+ requiresRole: "viewer"
7333
+ },
7334
+ "environments.promote": {
7335
+ method: "POST",
7336
+ path: "/v1/orgs/:orgId/environments/:environmentId/promote",
7337
+ params: PromoteEnvironmentInput2,
7338
+ response: PromoteEnvironmentResponse,
7339
+ mutates: true,
7340
+ requiresRole: "experimenter"
7341
+ },
7342
+ "configuration.getPublished": {
7343
+ method: "GET",
7344
+ path: "/v1/orgs/:orgId/environments/:environmentId/configuration",
7345
+ params: Empty,
7346
+ response: EnvironmentPublication,
7347
+ mutates: false,
7348
+ requiresRole: "viewer"
7349
+ },
7350
+ "manifests.publish": {
7351
+ method: "POST",
7352
+ path: "/v1/orgs/:orgId/manifests/publish",
7353
+ params: Empty,
7354
+ response: PublishManifestResponse,
7355
+ mutates: true,
7356
+ requiresRole: "experimenter"
7357
+ },
7358
+ "manifests.getKeys": {
7359
+ method: "GET",
7360
+ path: "/v1/orgs/:orgId/manifests/keys",
7361
+ params: Empty,
7362
+ response: ManifestKeysResponse,
7363
+ mutates: false,
7364
+ requiresRole: "admin"
7365
+ },
7366
+ "manifests.rotateKey": {
7367
+ method: "POST",
7368
+ path: "/v1/orgs/:orgId/manifests/keys/rotate",
7369
+ params: external_exports.object({ keyId: external_exports.string().min(1).max(128) }),
7370
+ response: ManifestKey,
7371
+ mutates: true,
7372
+ requiresRole: "admin"
7373
+ },
7374
+ "manifests.retireKey": {
7375
+ method: "POST",
7376
+ path: "/v1/orgs/:orgId/manifests/keys/retire",
7377
+ params: external_exports.object({ keyId: external_exports.string() }),
7378
+ response: ManifestKey,
7379
+ mutates: true,
7380
+ requiresRole: "admin"
7381
+ },
7382
+ "preview.sign": {
7383
+ method: "POST",
7384
+ path: "/v1/orgs/:orgId/preview/sign",
7385
+ params: PreviewSignInput,
7386
+ response: PreviewSignResponse,
7387
+ mutates: true,
7388
+ requiresRole: "experimenter"
7389
+ },
7390
+ "audit.list": {
7391
+ method: "GET",
7392
+ path: "/v1/orgs/:orgId/audit",
7393
+ params: Empty,
7394
+ response: AuditListResponse,
7395
+ mutates: false,
7396
+ requiresRole: "viewer"
7397
+ },
7398
+ "audit.exports.list": {
7399
+ method: "GET",
7400
+ path: "/v1/orgs/:orgId/audit/exports",
7401
+ params: Empty,
7402
+ response: AuditExportListResponse,
7403
+ mutates: false,
7404
+ requiresRole: "admin"
7405
+ },
7406
+ "audit.exports.create": {
7407
+ method: "POST",
7408
+ path: "/v1/orgs/:orgId/audit/exports",
7409
+ params: CreateAuditExportInput,
7410
+ response: AuditExport,
7411
+ mutates: true,
7412
+ requiresRole: "admin"
7413
+ },
7414
+ "audit.exports.delete": {
7415
+ method: "DELETE",
7416
+ path: "/v1/orgs/:orgId/audit/exports/:exportId",
7417
+ params: Empty,
7418
+ response: external_exports.object({ ok: external_exports.literal(true) }),
7419
+ mutates: true,
7420
+ requiresRole: "admin"
7421
+ },
7422
+ "apiKeys.list": {
7423
+ method: "GET",
7424
+ path: "/v1/orgs/:orgId/api-keys",
7425
+ params: Empty,
7426
+ response: ApiKeyListResponse,
7427
+ mutates: false,
7428
+ requiresRole: "admin"
7429
+ },
7430
+ "apiKeys.create": {
7431
+ method: "POST",
7432
+ path: "/v1/orgs/:orgId/api-keys",
7433
+ params: CreateApiKeyInput,
7434
+ response: CreateApiKeyResponse,
7435
+ mutates: true,
7436
+ requiresRole: "admin"
7437
+ },
7438
+ "apiKeys.revoke": {
7439
+ method: "DELETE",
7440
+ path: "/v1/orgs/:orgId/api-keys/:keyId",
7441
+ params: Empty,
7442
+ response: external_exports.object({ ok: external_exports.literal(true) }),
7443
+ mutates: true,
7444
+ requiresRole: "admin"
7445
+ },
7446
+ "saml.get": {
7447
+ method: "GET",
7448
+ path: "/v1/orgs/:orgId/saml",
7449
+ params: Empty,
7450
+ response: SamlConfig,
7451
+ mutates: false,
7452
+ requiresRole: "owner"
7453
+ },
7454
+ "saml.update": {
7455
+ method: "POST",
7456
+ path: "/v1/orgs/:orgId/saml",
7457
+ params: SamlConfig,
7458
+ response: SamlConfig,
7459
+ mutates: true,
7460
+ requiresRole: "owner"
7461
+ }
7462
+ };
7463
+ function buildPath(template, pathParams) {
7464
+ return template.replace(/:([a-zA-Z][a-zA-Z0-9_]*)/g, (_, name) => {
7465
+ const v = pathParams[name];
7466
+ if (v == null) throw new Error(`Missing path parameter: ${name}`);
7467
+ return encodeURIComponent(v);
7468
+ });
7469
+ }
7470
+ external_exports.object({
7471
+ code: external_exports.enum([
7472
+ "UNAUTHENTICATED",
7473
+ "FORBIDDEN",
7474
+ "NOT_FOUND",
7475
+ "VALIDATION_FAILED",
7476
+ "CONFLICT",
7477
+ "RATE_LIMITED",
7478
+ "INTERNAL"
7479
+ ]),
7480
+ message: external_exports.string(),
7481
+ details: external_exports.record(external_exports.unknown()).optional()
7482
+ });
7483
+
7484
+ // ../api-client/dist/index.js
7485
+ var ApiError2 = class extends Error {
7486
+ constructor(status, code, message, details) {
7487
+ super(message);
7488
+ this.status = status;
7489
+ this.code = code;
7490
+ this.details = details;
7491
+ this.name = "ApiError";
7492
+ }
7493
+ status;
7494
+ code;
7495
+ details;
7496
+ };
7497
+ var ApiClient = class {
7498
+ constructor(opts) {
7499
+ this.opts = opts;
7500
+ this.fetchImpl = opts.fetchImpl ?? globalThis.fetch;
7501
+ if (!this.fetchImpl) throw new Error("ApiClient: no fetch available");
7502
+ }
7503
+ opts;
7504
+ fetchImpl;
7505
+ async call(name, params, pathParams) {
7506
+ const def = endpoints[name];
7507
+ const merged = {
7508
+ orgId: this.opts.defaultOrgId,
7509
+ ...pathParams ?? {}
7510
+ };
7511
+ const url = new URL(buildPath(def.path, merged), this.opts.baseUrl);
7512
+ const init = {
7513
+ method: def.method,
7514
+ headers: {
7515
+ accept: "application/json",
7516
+ ...this.opts.apiKey ? { authorization: `Bearer ${this.opts.apiKey}` } : {}
7517
+ },
7518
+ credentials: "include"
7519
+ };
7520
+ if (def.method === "GET" || def.method === "DELETE") {
7521
+ for (const [k, v] of Object.entries(params)) {
7522
+ if (v != null) url.searchParams.set(k, String(v));
7523
+ }
7524
+ } else {
7525
+ init.headers = { ...init.headers, "content-type": "application/json" };
7526
+ init.body = JSON.stringify(params ?? {});
7527
+ }
7528
+ const attempts = this.opts.retry?.attempts ?? 3;
7529
+ const base = this.opts.retry?.baseDelayMs ?? 250;
7530
+ let lastErr;
7531
+ for (let i = 0; i < attempts; i++) {
7532
+ try {
7533
+ const r = await this.fetchImpl(url.toString(), init);
7534
+ if (r.ok) {
7535
+ if (r.status === 204) return void 0;
7536
+ return await r.json();
7537
+ }
7538
+ if (r.status < 500) {
7539
+ const body = await safeJson(r);
7540
+ const err = body?.error;
7541
+ throw new ApiError2(
7542
+ r.status,
7543
+ err?.code ?? "UNKNOWN",
7544
+ err?.message ?? r.statusText,
7545
+ err?.details
7546
+ );
7547
+ }
7548
+ lastErr = new ApiError2(r.status, "INTERNAL", `${r.status} ${r.statusText}`);
7549
+ } catch (e) {
7550
+ if (e instanceof ApiError2 && e.status < 500) throw e;
7551
+ lastErr = e;
7552
+ }
7553
+ await sleep(base * 2 ** i + Math.random() * 100);
7554
+ }
7555
+ throw lastErr;
7556
+ }
7557
+ // ---- Convenience namespaces (typed shortcuts) -----------------------------
7558
+ tenants = {
7559
+ me: () => this.call("tenants.me", {})
7560
+ };
7561
+ experiments = {
7562
+ list: (orgId) => this.call("experiments.list", {}, orgId ? { orgId } : void 0),
7563
+ get: (experimentId, orgId) => this.call("experiments.get", {}, orgId ? { orgId, experimentId } : { experimentId }),
7564
+ invokeAction: (params, orgId) => this.call("experiments.invokeAction", params, orgId ? { orgId } : void 0),
7565
+ aggregate: (experimentId, params, orgId) => this.call(
7566
+ "experiments.aggregate",
7567
+ params,
7568
+ orgId ? { orgId, experimentId } : { experimentId }
7569
+ )
7570
+ };
7571
+ projects = {
7572
+ list: (orgId) => this.call("projects.list", {}, orgId ? { orgId } : void 0),
7573
+ create: (params, orgId) => this.call("projects.create", params, orgId ? { orgId } : void 0)
7574
+ };
7575
+ properties = {
7576
+ list: (projectId, orgId) => this.call("properties.list", {}, orgId ? { orgId, projectId } : { projectId }),
7577
+ create: (projectId, params, orgId) => this.call("properties.create", params, orgId ? { orgId, projectId } : { projectId })
7578
+ };
7579
+ environments = {
7580
+ list: (projectId, orgId) => this.call("environments.list", {}, orgId ? { orgId, projectId } : { projectId }),
7581
+ create: (projectId, params, orgId) => this.call("environments.create", params, orgId ? { orgId, projectId } : { projectId }),
7582
+ publish: (environmentId, orgId) => this.call(
7583
+ "environments.publish",
7584
+ {},
7585
+ orgId ? { orgId, environmentId } : { environmentId }
7586
+ ),
7587
+ publications: (environmentId, orgId) => this.call(
7588
+ "environments.publications",
7589
+ {},
7590
+ orgId ? { orgId, environmentId } : { environmentId }
7591
+ ),
7592
+ promote: (environmentId, params, orgId) => this.call(
7593
+ "environments.promote",
7594
+ params,
7595
+ orgId ? { orgId, environmentId } : { environmentId }
7596
+ ),
7597
+ configuration: (environmentId, orgId) => this.call(
7598
+ "configuration.getPublished",
7599
+ {},
7600
+ orgId ? { orgId, environmentId } : { environmentId }
7601
+ )
7602
+ };
7603
+ features = {
7604
+ list: (projectId, orgId) => this.call("features.list", {}, orgId ? { orgId, projectId } : { projectId }),
7605
+ create: (projectId, params, orgId) => this.call("features.create", params, orgId ? { orgId, projectId } : { projectId })
7606
+ };
7607
+ rules = {
7608
+ list: (featureId, orgId) => this.call("rules.list", {}, orgId ? { orgId, featureId } : { featureId }),
7609
+ create: (featureId, params, orgId) => this.call("rules.create", params, orgId ? { orgId, featureId } : { featureId })
7610
+ };
7611
+ manifests = {
7612
+ publish: (orgId) => this.call("manifests.publish", {}, orgId ? { orgId } : void 0),
7613
+ getKeys: (orgId) => this.call("manifests.getKeys", {}, orgId ? { orgId } : void 0),
7614
+ rotateKey: (keyId, orgId) => this.call("manifests.rotateKey", { keyId }, orgId ? { orgId } : void 0),
7615
+ retireKey: (keyId, orgId) => this.call("manifests.retireKey", { keyId }, orgId ? { orgId } : void 0)
7616
+ };
7617
+ audit = {
7618
+ list: (orgId) => this.call("audit.list", {}, orgId ? { orgId } : void 0)
7619
+ };
7620
+ preview = {
7621
+ sign: (params, orgId) => this.call("preview.sign", params, orgId ? { orgId } : void 0)
7622
+ };
7623
+ apiKeys = {
7624
+ list: (orgId) => this.call("apiKeys.list", {}, orgId ? { orgId } : void 0),
7625
+ create: (params, orgId) => this.call("apiKeys.create", params, orgId ? { orgId } : void 0),
7626
+ revoke: (keyId, orgId) => this.call("apiKeys.revoke", {}, orgId ? { orgId, keyId } : { keyId })
7627
+ };
7628
+ saml = {
7629
+ get: (orgId) => this.call("saml.get", {}, orgId ? { orgId } : void 0),
7630
+ update: (params, orgId) => this.call("saml.update", params, orgId ? { orgId } : void 0)
7631
+ };
7632
+ };
7633
+ async function safeJson(r) {
7634
+ try {
7635
+ return await r.json();
7636
+ } catch {
7637
+ return null;
7638
+ }
7639
+ }
7640
+ function sleep(ms) {
7641
+ return new Promise((resolve9) => setTimeout(resolve9, ms));
7642
+ }
7643
+
7644
+ // src/commands/preview.ts
7645
+ var LOCAL_SECRET_FILE = "preview-secret";
7646
+ async function cmdPreview(experimentId, options) {
7647
+ if (!options.variantKey) {
7648
+ process.stderr.write(
7649
+ "Usage: fx preview <experimentId> --variant <key> [--ttl 900] [--origin https://...]\n"
7650
+ );
7651
+ return 1;
7652
+ }
7653
+ const tenantId = options.tenantId ?? "default";
7654
+ const ttl = clamp(options.ttlSeconds ?? 900, 60, 3600);
7655
+ const exp = Math.floor(Date.now() / 1e3) + ttl;
7656
+ let token;
7657
+ let signerId;
7658
+ if (options.apiUrl && options.apiKey && !options.local) {
7659
+ const client = new ApiClient({
7660
+ baseUrl: options.apiUrl,
7661
+ apiKey: options.apiKey,
7662
+ defaultOrgId: tenantId
7663
+ });
7664
+ const r = await client.call(
7665
+ "preview.sign",
7666
+ {
7667
+ experimentId,
7668
+ variantKey: options.variantKey,
7669
+ ttlSeconds: ttl
7670
+ },
7671
+ { orgId: tenantId }
7672
+ );
7673
+ token = r.token;
7674
+ signerId = r.keyId;
7675
+ } else {
7676
+ const ws = await loadWorkspace();
7677
+ const secretFile = path.join(ws.fxDir, LOCAL_SECRET_FILE);
7678
+ let secret;
7679
+ if (fs.existsSync(secretFile)) {
7680
+ secret = new Uint8Array(Buffer.from(fs.readFileSync(secretFile, "utf8"), "hex"));
7681
+ } else {
7682
+ secret = crypto$1.webcrypto.getRandomValues(new Uint8Array(32));
7683
+ fs.writeFileSync(secretFile, Buffer.from(secret).toString("hex"), { mode: 384 });
7684
+ process.stderr.write(`(generated local preview secret at ${secretFile})
7685
+ `);
7686
+ }
7687
+ token = await signHs256(
7688
+ { experimentId, variantKey: options.variantKey, tenantId, exp },
7689
+ secret
7690
+ );
7691
+ signerId = "local-hs256";
7692
+ }
7693
+ const params = new URLSearchParams({
7694
+ fxpreview: `${experimentId}:${options.variantKey}`,
7695
+ fxtoken: token
7696
+ });
7697
+ const url = options.origin ? `${options.origin.replace(/\/$/, "")}/?${params.toString()}` : `?${params.toString()}`;
7698
+ process.stdout.write(
7699
+ [
7700
+ `Experiment: ${experimentId}`,
7701
+ `Variant: ${options.variantKey}`,
7702
+ `Tenant: ${tenantId}`,
7703
+ `Expires: ${new Date(exp * 1e3).toISOString()} (TTL ${ttl}s)`,
7704
+ `Signer: ${signerId}`,
7705
+ "",
7706
+ url,
7707
+ ""
7708
+ ].join("\n")
7709
+ );
7710
+ return 0;
7711
+ }
7712
+ function clamp(n, min, max) {
7713
+ if (n < min) return min;
7714
+ if (n > max) return max;
7715
+ return n;
7716
+ }
7717
+ function b64url(bytes) {
7718
+ const data = typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes;
7719
+ return Buffer.from(data).toString("base64url");
7720
+ }
7721
+ async function signHs256(claim, secret) {
7722
+ const header = { alg: "HS256", typ: "JWT" };
7723
+ const h = b64url(JSON.stringify(header));
7724
+ const p = b64url(JSON.stringify(claim));
7725
+ const signing = `${h}.${p}`;
7726
+ const key = await crypto$1.webcrypto.subtle.importKey(
7727
+ "raw",
7728
+ secret,
7729
+ { name: "HMAC", hash: "SHA-256" },
7730
+ false,
7731
+ ["sign"]
7732
+ );
7733
+ const sig = new Uint8Array(
7734
+ await crypto$1.webcrypto.subtle.sign("HMAC", key, new TextEncoder().encode(signing))
7735
+ );
7736
+ return `${signing}.${b64url(sig)}`;
7737
+ }
7738
+ async function cmdPush(dir, options = {}) {
7739
+ const apiUrl = options.apiUrl ?? process.env.FX_API_URL;
7740
+ const apiKey = options.apiKey ?? process.env.FX_API_KEY;
7741
+ const tenantId = options.tenantId ?? process.env.FX_ORG_ID ?? "default";
7742
+ if (!apiUrl || !apiKey) {
7743
+ process.stderr.write(
7744
+ "Usage: fx push <dir> --api-url <url> --api-key <key> [--tenant <orgId>]\n"
7745
+ );
7746
+ return 1;
7747
+ }
7748
+ const api = new ApiClient({ baseUrl: apiUrl, apiKey, defaultOrgId: tenantId });
7749
+ const specs = (await loadExperimentDir(path.resolve(dir))).map((s) => s.spec);
7750
+ const summaries = (await api.experiments.list()).experiments;
7751
+ const current = [];
7752
+ for (const summary of summaries) {
7753
+ current.push(await api.experiments.get(summary.id));
7754
+ }
7755
+ const p = plan({
7756
+ specs,
7757
+ current,
7758
+ tenantId,
7759
+ ownerId: options.ownerId ?? "cli",
7760
+ approverId: options.approverId ?? "cli-reviewer",
7761
+ allowDeletes: options.allowDeletes
7762
+ });
7763
+ process.stdout.write(formatPlan(p));
7764
+ process.stdout.write("\n");
7765
+ if (p.blocked.length > 0) {
7766
+ process.stderr.write("\nPush blocked. Resolve the issues above and re-run.\n");
7767
+ return 2;
7768
+ }
7769
+ if (options.dryRun || p.actions.length === 0) return 0;
7770
+ for (const action of p.actions) {
7771
+ const result = await invokeHostedPlanned(
7772
+ api,
7773
+ action,
7774
+ options.ownerId ?? "cli",
7775
+ options.approverId ?? "cli-reviewer"
7776
+ );
7777
+ if (!result.success) throw new Error(`${action.actionId}: ${result.error ?? "failed"}`);
7778
+ }
7779
+ if (options.publish !== false) {
7780
+ const manifest = await api.manifests.publish();
7781
+ process.stdout.write(
7782
+ `
7783
+ Manifest v${manifest.manifestVersion} published (${manifest.experimentCount} live experiment${manifest.experimentCount === 1 ? "" : "s"}).
7784
+ `
7785
+ );
7786
+ }
7787
+ return 0;
7788
+ }
7789
+ async function invokeHostedPlanned(api, action, ownerId, approverId) {
7790
+ if (action.actionId === "experiment.create") {
7791
+ return api.experiments.invokeAction({
7792
+ actionId: "experiment.create",
7793
+ params: { ...action.params.spec, ownerId, tenantId: action.params.tenantId }
7794
+ });
7795
+ }
7796
+ if (action.actionId === "experiment.approve") {
7797
+ return api.experiments.invokeAction({
7798
+ actionId: action.actionId,
7799
+ params: { ...action.params, approverId }
7800
+ });
7801
+ }
7802
+ return api.experiments.invokeAction(action);
7803
+ }
7804
+ var FILES = {
7805
+ "cucumber.mjs": `export default {
7806
+ paths: ['features/**/*.feature'],
7807
+ import: ['features/support/steps.ts'],
7808
+ format: [
7809
+ 'progress',
7810
+ ['@fabricorg/databricks-bdd/evidence-formatter', 'reports/evidence.json'],
7811
+ ],
7812
+ };
7813
+ `,
7814
+ "features/support/steps.ts": `import '@fabricorg/databricks-bdd/steps';
7815
+ `,
7816
+ "features/databricks.feature": `Feature: Databricks SQL contract
7817
+
7818
+ Scenario: A seeded table is queryable
7819
+ Given catalog "fx_test" and schema "scenarios"
7820
+ And a table "example_events" with:
7821
+ | id | event_name |
7822
+ | 1 | signup |
7823
+ When I query table "example_events"
7824
+ Then the result has 1 rows
7825
+ `,
7826
+ "fixtures/example.json": `${JSON.stringify(
7827
+ {
7828
+ table: "example_events",
7829
+ schema: "id BIGINT, event_name STRING",
7830
+ rows: [[1, "signup"]]
7831
+ },
7832
+ null,
7833
+ 2
7834
+ )}
5966
7835
  `,
5967
- "utf8"
7836
+ ".env.databricks.example": `DBX_TEST_PROFILE=local
7837
+ # Live runs additionally require DBX_TEST_LIVE=1, DATABRICKS_HOST,
7838
+ # DATABRICKS_WAREHOUSE_ID, DBX_TEST_CATALOG/SCHEMA, and an auth method.
7839
+ `
7840
+ };
7841
+ async function cmdInitDatabricksTests(directory = "databricks-tests", options = {}) {
7842
+ const root = path.resolve(directory);
7843
+ for (const relative of Object.keys(FILES)) {
7844
+ const path$1 = path.join(root, relative);
7845
+ if (!options.force && await exists(path$1)) {
7846
+ throw new Error(`${path$1} already exists; pass --force to overwrite`);
7847
+ }
7848
+ }
7849
+ for (const [relative, contents] of Object.entries(FILES)) {
7850
+ const path$1 = path.join(root, relative);
7851
+ await promises.mkdir(path.join(path$1, ".."), { recursive: true });
7852
+ await promises.writeFile(path$1, contents, "utf8");
7853
+ }
7854
+ process.stdout.write(`Databricks test scaffold written to ${root}
7855
+ `);
7856
+ return 0;
7857
+ }
7858
+ async function exists(path) {
7859
+ try {
7860
+ await promises.access(path);
7861
+ return true;
7862
+ } catch {
7863
+ return false;
7864
+ }
7865
+ }
7866
+ var DEFAULT_STATE = ".fx/databricks-test-environments.json";
7867
+ async function cmdTestEnv(action, options = {}) {
7868
+ const env = options.env ?? process.env;
7869
+ if (env.DBX_TEST_LIVE !== "1") throw new Error("fx test env requires DBX_TEST_LIVE=1");
7870
+ switch (action) {
7871
+ case "create":
7872
+ await createTestEnvironment(options);
7873
+ return 0;
7874
+ case "destroy":
7875
+ await destroyTestEnvironment(options);
7876
+ return 0;
7877
+ case "list":
7878
+ await listTestEnvironments(options);
7879
+ return 0;
7880
+ case "reap":
7881
+ await reapTestEnvironments(options);
7882
+ return 0;
7883
+ default:
7884
+ throw new Error("Usage: fx test env <create|destroy|list|reap> [--name <name>]");
7885
+ }
7886
+ }
7887
+ async function createTestEnvironment(options) {
7888
+ const env = options.env ?? process.env;
7889
+ const name = requireName(options.name);
7890
+ const catalog = validateIdentifier(options.catalog ?? env.DBX_TEST_CATALOG, "catalog");
7891
+ const schema = validateIdentifier(toSchemaName(name), "schema");
7892
+ const statePath = options.statePath ?? DEFAULT_STATE;
7893
+ const state = await readState(statePath);
7894
+ if (state.environments.some((item) => item.name === name)) {
7895
+ throw new Error(`Test environment '${name}' already exists in ${statePath}`);
7896
+ }
7897
+ const ttlMs = parseTtl(options.ttl ?? "24h");
7898
+ const factory = options.contextFactory ?? databricksTestkit.createWorkspaceContext;
7899
+ const admin = await factory({
7900
+ env: { ...env, DBX_TEST_SCHEMA: void 0 },
7901
+ cleanupFixtures: false
7902
+ });
7903
+ let lakebase;
7904
+ try {
7905
+ await admin.exec(`CREATE SCHEMA IF NOT EXISTS ${catalog}.${schema}`);
7906
+ if (options.principal) {
7907
+ const principal = quotePrincipal(options.principal);
7908
+ if (options.grantCatalog !== false) {
7909
+ await admin.exec(`GRANT USE CATALOG ON CATALOG ${catalog} TO ${principal}`);
7910
+ }
7911
+ await admin.exec(
7912
+ `GRANT USE SCHEMA, CREATE TABLE, MODIFY, SELECT ON SCHEMA ${catalog}.${schema} TO ${principal}`
7913
+ );
7914
+ }
7915
+ const expiresAt = new Date(now2(options).getTime() + ttlMs).toISOString();
7916
+ await admin.exec(
7917
+ `ALTER SCHEMA ${catalog}.${schema} SET DBPROPERTIES ('fx.test_env' = 'true', 'fx.expires_at' = '${expiresAt}')`
5968
7918
  );
5969
- return kp;
7919
+ if (options.seedDir) {
7920
+ const scoped = await factory({
7921
+ env: { ...env, DBX_TEST_CATALOG: catalog, DBX_TEST_SCHEMA: schema },
7922
+ cleanupFixtures: false
7923
+ });
7924
+ try {
7925
+ for (const fixture of await readSeedFixtures(options.seedDir)) {
7926
+ await scoped.loadFixture(fixture);
7927
+ }
7928
+ } finally {
7929
+ await scoped.close();
7930
+ }
7931
+ }
7932
+ if (options.lakebaseBranch) {
7933
+ lakebase = await databricksTestkit.createEphemeralLakebaseBranch({
7934
+ env,
7935
+ ...options.lakebaseClient ? { client: options.lakebaseClient } : {},
7936
+ ...options.lakebaseProject ? { project: options.lakebaseProject } : {},
7937
+ branchId: databricksTestkit.toLakebaseBranchId(name),
7938
+ ttlMs,
7939
+ now: options.now
7940
+ });
7941
+ }
7942
+ const created = {
7943
+ name,
7944
+ catalog,
7945
+ schema,
7946
+ ...options.principal ? { principal: options.principal } : {},
7947
+ createdAt: now2(options).toISOString(),
7948
+ expiresAt,
7949
+ ...lakebase ? { lakebase } : {}
7950
+ };
7951
+ state.environments.push(created);
7952
+ await writeState(statePath, state);
7953
+ process.stdout.write(`${JSON.stringify(created)}
7954
+ `);
7955
+ return created;
7956
+ } catch (error) {
7957
+ if (lakebase) {
7958
+ await databricksTestkit.deleteEphemeralLakebaseBranch(lakebase, {
7959
+ env,
7960
+ ...options.lakebaseClient ? { client: options.lakebaseClient } : {}
7961
+ }).catch(() => void 0);
7962
+ }
7963
+ await admin.exec(`DROP SCHEMA IF EXISTS ${catalog}.${schema} CASCADE`).catch(() => void 0);
7964
+ throw error;
7965
+ } finally {
7966
+ await admin.close();
7967
+ }
7968
+ }
7969
+ async function destroyTestEnvironment(options) {
7970
+ const name = requireName(options.name);
7971
+ const env = options.env ?? process.env;
7972
+ const statePath = options.statePath ?? DEFAULT_STATE;
7973
+ const state = await readState(statePath);
7974
+ const target = state.environments.find((item) => item.name === name);
7975
+ if (!target) throw new Error(`Unknown test environment '${name}'`);
7976
+ const factory = options.contextFactory ?? databricksTestkit.createWorkspaceContext;
7977
+ const admin = await factory({
7978
+ env: { ...env, DBX_TEST_SCHEMA: void 0 },
7979
+ cleanupFixtures: false
7980
+ });
7981
+ try {
7982
+ await admin.exec(`DROP SCHEMA IF EXISTS ${target.catalog}.${target.schema} CASCADE`);
7983
+ if (target.lakebase) {
7984
+ await databricksTestkit.deleteEphemeralLakebaseBranch(target.lakebase, {
7985
+ env,
7986
+ ...options.lakebaseClient ? { client: options.lakebaseClient } : {}
7987
+ });
7988
+ }
7989
+ } finally {
7990
+ await admin.close();
7991
+ }
7992
+ state.environments = state.environments.filter((item) => item.name !== name);
7993
+ await writeState(statePath, state);
7994
+ }
7995
+ async function listTestEnvironments(options = {}) {
7996
+ const state = await readState(options.statePath ?? DEFAULT_STATE);
7997
+ for (const item of state.environments) process.stdout.write(`${JSON.stringify(item)}
7998
+ `);
7999
+ return state.environments;
8000
+ }
8001
+ async function reapTestEnvironments(options = {}) {
8002
+ const state = options.remote ? { environments: await discoverRemoteEnvironments(options) } : await readState(options.statePath ?? DEFAULT_STATE);
8003
+ const expired = state.environments.filter(
8004
+ (item) => Date.parse(item.expiresAt) <= now2(options).getTime()
8005
+ );
8006
+ if (options.remote && expired.length > 0) {
8007
+ const env = options.env ?? process.env;
8008
+ const factory = options.contextFactory ?? databricksTestkit.createWorkspaceContext;
8009
+ const admin = await factory({
8010
+ env: { ...env, DBX_TEST_SCHEMA: void 0 },
8011
+ cleanupFixtures: false
8012
+ });
8013
+ try {
8014
+ for (const item of expired) {
8015
+ await admin.exec(`DROP SCHEMA IF EXISTS ${item.catalog}.${item.schema} CASCADE`);
8016
+ }
8017
+ } finally {
8018
+ await admin.close();
8019
+ }
8020
+ } else {
8021
+ for (const item of expired) await destroyTestEnvironment({ ...options, name: item.name });
8022
+ }
8023
+ return expired.map((item) => item.name);
8024
+ }
8025
+ async function discoverRemoteEnvironments(options = {}) {
8026
+ const env = options.env ?? process.env;
8027
+ const catalog = validateIdentifier(options.catalog ?? env.DBX_TEST_CATALOG, "catalog");
8028
+ const factory = options.contextFactory ?? databricksTestkit.createWorkspaceContext;
8029
+ const admin = await factory({
8030
+ env: { ...env, DBX_TEST_SCHEMA: void 0 },
8031
+ cleanupFixtures: false
8032
+ });
8033
+ try {
8034
+ const schemas = await admin.query(`SHOW SCHEMAS IN ${catalog} LIKE 'fx_*'`);
8035
+ const found = [];
8036
+ for (const row of schemas) {
8037
+ const schema = String(row.databaseName ?? row.namespace ?? row.schemaName ?? "");
8038
+ if (!/^fx_[A-Za-z0-9_]+$/.test(schema)) continue;
8039
+ const description = await admin.query(`DESCRIBE SCHEMA EXTENDED ${catalog}.${schema}`);
8040
+ const properties = description.map((item) => String(item.database_description_value ?? item.info_value ?? "")).join(" ");
8041
+ const expiresAt = properties.match(
8042
+ /fx\.expires_at[^0-9]*(\d{4}-\d{2}-\d{2}T[^'"),\]]+)/
8043
+ )?.[1];
8044
+ if (!expiresAt || Number.isNaN(Date.parse(expiresAt))) continue;
8045
+ found.push({
8046
+ name: schema.replace(/^fx_/, "").replaceAll("_", "-"),
8047
+ catalog,
8048
+ schema,
8049
+ createdAt: "",
8050
+ expiresAt
8051
+ });
8052
+ }
8053
+ return found;
8054
+ } finally {
8055
+ await admin.close();
5970
8056
  }
5971
8057
  }
8058
+ function now2(options) {
8059
+ return options.now?.() ?? /* @__PURE__ */ new Date();
8060
+ }
8061
+ function requireName(value) {
8062
+ if (!value) throw new Error("Test environment name is required (--name <name>)");
8063
+ if (!/^[A-Za-z0-9_-]+$/.test(value)) throw new Error(`Invalid test environment name '${value}'`);
8064
+ return value;
8065
+ }
8066
+ function toSchemaName(name) {
8067
+ const normalized = name.toLowerCase().replaceAll("-", "_");
8068
+ return normalized.startsWith("fx_") ? normalized : `fx_${normalized}`;
8069
+ }
8070
+ function validateIdentifier(value, label) {
8071
+ if (!value || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) {
8072
+ throw new Error(`A safe ${label} identifier is required, got '${value ?? ""}'`);
8073
+ }
8074
+ return value;
8075
+ }
8076
+ function quotePrincipal(value) {
8077
+ if (!value || value.includes("`")) {
8078
+ throw new Error("Principal must be non-empty and cannot contain backticks");
8079
+ }
8080
+ return `\`${value}\``;
8081
+ }
8082
+ function parseTtl(value) {
8083
+ const match = value.match(/^(\d+)(m|h|d)$/);
8084
+ if (!match) throw new Error(`TTL must look like 30m, 24h, or 7d; got '${value}'`);
8085
+ const amount = Number(match[1]);
8086
+ const unit = match[2];
8087
+ return amount * (unit === "m" ? 6e4 : unit === "h" ? 36e5 : 864e5);
8088
+ }
8089
+ async function readSeedFixtures(directory) {
8090
+ const files = (await promises.readdir(directory)).filter((file) => file.endsWith(".json")).sort();
8091
+ const fixtures = [];
8092
+ for (const file of files) {
8093
+ const parsed = JSON.parse(await promises.readFile(path.join(directory, file), "utf8"));
8094
+ fixtures.push(...Array.isArray(parsed) ? parsed : [parsed]);
8095
+ }
8096
+ return fixtures;
8097
+ }
8098
+ async function readState(path) {
8099
+ try {
8100
+ return JSON.parse(await promises.readFile(path, "utf8"));
8101
+ } catch (error) {
8102
+ if (error.code === "ENOENT") {
8103
+ return { schemaVersion: 1, environments: [] };
8104
+ }
8105
+ throw error;
8106
+ }
8107
+ }
8108
+ async function writeState(path$1, state) {
8109
+ await promises.mkdir(path.dirname(path$1), { recursive: true });
8110
+ await promises.writeFile(path$1, `${JSON.stringify(state, null, 2)}
8111
+ `, "utf8");
8112
+ }
5972
8113
 
5973
8114
  exports.cmdApply = cmdApply;
5974
8115
  exports.cmdDev = cmdDev;
8116
+ exports.cmdImportMojito = cmdImportMojito;
8117
+ exports.cmdInitDatabricksTests = cmdInitDatabricksTests;
5975
8118
  exports.cmdKill = cmdKill;
5976
8119
  exports.cmdPlan = cmdPlan;
8120
+ exports.cmdPreview = cmdPreview;
5977
8121
  exports.cmdPublish = cmdPublish;
8122
+ exports.cmdPush = cmdPush;
5978
8123
  exports.cmdReport = cmdReport;
8124
+ exports.cmdTestEnv = cmdTestEnv;
5979
8125
  exports.cmdValidate = cmdValidate;
8126
+ exports.createTestEnvironment = createTestEnvironment;
8127
+ exports.destroyTestEnvironment = destroyTestEnvironment;
8128
+ exports.discoverRemoteEnvironments = discoverRemoteEnvironments;
8129
+ exports.listTestEnvironments = listTestEnvironments;
5980
8130
  exports.loadExperimentDir = loadExperimentDir;
5981
8131
  exports.loadExperimentFile = loadExperimentFile;
5982
8132
  exports.loadWorkspace = loadWorkspace;
8133
+ exports.reapTestEnvironments = reapTestEnvironments;
5983
8134
  //# sourceMappingURL=index.cjs.map
5984
8135
  //# sourceMappingURL=index.cjs.map