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