@fabricorg/experiments 0.5.3 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/fx.cjs +2878 -109
- package/dist/bin/fx.cjs.map +1 -1
- package/dist/bin/fx.js +8778 -15
- package/dist/bin/fx.js.map +1 -1
- package/package.json +8 -17
- package/dist/chunk-57IPTSQM.js +0 -5997
- package/dist/chunk-57IPTSQM.js.map +0 -1
- package/dist/index.cjs +0 -6008
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -102
- package/dist/index.d.ts +0 -102
- package/dist/index.js +0 -3
- package/dist/index.js.map +0 -1
package/dist/bin/fx.cjs
CHANGED
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
|
+
var fs = require('fs');
|
|
4
5
|
var path = require('path');
|
|
6
|
+
var url = require('url');
|
|
5
7
|
var promises = require('fs/promises');
|
|
6
8
|
var yaml = require('yaml');
|
|
7
|
-
var fs = require('fs');
|
|
8
9
|
var crypto$1 = require('crypto');
|
|
9
10
|
var http = require('http');
|
|
11
|
+
var module$1 = require('module');
|
|
12
|
+
var databricksTestkit = require('@fabricorg/databricks-testkit');
|
|
13
|
+
var fastXmlParser = require('fast-xml-parser');
|
|
10
14
|
|
|
15
|
+
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
11
16
|
var __defProp = Object.defineProperty;
|
|
12
17
|
var __export = (target, all) => {
|
|
13
18
|
for (var name in all)
|
|
@@ -4067,23 +4072,131 @@ var ExperimentState = external_exports.enum([
|
|
|
4067
4072
|
"archived"
|
|
4068
4073
|
]);
|
|
4069
4074
|
var VariantKey = external_exports.string().min(1).max(32).regex(/^[a-z0-9_-]+$/);
|
|
4075
|
+
var JsSource = external_exports.string().max(5e4).refine(
|
|
4076
|
+
(source) => {
|
|
4077
|
+
try {
|
|
4078
|
+
new Function("experiment", "variant", source);
|
|
4079
|
+
return true;
|
|
4080
|
+
} catch {
|
|
4081
|
+
return false;
|
|
4082
|
+
}
|
|
4083
|
+
},
|
|
4084
|
+
{ message: "JavaScript contains a syntax error" }
|
|
4085
|
+
);
|
|
4086
|
+
var CssSource = external_exports.string().max(5e4);
|
|
4087
|
+
var DomOp = external_exports.discriminatedUnion("op", [
|
|
4088
|
+
external_exports.object({
|
|
4089
|
+
op: external_exports.literal("replaceText"),
|
|
4090
|
+
selector: external_exports.string().min(1).max(512),
|
|
4091
|
+
value: external_exports.string().max(1e4),
|
|
4092
|
+
waitForMs: external_exports.number().int().min(0).max(3e4).optional()
|
|
4093
|
+
}),
|
|
4094
|
+
external_exports.object({
|
|
4095
|
+
op: external_exports.literal("replaceHTML"),
|
|
4096
|
+
selector: external_exports.string().min(1).max(512),
|
|
4097
|
+
value: external_exports.string().max(5e4),
|
|
4098
|
+
waitForMs: external_exports.number().int().min(0).max(3e4).optional()
|
|
4099
|
+
}),
|
|
4100
|
+
external_exports.object({
|
|
4101
|
+
op: external_exports.literal("setAttr"),
|
|
4102
|
+
selector: external_exports.string().min(1).max(512),
|
|
4103
|
+
name: external_exports.string().min(1).max(128),
|
|
4104
|
+
value: external_exports.string().max(2048),
|
|
4105
|
+
waitForMs: external_exports.number().int().min(0).max(3e4).optional()
|
|
4106
|
+
}),
|
|
4107
|
+
external_exports.object({
|
|
4108
|
+
op: external_exports.literal("addClass"),
|
|
4109
|
+
selector: external_exports.string().min(1).max(512),
|
|
4110
|
+
value: external_exports.string().min(1).max(256),
|
|
4111
|
+
waitForMs: external_exports.number().int().min(0).max(3e4).optional()
|
|
4112
|
+
}),
|
|
4113
|
+
external_exports.object({
|
|
4114
|
+
op: external_exports.literal("removeClass"),
|
|
4115
|
+
selector: external_exports.string().min(1).max(512),
|
|
4116
|
+
value: external_exports.string().min(1).max(256),
|
|
4117
|
+
waitForMs: external_exports.number().int().min(0).max(3e4).optional()
|
|
4118
|
+
}),
|
|
4119
|
+
external_exports.object({
|
|
4120
|
+
op: external_exports.literal("setStyle"),
|
|
4121
|
+
selector: external_exports.string().min(1).max(512),
|
|
4122
|
+
name: external_exports.string().min(1).max(128),
|
|
4123
|
+
value: external_exports.string().max(2048),
|
|
4124
|
+
waitForMs: external_exports.number().int().min(0).max(3e4).optional()
|
|
4125
|
+
}),
|
|
4126
|
+
external_exports.object({
|
|
4127
|
+
op: external_exports.literal("remove"),
|
|
4128
|
+
selector: external_exports.string().min(1).max(512),
|
|
4129
|
+
waitForMs: external_exports.number().int().min(0).max(3e4).optional()
|
|
4130
|
+
}),
|
|
4131
|
+
external_exports.object({
|
|
4132
|
+
op: external_exports.literal("injectCSS"),
|
|
4133
|
+
value: external_exports.string().min(1).max(5e4)
|
|
4134
|
+
}),
|
|
4135
|
+
external_exports.object({
|
|
4136
|
+
op: external_exports.literal("injectHTML"),
|
|
4137
|
+
selector: external_exports.string().min(1).max(512),
|
|
4138
|
+
position: external_exports.enum(["beforeend", "afterbegin", "beforebegin", "afterend"]),
|
|
4139
|
+
value: external_exports.string().max(5e4),
|
|
4140
|
+
waitForMs: external_exports.number().int().min(0).max(3e4).optional()
|
|
4141
|
+
})
|
|
4142
|
+
]);
|
|
4070
4143
|
var Variant = external_exports.object({
|
|
4071
4144
|
key: VariantKey,
|
|
4072
4145
|
name: external_exports.string().min(1).max(120),
|
|
4073
4146
|
/** Cumulative split weight in [0, 10000]; M1 ships even-split if all weights are 0/undefined. */
|
|
4074
4147
|
weight: external_exports.number().int().min(0).max(1e4).optional(),
|
|
4075
4148
|
/** Optional inline JS payload that the Web SDK eval-applies under try/catch. */
|
|
4076
|
-
js:
|
|
4149
|
+
js: JsSource.optional(),
|
|
4077
4150
|
/** Optional inline CSS payload that the Web SDK injects via <style>. */
|
|
4078
|
-
css:
|
|
4151
|
+
css: CssSource.optional(),
|
|
4152
|
+
/** Declarative DOM ops applied by the Web SDK after assignment (Mojito-parity). */
|
|
4153
|
+
domOps: external_exports.array(DomOp).optional(),
|
|
4154
|
+
/**
|
|
4155
|
+
* Mojito-parity: independent gate per variant. After bucketing selects this
|
|
4156
|
+
* variant, a second deterministic sample compares against `recipeSampleRate`.
|
|
4157
|
+
* Below the threshold, the SDK is "in-test but no recipe" and emits no
|
|
4158
|
+
* exposure. Distinct from `weight` (bucket split) and `audience.sampleRate`
|
|
4159
|
+
* (test-level eligibility).
|
|
4160
|
+
*/
|
|
4161
|
+
recipeSampleRate: external_exports.number().min(0).max(1).optional(),
|
|
4079
4162
|
/** Arbitrary feature payload available to server SDKs. */
|
|
4080
4163
|
payload: external_exports.record(external_exports.unknown()).optional()
|
|
4081
4164
|
});
|
|
4165
|
+
var Trigger = external_exports.discriminatedUnion("kind", [
|
|
4166
|
+
external_exports.object({ kind: external_exports.literal("auto") }),
|
|
4167
|
+
external_exports.object({
|
|
4168
|
+
kind: external_exports.literal("urlMatch"),
|
|
4169
|
+
/** Substring or regex source. If `regex` is true, pattern is a JS regex source. */
|
|
4170
|
+
pattern: external_exports.string().min(1).max(1024),
|
|
4171
|
+
regex: external_exports.boolean().optional()
|
|
4172
|
+
}),
|
|
4173
|
+
external_exports.object({
|
|
4174
|
+
kind: external_exports.literal("waitForSelector"),
|
|
4175
|
+
selector: external_exports.string().min(1).max(512),
|
|
4176
|
+
timeoutMs: external_exports.number().int().min(0).max(6e4).default(2e3)
|
|
4177
|
+
}),
|
|
4178
|
+
external_exports.object({
|
|
4179
|
+
kind: external_exports.literal("event"),
|
|
4180
|
+
name: external_exports.string().min(1).max(128)
|
|
4181
|
+
})
|
|
4182
|
+
]);
|
|
4183
|
+
var TargetingRule = external_exports.union([
|
|
4184
|
+
external_exports.boolean(),
|
|
4185
|
+
external_exports.number(),
|
|
4186
|
+
external_exports.string(),
|
|
4187
|
+
external_exports.array(external_exports.unknown()),
|
|
4188
|
+
external_exports.record(external_exports.unknown())
|
|
4189
|
+
]);
|
|
4082
4190
|
var Audience = external_exports.object({
|
|
4083
4191
|
/** Sample rate in [0, 1] of eligible traffic that the experiment applies to. */
|
|
4084
4192
|
sampleRate: external_exports.number().min(0).max(1).default(1),
|
|
4085
|
-
/**
|
|
4086
|
-
|
|
4193
|
+
/**
|
|
4194
|
+
* Optional targeting rule — a JSONLogic-style AST evaluated against
|
|
4195
|
+
* `targetingContext` (browser SDK) or `ctx.user` (server SDK). When the
|
|
4196
|
+
* rule evaluates to `false` for the current subject, the SDK returns
|
|
4197
|
+
* `null` from `treatment()` and emits no exposure.
|
|
4198
|
+
*/
|
|
4199
|
+
rule: TargetingRule.optional()
|
|
4087
4200
|
});
|
|
4088
4201
|
var MetricKind = external_exports.enum(["conversion", "count", "sum"]);
|
|
4089
4202
|
var Metric = external_exports.object({
|
|
@@ -4100,7 +4213,17 @@ var Approval = external_exports.object({
|
|
|
4100
4213
|
approvedAt: external_exports.string().datetime(),
|
|
4101
4214
|
note: external_exports.string().max(2e3).optional()
|
|
4102
4215
|
});
|
|
4103
|
-
external_exports.object({
|
|
4216
|
+
var DatabricksWorkload = external_exports.object({
|
|
4217
|
+
kind: external_exports.enum(["sql", "notebook", "job", "pipeline", "model", "feature-serving"]),
|
|
4218
|
+
resourceId: external_exports.string().min(1).max(256),
|
|
4219
|
+
resourceName: external_exports.string().min(1).max(256).optional(),
|
|
4220
|
+
evaluationMode: external_exports.enum(["online", "offline", "shadow"]).default("online"),
|
|
4221
|
+
assignmentUnit: external_exports.enum(["user", "request", "job-run", "table-partition"]).default("request"),
|
|
4222
|
+
catalog: external_exports.string().min(1).max(255).optional(),
|
|
4223
|
+
schema: external_exports.string().min(1).max(255).optional(),
|
|
4224
|
+
tags: external_exports.record(external_exports.string()).optional()
|
|
4225
|
+
});
|
|
4226
|
+
var Experiment = external_exports.object({
|
|
4104
4227
|
id: ExperimentId,
|
|
4105
4228
|
name: external_exports.string().min(1).max(200),
|
|
4106
4229
|
description: external_exports.string().max(4e3).optional(),
|
|
@@ -4110,23 +4233,64 @@ external_exports.object({
|
|
|
4110
4233
|
audience: Audience,
|
|
4111
4234
|
variants: external_exports.array(Variant).min(2),
|
|
4112
4235
|
metrics: external_exports.array(Metric).default([]),
|
|
4236
|
+
/** Activation trigger for Web SDK. Defaults to `{ kind: 'auto' }`. */
|
|
4237
|
+
trigger: Trigger.optional(),
|
|
4238
|
+
/** When true, SDK assigns + applies but defers `onExposure` until host calls `client.expose(id)`. */
|
|
4239
|
+
manualExposure: external_exports.boolean().optional(),
|
|
4240
|
+
/** When set to a variant key, all eligible traffic is routed to that variant (Mojito `divertTo`). */
|
|
4241
|
+
divertTo: VariantKey.optional(),
|
|
4242
|
+
/** Mojito-parity: shared JS that runs once per (experiment, page) before any variant code. */
|
|
4243
|
+
sharedJs: JsSource.optional(),
|
|
4244
|
+
/** Mojito-parity: shared CSS injected once per (experiment, page) before any variant CSS. */
|
|
4245
|
+
sharedCss: CssSource.optional(),
|
|
4246
|
+
/** Per-experiment metadata accessible to variant code via `client.metadata(id)`. */
|
|
4247
|
+
metadata: external_exports.record(external_exports.unknown()).optional(),
|
|
4113
4248
|
approval: Approval.nullable().default(null),
|
|
4114
4249
|
killReason: external_exports.string().max(500).nullable().default(null),
|
|
4115
4250
|
ownerId: external_exports.string().min(1),
|
|
4116
4251
|
tenantId: external_exports.string().min(1).default("default"),
|
|
4252
|
+
/** Optional Mojito-style hierarchy bindings. Legacy experiments remain tenant-scoped. */
|
|
4253
|
+
projectId: external_exports.string().uuid().optional(),
|
|
4254
|
+
propertyId: external_exports.string().uuid().optional(),
|
|
4255
|
+
featureId: external_exports.string().uuid().optional(),
|
|
4256
|
+
environmentIds: external_exports.array(external_exports.string().uuid()).optional(),
|
|
4257
|
+
workload: DatabricksWorkload.optional(),
|
|
4117
4258
|
createdAt: external_exports.string().datetime(),
|
|
4118
4259
|
updatedAt: external_exports.string().datetime(),
|
|
4119
4260
|
startedAt: external_exports.string().datetime().nullable().default(null),
|
|
4120
4261
|
endedAt: external_exports.string().datetime().nullable().default(null)
|
|
4121
4262
|
});
|
|
4122
|
-
var
|
|
4263
|
+
var ExperimentSpecBase = external_exports.object({
|
|
4123
4264
|
id: ExperimentId,
|
|
4124
4265
|
name: external_exports.string().min(1).max(200),
|
|
4125
4266
|
description: external_exports.string().max(4e3).optional(),
|
|
4267
|
+
projectId: external_exports.string().uuid().optional(),
|
|
4268
|
+
propertyId: external_exports.string().uuid().optional(),
|
|
4269
|
+
featureId: external_exports.string().uuid().optional(),
|
|
4270
|
+
environmentIds: external_exports.array(external_exports.string().uuid()).optional(),
|
|
4271
|
+
workload: DatabricksWorkload.optional(),
|
|
4126
4272
|
salt: external_exports.string().min(1).max(64).optional(),
|
|
4127
4273
|
sampleRate: external_exports.number().min(0).max(1).optional(),
|
|
4274
|
+
/**
|
|
4275
|
+
* Mojito-parity sugar: fraction of the eligible cohort held out of the test entirely.
|
|
4276
|
+
* `holdback: 0.1` means 10% of eligible traffic is excluded; the remainder is split
|
|
4277
|
+
* across variants per their weights. Compiles to `audience.sampleRate = 1 - holdback`.
|
|
4278
|
+
*/
|
|
4279
|
+
holdback: external_exports.number().min(0).max(1).optional(),
|
|
4128
4280
|
audience: Audience.partial().optional(),
|
|
4129
4281
|
variants: external_exports.array(Variant).min(2),
|
|
4282
|
+
/** Mojito-parity: route all eligible traffic to a single variant key. */
|
|
4283
|
+
divertTo: VariantKey.optional(),
|
|
4284
|
+
/** Mojito-parity: defer exposure until host calls `client.expose(id)`. */
|
|
4285
|
+
manualExposure: external_exports.boolean().optional(),
|
|
4286
|
+
/** Activation trigger for Web SDK. */
|
|
4287
|
+
trigger: Trigger.optional(),
|
|
4288
|
+
/** Mojito-parity: shared JS that runs once before any variant code. */
|
|
4289
|
+
sharedJs: JsSource.optional(),
|
|
4290
|
+
/** Mojito-parity: shared CSS injected once before any variant CSS. */
|
|
4291
|
+
sharedCss: CssSource.optional(),
|
|
4292
|
+
/** Per-experiment metadata accessible via `client.metadata(id)`. */
|
|
4293
|
+
metadata: external_exports.record(external_exports.unknown()).optional(),
|
|
4130
4294
|
metrics: external_exports.array(
|
|
4131
4295
|
external_exports.object({
|
|
4132
4296
|
key: external_exports.string().min(1).max(64),
|
|
@@ -4138,6 +4302,25 @@ var ExperimentSpec = external_exports.object({
|
|
|
4138
4302
|
})
|
|
4139
4303
|
).optional()
|
|
4140
4304
|
});
|
|
4305
|
+
var ExperimentSpec = ExperimentSpecBase.refine(
|
|
4306
|
+
(s) => s.holdback === void 0 || s.sampleRate === void 0,
|
|
4307
|
+
{ message: "Use either `sampleRate` or `holdback`, not both.", path: ["holdback"] }
|
|
4308
|
+
).refine((s) => s.divertTo === void 0 || s.variants.some((v) => v.key === s.divertTo), {
|
|
4309
|
+
message: "`divertTo` must reference an existing variant key.",
|
|
4310
|
+
path: ["divertTo"]
|
|
4311
|
+
}).refine(
|
|
4312
|
+
(s) => {
|
|
4313
|
+
const withWeight = s.variants.filter((v) => v.weight !== void 0);
|
|
4314
|
+
if (withWeight.length === 0) return true;
|
|
4315
|
+
if (withWeight.length !== s.variants.length) return false;
|
|
4316
|
+
const sum = withWeight.reduce((acc, v) => acc + (v.weight ?? 0), 0);
|
|
4317
|
+
return sum === 1e4;
|
|
4318
|
+
},
|
|
4319
|
+
{
|
|
4320
|
+
message: "When variant weights are set, all variants must have weights summing to 10000.",
|
|
4321
|
+
path: ["variants"]
|
|
4322
|
+
}
|
|
4323
|
+
);
|
|
4141
4324
|
external_exports.object({
|
|
4142
4325
|
experimentId: ExperimentId,
|
|
4143
4326
|
subjectId: external_exports.string().min(1),
|
|
@@ -4154,6 +4337,8 @@ var Exposure = external_exports.object({
|
|
|
4154
4337
|
tenantId: external_exports.string().min(1).default("default"),
|
|
4155
4338
|
manifestVersion: external_exports.number().int().min(0),
|
|
4156
4339
|
at: external_exports.string().datetime(),
|
|
4340
|
+
/** Explicit low-cardinality dimensions used by segmented analytics. */
|
|
4341
|
+
dimensions: external_exports.record(external_exports.string()).optional(),
|
|
4157
4342
|
/** Set when the variant code threw; used as a quality signal. */
|
|
4158
4343
|
failure: external_exports.object({ message: external_exports.string(), stack: external_exports.string().optional() }).nullable().default(null)
|
|
4159
4344
|
});
|
|
@@ -4183,7 +4368,132 @@ function canTransition(current, event2) {
|
|
|
4183
4368
|
function isLive(state) {
|
|
4184
4369
|
return state === "running" || state === "paused";
|
|
4185
4370
|
}
|
|
4186
|
-
external_exports.
|
|
4371
|
+
var ResourceKey = external_exports.string().min(2).max(64).regex(/^[a-z][a-z0-9_-]*$/, "lowercase key, must start with a letter");
|
|
4372
|
+
var ResourceBase = external_exports.object({
|
|
4373
|
+
id: external_exports.string().uuid(),
|
|
4374
|
+
tenantId: external_exports.string().min(1),
|
|
4375
|
+
key: ResourceKey,
|
|
4376
|
+
name: external_exports.string().min(1).max(200),
|
|
4377
|
+
description: external_exports.string().max(4e3).optional(),
|
|
4378
|
+
createdAt: external_exports.string().datetime(),
|
|
4379
|
+
updatedAt: external_exports.string().datetime()
|
|
4380
|
+
});
|
|
4381
|
+
var Project = ResourceBase.extend({
|
|
4382
|
+
kind: external_exports.literal("project")
|
|
4383
|
+
});
|
|
4384
|
+
var Property = ResourceBase.extend({
|
|
4385
|
+
kind: external_exports.literal("property"),
|
|
4386
|
+
projectId: external_exports.string().uuid(),
|
|
4387
|
+
platform: external_exports.enum(["web", "server", "mobile", "databricks"]),
|
|
4388
|
+
origins: external_exports.array(external_exports.string().url()).default([])
|
|
4389
|
+
});
|
|
4390
|
+
var EnvironmentTier = external_exports.enum(["development", "staging", "production"]);
|
|
4391
|
+
var Environment = ResourceBase.extend({
|
|
4392
|
+
kind: external_exports.literal("environment"),
|
|
4393
|
+
projectId: external_exports.string().uuid(),
|
|
4394
|
+
tier: EnvironmentTier,
|
|
4395
|
+
rank: external_exports.number().int().min(0).max(100),
|
|
4396
|
+
requiresApproval: external_exports.boolean().default(false)
|
|
4397
|
+
});
|
|
4398
|
+
var FeatureValue = external_exports.union([
|
|
4399
|
+
external_exports.boolean(),
|
|
4400
|
+
external_exports.string(),
|
|
4401
|
+
external_exports.number(),
|
|
4402
|
+
external_exports.record(external_exports.unknown()),
|
|
4403
|
+
external_exports.array(external_exports.unknown())
|
|
4404
|
+
]);
|
|
4405
|
+
var Feature = ResourceBase.extend({
|
|
4406
|
+
kind: external_exports.literal("feature"),
|
|
4407
|
+
projectId: external_exports.string().uuid(),
|
|
4408
|
+
propertyId: external_exports.string().uuid().optional(),
|
|
4409
|
+
valueType: external_exports.enum(["boolean", "string", "number", "json"]),
|
|
4410
|
+
defaultValue: FeatureValue,
|
|
4411
|
+
archived: external_exports.boolean().default(false)
|
|
4412
|
+
});
|
|
4413
|
+
var FeatureRule = external_exports.object({
|
|
4414
|
+
id: external_exports.string().uuid(),
|
|
4415
|
+
kind: external_exports.literal("rule"),
|
|
4416
|
+
tenantId: external_exports.string().min(1),
|
|
4417
|
+
featureId: external_exports.string().uuid(),
|
|
4418
|
+
environmentId: external_exports.string().uuid(),
|
|
4419
|
+
name: external_exports.string().min(1).max(200),
|
|
4420
|
+
enabled: external_exports.boolean().default(true),
|
|
4421
|
+
priority: external_exports.number().int().min(0).max(1e4),
|
|
4422
|
+
audience: TargetingRule.optional(),
|
|
4423
|
+
experimentId: ExperimentId.optional(),
|
|
4424
|
+
variants: external_exports.array(Variant).min(2).optional(),
|
|
4425
|
+
value: FeatureValue.optional(),
|
|
4426
|
+
rolloutPercentage: external_exports.number().min(0).max(100).default(100),
|
|
4427
|
+
createdAt: external_exports.string().datetime(),
|
|
4428
|
+
updatedAt: external_exports.string().datetime()
|
|
4429
|
+
});
|
|
4430
|
+
var EnvironmentPublication = external_exports.object({
|
|
4431
|
+
id: external_exports.string().uuid(),
|
|
4432
|
+
kind: external_exports.literal("publication"),
|
|
4433
|
+
tenantId: external_exports.string().min(1),
|
|
4434
|
+
environmentId: external_exports.string().uuid(),
|
|
4435
|
+
version: external_exports.number().int().positive(),
|
|
4436
|
+
status: external_exports.literal("published"),
|
|
4437
|
+
resourceHash: external_exports.string().regex(/^[0-9a-f]{64}$/),
|
|
4438
|
+
manifestVersion: external_exports.number().int().nonnegative(),
|
|
4439
|
+
publishedBy: external_exports.string().min(1),
|
|
4440
|
+
publishedAt: external_exports.string().datetime(),
|
|
4441
|
+
snapshot: external_exports.object({
|
|
4442
|
+
features: external_exports.array(Feature),
|
|
4443
|
+
rules: external_exports.array(FeatureRule)
|
|
4444
|
+
})
|
|
4445
|
+
});
|
|
4446
|
+
var WorkspaceResource = external_exports.discriminatedUnion("kind", [
|
|
4447
|
+
Project,
|
|
4448
|
+
Property,
|
|
4449
|
+
Environment,
|
|
4450
|
+
Feature,
|
|
4451
|
+
FeatureRule,
|
|
4452
|
+
EnvironmentPublication
|
|
4453
|
+
]);
|
|
4454
|
+
var MutableWorkspaceResource = external_exports.discriminatedUnion("kind", [
|
|
4455
|
+
Project,
|
|
4456
|
+
Property,
|
|
4457
|
+
Environment,
|
|
4458
|
+
Feature,
|
|
4459
|
+
FeatureRule
|
|
4460
|
+
]);
|
|
4461
|
+
var CreateProjectInput = Project.pick({ key: true, name: true, description: true });
|
|
4462
|
+
var CreatePropertyInput = Property.pick({
|
|
4463
|
+
key: true,
|
|
4464
|
+
name: true,
|
|
4465
|
+
description: true,
|
|
4466
|
+
platform: true,
|
|
4467
|
+
origins: true
|
|
4468
|
+
});
|
|
4469
|
+
var CreateEnvironmentInput = Environment.pick({
|
|
4470
|
+
key: true,
|
|
4471
|
+
name: true,
|
|
4472
|
+
description: true,
|
|
4473
|
+
tier: true,
|
|
4474
|
+
rank: true,
|
|
4475
|
+
requiresApproval: true
|
|
4476
|
+
});
|
|
4477
|
+
var CreateFeatureInput = Feature.pick({
|
|
4478
|
+
key: true,
|
|
4479
|
+
name: true,
|
|
4480
|
+
description: true,
|
|
4481
|
+
propertyId: true,
|
|
4482
|
+
valueType: true,
|
|
4483
|
+
defaultValue: true
|
|
4484
|
+
});
|
|
4485
|
+
var CreateFeatureRuleInput = FeatureRule.pick({
|
|
4486
|
+
name: true,
|
|
4487
|
+
environmentId: true,
|
|
4488
|
+
enabled: true,
|
|
4489
|
+
priority: true,
|
|
4490
|
+
audience: true,
|
|
4491
|
+
experimentId: true,
|
|
4492
|
+
variants: true,
|
|
4493
|
+
value: true,
|
|
4494
|
+
rolloutPercentage: true
|
|
4495
|
+
});
|
|
4496
|
+
var ActionId = external_exports.enum([
|
|
4187
4497
|
"experiment.create",
|
|
4188
4498
|
"experiment.submit_for_review",
|
|
4189
4499
|
"experiment.approve",
|
|
@@ -4193,9 +4503,12 @@ external_exports.enum([
|
|
|
4193
4503
|
"experiment.kill",
|
|
4194
4504
|
"experiment.declare_winner",
|
|
4195
4505
|
"experiment.update",
|
|
4196
|
-
"experiment.guardrail_breach"
|
|
4506
|
+
"experiment.guardrail_breach",
|
|
4507
|
+
"experiment.workspace_resource_upsert",
|
|
4508
|
+
"experiment.environment_publish",
|
|
4509
|
+
"experiment.environment_promote"
|
|
4197
4510
|
]);
|
|
4198
|
-
var CreateExperimentInput =
|
|
4511
|
+
var CreateExperimentInput = ExperimentSpecBase.extend({
|
|
4199
4512
|
ownerId: external_exports.string().min(1),
|
|
4200
4513
|
tenantId: external_exports.string().min(1).default("default")
|
|
4201
4514
|
});
|
|
@@ -4230,6 +4543,21 @@ var GuardrailBreachInput = ExperimentRef.extend({
|
|
|
4230
4543
|
/** When 'pause', the action also pauses the experiment as part of breach handling. */
|
|
4231
4544
|
action: external_exports.enum(["alert", "pause"]).default("alert")
|
|
4232
4545
|
});
|
|
4546
|
+
var UpsertWorkspaceResourceInput = external_exports.object({
|
|
4547
|
+
tenantId: external_exports.string().min(1),
|
|
4548
|
+
resource: MutableWorkspaceResource
|
|
4549
|
+
});
|
|
4550
|
+
var PublishEnvironmentInput = external_exports.object({
|
|
4551
|
+
tenantId: external_exports.string().min(1),
|
|
4552
|
+
environmentId: external_exports.string().uuid(),
|
|
4553
|
+
publishedBy: external_exports.string().min(1)
|
|
4554
|
+
});
|
|
4555
|
+
var PromoteEnvironmentInput = external_exports.object({
|
|
4556
|
+
tenantId: external_exports.string().min(1),
|
|
4557
|
+
sourceEnvironmentId: external_exports.string().uuid(),
|
|
4558
|
+
targetEnvironmentId: external_exports.string().uuid(),
|
|
4559
|
+
promotedBy: external_exports.string().min(1)
|
|
4560
|
+
});
|
|
4233
4561
|
external_exports.enum([
|
|
4234
4562
|
"experiment.created",
|
|
4235
4563
|
"experiment.submitted_for_review",
|
|
@@ -4245,7 +4573,11 @@ external_exports.enum([
|
|
|
4245
4573
|
"experiment.variant_updated",
|
|
4246
4574
|
"manifest.published",
|
|
4247
4575
|
"guardrail.breached",
|
|
4248
|
-
"analysis.completed"
|
|
4576
|
+
"analysis.completed",
|
|
4577
|
+
"experiment.preview_signed",
|
|
4578
|
+
"workspace_resource.upserted",
|
|
4579
|
+
"environment.published",
|
|
4580
|
+
"environment.promoted"
|
|
4249
4581
|
]);
|
|
4250
4582
|
var DomainError = class extends Error {
|
|
4251
4583
|
constructor(message, code, details) {
|
|
@@ -4281,6 +4613,32 @@ var PolicyDenied = class extends DomainError {
|
|
|
4281
4613
|
this.name = "PolicyDenied";
|
|
4282
4614
|
}
|
|
4283
4615
|
};
|
|
4616
|
+
function parseExperimentYamlText(text) {
|
|
4617
|
+
let parsed;
|
|
4618
|
+
try {
|
|
4619
|
+
parsed = yaml.parse(text);
|
|
4620
|
+
} catch (e) {
|
|
4621
|
+
return { ok: false, message: `YAML parse failed: ${e.message}` };
|
|
4622
|
+
}
|
|
4623
|
+
const result = ExperimentSpec.safeParse(parsed);
|
|
4624
|
+
if (!result.success) {
|
|
4625
|
+
return {
|
|
4626
|
+
ok: false,
|
|
4627
|
+
message: "Experiment spec validation failed",
|
|
4628
|
+
issues: result.error.issues.map((issue) => ({
|
|
4629
|
+
path: issue.path.join(".") || "spec",
|
|
4630
|
+
message: issue.message
|
|
4631
|
+
}))
|
|
4632
|
+
};
|
|
4633
|
+
}
|
|
4634
|
+
return { ok: true, spec: result.data };
|
|
4635
|
+
}
|
|
4636
|
+
function parseExperimentYamlTextOrThrow(text) {
|
|
4637
|
+
const result = parseExperimentYamlText(text);
|
|
4638
|
+
if (result.ok) return result.spec;
|
|
4639
|
+
const issueText = result.issues?.map((issue) => `${issue.path}: ${issue.message}`).join("; ");
|
|
4640
|
+
throw new Error(issueText ? `${result.message}: ${issueText}` : result.message);
|
|
4641
|
+
}
|
|
4284
4642
|
|
|
4285
4643
|
// src/yaml-loader.ts
|
|
4286
4644
|
async function loadExperimentDir(dir) {
|
|
@@ -4297,8 +4655,7 @@ async function loadExperimentDir(dir) {
|
|
|
4297
4655
|
}
|
|
4298
4656
|
async function loadExperimentFile(path) {
|
|
4299
4657
|
const text = await promises.readFile(path, "utf8");
|
|
4300
|
-
|
|
4301
|
-
return ExperimentSpec.parse(parsed);
|
|
4658
|
+
return parseExperimentYamlTextOrThrow(text);
|
|
4302
4659
|
}
|
|
4303
4660
|
|
|
4304
4661
|
// src/commands/validate.ts
|
|
@@ -4369,7 +4726,7 @@ function compareSpecToCurrent(spec, current) {
|
|
|
4369
4726
|
to: spec.description ?? null
|
|
4370
4727
|
});
|
|
4371
4728
|
}
|
|
4372
|
-
const specSampleRate = spec.sampleRate ?? spec.audience?.sampleRate ?? 1;
|
|
4729
|
+
const specSampleRate = spec.sampleRate ?? (spec.holdback !== void 0 ? 1 - spec.holdback : void 0) ?? spec.audience?.sampleRate ?? 1;
|
|
4373
4730
|
if (specSampleRate !== current.audience.sampleRate) {
|
|
4374
4731
|
changes.push({
|
|
4375
4732
|
kind: "changed",
|
|
@@ -4378,6 +4735,54 @@ function compareSpecToCurrent(spec, current) {
|
|
|
4378
4735
|
to: specSampleRate
|
|
4379
4736
|
});
|
|
4380
4737
|
}
|
|
4738
|
+
if ((spec.divertTo ?? null) !== (current.divertTo ?? null)) {
|
|
4739
|
+
changes.push({
|
|
4740
|
+
kind: "changed",
|
|
4741
|
+
path: "divertTo",
|
|
4742
|
+
from: current.divertTo ?? null,
|
|
4743
|
+
to: spec.divertTo ?? null
|
|
4744
|
+
});
|
|
4745
|
+
}
|
|
4746
|
+
if ((spec.manualExposure ?? false) !== (current.manualExposure ?? false)) {
|
|
4747
|
+
changes.push({
|
|
4748
|
+
kind: "changed",
|
|
4749
|
+
path: "manualExposure",
|
|
4750
|
+
from: current.manualExposure ?? false,
|
|
4751
|
+
to: spec.manualExposure ?? false
|
|
4752
|
+
});
|
|
4753
|
+
}
|
|
4754
|
+
if (JSON.stringify(spec.trigger ?? null) !== JSON.stringify(current.trigger ?? null)) {
|
|
4755
|
+
changes.push({
|
|
4756
|
+
kind: "changed",
|
|
4757
|
+
path: "trigger",
|
|
4758
|
+
from: current.trigger ?? null,
|
|
4759
|
+
to: spec.trigger ?? null
|
|
4760
|
+
});
|
|
4761
|
+
}
|
|
4762
|
+
if ((spec.sharedJs ?? null) !== (current.sharedJs ?? null)) {
|
|
4763
|
+
changes.push({
|
|
4764
|
+
kind: "changed",
|
|
4765
|
+
path: "sharedJs",
|
|
4766
|
+
from: current.sharedJs ?? null,
|
|
4767
|
+
to: spec.sharedJs ?? null
|
|
4768
|
+
});
|
|
4769
|
+
}
|
|
4770
|
+
if ((spec.sharedCss ?? null) !== (current.sharedCss ?? null)) {
|
|
4771
|
+
changes.push({
|
|
4772
|
+
kind: "changed",
|
|
4773
|
+
path: "sharedCss",
|
|
4774
|
+
from: current.sharedCss ?? null,
|
|
4775
|
+
to: spec.sharedCss ?? null
|
|
4776
|
+
});
|
|
4777
|
+
}
|
|
4778
|
+
if (JSON.stringify(spec.metadata ?? null) !== JSON.stringify(current.metadata ?? null)) {
|
|
4779
|
+
changes.push({
|
|
4780
|
+
kind: "changed",
|
|
4781
|
+
path: "metadata",
|
|
4782
|
+
from: current.metadata ?? null,
|
|
4783
|
+
to: spec.metadata ?? null
|
|
4784
|
+
});
|
|
4785
|
+
}
|
|
4381
4786
|
const specByKey = new Map(spec.variants.map((v) => [v.key, v]));
|
|
4382
4787
|
const curByKey = new Map(current.variants.map((v) => [v.key, v]));
|
|
4383
4788
|
for (const v of spec.variants) {
|
|
@@ -4408,7 +4813,28 @@ function compareVariant(spec, cur, prefix) {
|
|
|
4408
4813
|
out.push({ kind: "changed", path: `${prefix}.js`, from: cur.js ?? null, to: spec.js ?? null });
|
|
4409
4814
|
}
|
|
4410
4815
|
if ((spec.css ?? null) !== (cur.css ?? null)) {
|
|
4411
|
-
out.push({
|
|
4816
|
+
out.push({
|
|
4817
|
+
kind: "changed",
|
|
4818
|
+
path: `${prefix}.css`,
|
|
4819
|
+
from: cur.css ?? null,
|
|
4820
|
+
to: spec.css ?? null
|
|
4821
|
+
});
|
|
4822
|
+
}
|
|
4823
|
+
if (JSON.stringify(spec.domOps ?? null) !== JSON.stringify(cur.domOps ?? null)) {
|
|
4824
|
+
out.push({
|
|
4825
|
+
kind: "changed",
|
|
4826
|
+
path: `${prefix}.domOps`,
|
|
4827
|
+
from: cur.domOps ?? null,
|
|
4828
|
+
to: spec.domOps ?? null
|
|
4829
|
+
});
|
|
4830
|
+
}
|
|
4831
|
+
if ((spec.recipeSampleRate ?? null) !== (cur.recipeSampleRate ?? null)) {
|
|
4832
|
+
out.push({
|
|
4833
|
+
kind: "changed",
|
|
4834
|
+
path: `${prefix}.recipeSampleRate`,
|
|
4835
|
+
from: cur.recipeSampleRate ?? null,
|
|
4836
|
+
to: spec.recipeSampleRate ?? null
|
|
4837
|
+
});
|
|
4412
4838
|
}
|
|
4413
4839
|
if (JSON.stringify(spec.payload ?? null) !== JSON.stringify(cur.payload ?? null)) {
|
|
4414
4840
|
out.push({
|
|
@@ -4447,7 +4873,7 @@ function plan(args) {
|
|
|
4447
4873
|
if (d.breaking) {
|
|
4448
4874
|
blocked.push({
|
|
4449
4875
|
id: d.id,
|
|
4450
|
-
reason:
|
|
4876
|
+
reason: "Variant set changed after start; create a new experiment id instead."
|
|
4451
4877
|
});
|
|
4452
4878
|
continue;
|
|
4453
4879
|
}
|
|
@@ -4459,7 +4885,7 @@ function plan(args) {
|
|
|
4459
4885
|
if (!args.allowDeletes) {
|
|
4460
4886
|
blocked.push({
|
|
4461
4887
|
id: d.id,
|
|
4462
|
-
reason:
|
|
4888
|
+
reason: "Removed from YAML; pass --allow-deletes to kill in control plane."
|
|
4463
4889
|
});
|
|
4464
4890
|
continue;
|
|
4465
4891
|
}
|
|
@@ -4501,14 +4927,12 @@ function formatPlan(p) {
|
|
|
4501
4927
|
function renderDiff(d) {
|
|
4502
4928
|
if (d.kind === "noop") return [];
|
|
4503
4929
|
if (d.kind === "create") return [` + ${d.spec.id} ${d.spec.name} (create)`];
|
|
4504
|
-
if (d.kind === "delete")
|
|
4505
|
-
return [` - ${d.id} (in control plane but not in YAML; will kill)`];
|
|
4930
|
+
if (d.kind === "delete") return [` - ${d.id} (in control plane but not in YAML; will kill)`];
|
|
4506
4931
|
const out = [` ~ ${d.id} ${d.spec.name} (update${d.breaking ? " \u2014 BLOCKED" : ""})`];
|
|
4507
4932
|
for (const c of d.changes) {
|
|
4508
4933
|
if (c.kind === "added") out.push(` + ${c.path}: ${jsonish(c.value)}`);
|
|
4509
4934
|
else if (c.kind === "removed") out.push(` - ${c.path}: ${jsonish(c.value)}`);
|
|
4510
|
-
else
|
|
4511
|
-
out.push(` ~ ${c.path}: ${jsonish(c.from)} \u2192 ${jsonish(c.to)}`);
|
|
4935
|
+
else out.push(` ~ ${c.path}: ${jsonish(c.from)} \u2192 ${jsonish(c.to)}`);
|
|
4512
4936
|
}
|
|
4513
4937
|
return out;
|
|
4514
4938
|
}
|
|
@@ -4533,6 +4957,8 @@ var ManifestVariant = Variant.pick({
|
|
|
4533
4957
|
weight: true,
|
|
4534
4958
|
js: true,
|
|
4535
4959
|
css: true,
|
|
4960
|
+
domOps: true,
|
|
4961
|
+
recipeSampleRate: true,
|
|
4536
4962
|
payload: true
|
|
4537
4963
|
});
|
|
4538
4964
|
var ManifestExperiment = external_exports.object({
|
|
@@ -4547,7 +4973,25 @@ var ManifestExperiment = external_exports.object({
|
|
|
4547
4973
|
/** Killed-or-paused short-circuit: when true, SDK must NOT execute variant code. */
|
|
4548
4974
|
applyVariants: external_exports.boolean(),
|
|
4549
4975
|
/** Optional default variant to return when paused. */
|
|
4550
|
-
defaultVariantKey: VariantKey.optional()
|
|
4976
|
+
defaultVariantKey: VariantKey.optional(),
|
|
4977
|
+
/** Activation trigger; absent means `auto`. */
|
|
4978
|
+
trigger: Trigger.optional(),
|
|
4979
|
+
/** Defer exposure until host calls `client.expose(id)`. */
|
|
4980
|
+
manualExposure: external_exports.boolean().optional(),
|
|
4981
|
+
/** Route all eligible traffic to a single variant key. */
|
|
4982
|
+
divertTo: VariantKey.optional(),
|
|
4983
|
+
/** Shared JS that runs once before any variant code. */
|
|
4984
|
+
sharedJs: external_exports.string().optional(),
|
|
4985
|
+
/** Shared CSS injected once before any variant CSS. */
|
|
4986
|
+
sharedCss: external_exports.string().optional(),
|
|
4987
|
+
/** Per-experiment metadata accessible via `client.metadata(id)`. */
|
|
4988
|
+
metadata: external_exports.record(external_exports.unknown()).optional(),
|
|
4989
|
+
/**
|
|
4990
|
+
* Targeting rule (JSONLogic-style AST) evaluated against `targetingContext`
|
|
4991
|
+
* by the SDK. When false, the subject is ineligible — `treatment()` returns
|
|
4992
|
+
* null and no exposure is recorded.
|
|
4993
|
+
*/
|
|
4994
|
+
targetingRule: external_exports.unknown().optional()
|
|
4551
4995
|
});
|
|
4552
4996
|
var ManifestSignature = external_exports.object({
|
|
4553
4997
|
keyId: external_exports.string().min(1).max(128),
|
|
@@ -4610,7 +5054,7 @@ function buildManifest(args) {
|
|
|
4610
5054
|
return Manifest.parse(manifest);
|
|
4611
5055
|
}
|
|
4612
5056
|
function toManifestExperiment(e) {
|
|
4613
|
-
|
|
5057
|
+
const out = {
|
|
4614
5058
|
id: e.id,
|
|
4615
5059
|
name: e.name,
|
|
4616
5060
|
state: e.state === "running" ? "running" : "paused",
|
|
@@ -4622,11 +5066,21 @@ function toManifestExperiment(e) {
|
|
|
4622
5066
|
weight: v.weight,
|
|
4623
5067
|
js: v.js,
|
|
4624
5068
|
css: v.css,
|
|
5069
|
+
domOps: v.domOps,
|
|
5070
|
+
recipeSampleRate: v.recipeSampleRate,
|
|
4625
5071
|
payload: v.payload
|
|
4626
5072
|
})),
|
|
4627
5073
|
applyVariants: e.state === "running",
|
|
4628
5074
|
defaultVariantKey: e.variants[0]?.key
|
|
4629
5075
|
};
|
|
5076
|
+
if (e.trigger) out.trigger = e.trigger;
|
|
5077
|
+
if (e.manualExposure) out.manualExposure = true;
|
|
5078
|
+
if (e.divertTo) out.divertTo = e.divertTo;
|
|
5079
|
+
if (e.sharedJs) out.sharedJs = e.sharedJs;
|
|
5080
|
+
if (e.sharedCss) out.sharedCss = e.sharedCss;
|
|
5081
|
+
if (e.metadata) out.metadata = e.metadata;
|
|
5082
|
+
if (e.audience.rule !== void 0) out.targetingRule = e.audience.rule;
|
|
5083
|
+
return out;
|
|
4630
5084
|
}
|
|
4631
5085
|
|
|
4632
5086
|
// ../module/dist/index.js
|
|
@@ -4639,9 +5093,22 @@ var FileStore = class {
|
|
|
4639
5093
|
const fs = await import('fs/promises');
|
|
4640
5094
|
try {
|
|
4641
5095
|
const text = await fs.readFile(this.path, "utf8");
|
|
4642
|
-
|
|
5096
|
+
const parsed = JSON.parse(text);
|
|
5097
|
+
return {
|
|
5098
|
+
experiments: parsed.experiments ?? {},
|
|
5099
|
+
events: parsed.events ?? [],
|
|
5100
|
+
manifestVersions: parsed.manifestVersions ?? {},
|
|
5101
|
+
resources: parsed.resources ?? {},
|
|
5102
|
+
resourceVersions: parsed.resourceVersions ?? {}
|
|
5103
|
+
};
|
|
4643
5104
|
} catch {
|
|
4644
|
-
return {
|
|
5105
|
+
return {
|
|
5106
|
+
experiments: {},
|
|
5107
|
+
events: [],
|
|
5108
|
+
manifestVersions: {},
|
|
5109
|
+
resources: {},
|
|
5110
|
+
resourceVersions: {}
|
|
5111
|
+
};
|
|
4645
5112
|
}
|
|
4646
5113
|
}
|
|
4647
5114
|
async save(state) {
|
|
@@ -4685,7 +5152,192 @@ var FileStore = class {
|
|
|
4685
5152
|
await this.save(s);
|
|
4686
5153
|
return v;
|
|
4687
5154
|
}
|
|
5155
|
+
async getResource(tenantId, kind, id) {
|
|
5156
|
+
const s = await this.load();
|
|
5157
|
+
return s.resources[`${tenantId}/${kind}/${id}`] ?? null;
|
|
5158
|
+
}
|
|
5159
|
+
async listResources(tenantId, kind) {
|
|
5160
|
+
const s = await this.load();
|
|
5161
|
+
return Object.values(s.resources).filter(
|
|
5162
|
+
(resource) => resource.tenantId === tenantId && resource.kind === kind
|
|
5163
|
+
);
|
|
5164
|
+
}
|
|
5165
|
+
async putResource(resource) {
|
|
5166
|
+
const s = await this.load();
|
|
5167
|
+
s.resources[`${resource.tenantId}/${resource.kind}/${resource.id}`] = resource;
|
|
5168
|
+
await this.save(s);
|
|
5169
|
+
}
|
|
5170
|
+
async nextResourceVersion(tenantId, scope) {
|
|
5171
|
+
const s = await this.load();
|
|
5172
|
+
const key = `${tenantId}/${scope}`;
|
|
5173
|
+
const version = (s.resourceVersions[key] ?? 0) + 1;
|
|
5174
|
+
s.resourceVersions[key] = version;
|
|
5175
|
+
await this.save(s);
|
|
5176
|
+
return version;
|
|
5177
|
+
}
|
|
5178
|
+
};
|
|
5179
|
+
var experimentStateMachine = {
|
|
5180
|
+
transitions: [
|
|
5181
|
+
{ from: "draft", to: "review", causedByAction: "experiment.submit_for_review" },
|
|
5182
|
+
{ from: "review", to: "approved", causedByAction: "experiment.approve" },
|
|
5183
|
+
{ from: "approved", to: "running", causedByAction: "experiment.start" },
|
|
5184
|
+
{ from: "running", to: "paused", causedByAction: "experiment.pause" },
|
|
5185
|
+
{ from: "paused", to: "running", causedByAction: "experiment.resume" },
|
|
5186
|
+
{ from: "running", to: "killed", causedByAction: "experiment.kill" },
|
|
5187
|
+
{ from: "paused", to: "killed", causedByAction: "experiment.kill" },
|
|
5188
|
+
{ from: "running", to: "concluded", causedByAction: "experiment.declare_winner" }
|
|
5189
|
+
]
|
|
5190
|
+
};
|
|
5191
|
+
var separationOfDuties = {
|
|
5192
|
+
policyId: "experiment.separation_of_duties.v1",
|
|
5193
|
+
version: 1,
|
|
5194
|
+
kind: "code",
|
|
5195
|
+
previewSafe: true,
|
|
5196
|
+
async evaluate(ctx) {
|
|
5197
|
+
const params = actionParams(ctx);
|
|
5198
|
+
const experiment = await findExperiment(ctx, params);
|
|
5199
|
+
const blocked = Boolean(
|
|
5200
|
+
experiment && typeof params.approverId === "string" && experiment.ownerId === params.approverId
|
|
5201
|
+
);
|
|
5202
|
+
return outcome(this, blocked, "The experiment owner cannot approve their own experiment.");
|
|
5203
|
+
}
|
|
5204
|
+
};
|
|
5205
|
+
var approvedToStart = {
|
|
5206
|
+
policyId: "experiment.approved_to_start.v1",
|
|
5207
|
+
version: 1,
|
|
5208
|
+
kind: "code",
|
|
5209
|
+
previewSafe: true,
|
|
5210
|
+
async evaluate(ctx) {
|
|
5211
|
+
const experiment = await findExperiment(ctx, actionParams(ctx));
|
|
5212
|
+
return outcome(
|
|
5213
|
+
this,
|
|
5214
|
+
Boolean(experiment && !experiment.approval),
|
|
5215
|
+
"An approval is required before start."
|
|
5216
|
+
);
|
|
5217
|
+
}
|
|
4688
5218
|
};
|
|
5219
|
+
var variantSetFrozen = {
|
|
5220
|
+
policyId: "experiment.freeze_variant_set.v1",
|
|
5221
|
+
version: 1,
|
|
5222
|
+
kind: "code",
|
|
5223
|
+
previewSafe: true,
|
|
5224
|
+
async evaluate(ctx) {
|
|
5225
|
+
const params = actionParams(ctx);
|
|
5226
|
+
const experiment = await findExperiment(ctx, params);
|
|
5227
|
+
const variants = isRecord(params.spec) && Array.isArray(params.spec.variants) ? params.spec.variants : [];
|
|
5228
|
+
if (!experiment || !["running", "paused", "concluded"].includes(experiment.state)) {
|
|
5229
|
+
return outcome(this, false, "Variant identities are mutable before the experiment starts.");
|
|
5230
|
+
}
|
|
5231
|
+
const current = new Set(experiment.variants.map((variant) => variant.key));
|
|
5232
|
+
const next = new Set(
|
|
5233
|
+
variants.filter(isRecord).map((variant) => variant.key).filter((key) => typeof key === "string")
|
|
5234
|
+
);
|
|
5235
|
+
const changed = current.size !== next.size || [...current].some((variantKey) => !next.has(variantKey));
|
|
5236
|
+
return outcome(this, changed, "Variant set cannot change after start or exposure begins.");
|
|
5237
|
+
}
|
|
5238
|
+
};
|
|
5239
|
+
var experimentPolicies = [separationOfDuties, approvedToStart, variantSetFrozen];
|
|
5240
|
+
var policiesById = new Map(experimentPolicies.map((policy) => [policy.policyId, policy]));
|
|
5241
|
+
async function executeGovernedExperimentAction(definition, parameters, ctx) {
|
|
5242
|
+
const policyOutcomes = [];
|
|
5243
|
+
for (const policyId of definition.policies ?? []) {
|
|
5244
|
+
const policy = policiesById.get(policyId);
|
|
5245
|
+
if (!policy) {
|
|
5246
|
+
return { success: false, error: `Required policy is not registered: ${policyId}` };
|
|
5247
|
+
}
|
|
5248
|
+
policyOutcomes.push(
|
|
5249
|
+
await policy.evaluate({
|
|
5250
|
+
tenantId: ctx.tenantId,
|
|
5251
|
+
spaceId: ctx.spaceId,
|
|
5252
|
+
actionInvocationId: ctx.actionInvocationId,
|
|
5253
|
+
actionId: definition.actionId,
|
|
5254
|
+
parameters,
|
|
5255
|
+
db: ctx.db,
|
|
5256
|
+
services: ctx.services,
|
|
5257
|
+
mode: "execute"
|
|
5258
|
+
})
|
|
5259
|
+
);
|
|
5260
|
+
}
|
|
5261
|
+
if (policyOutcomes.length > 0) {
|
|
5262
|
+
await appendGovernanceEvent(ctx, parameters, "policy.evaluated", {
|
|
5263
|
+
actionId: definition.actionId,
|
|
5264
|
+
outcomes: policyOutcomes
|
|
5265
|
+
});
|
|
5266
|
+
const blocked = policyOutcomes.find((policy) => policy.result === "block");
|
|
5267
|
+
if (blocked) {
|
|
5268
|
+
return {
|
|
5269
|
+
success: false,
|
|
5270
|
+
error: `Policy ${blocked.policyId} blocked ${definition.actionId}: ${blocked.reason ?? "denied"}`
|
|
5271
|
+
};
|
|
5272
|
+
}
|
|
5273
|
+
}
|
|
5274
|
+
if (definition.stateMachine) {
|
|
5275
|
+
const transitionError = await validateCurrentTransition(definition, parameters, ctx);
|
|
5276
|
+
if (transitionError) {
|
|
5277
|
+
await appendGovernanceEvent(ctx, parameters, "state_transition.rejected", {
|
|
5278
|
+
actionId: definition.actionId,
|
|
5279
|
+
error: transitionError
|
|
5280
|
+
});
|
|
5281
|
+
return { success: false, error: transitionError };
|
|
5282
|
+
}
|
|
5283
|
+
}
|
|
5284
|
+
if (!definition.handler) {
|
|
5285
|
+
return { success: false, error: `Action ${definition.actionId} has no handler` };
|
|
5286
|
+
}
|
|
5287
|
+
return definition.handler(ctx, parameters);
|
|
5288
|
+
}
|
|
5289
|
+
async function validateCurrentTransition(definition, parameters, ctx) {
|
|
5290
|
+
const binding = definition.stateMachine;
|
|
5291
|
+
if (!binding) return null;
|
|
5292
|
+
const entityId = binding.getEntityId(parameters);
|
|
5293
|
+
if (!entityId) return `Action ${definition.actionId} did not identify an experiment`;
|
|
5294
|
+
const params = actionParams({ parameters });
|
|
5295
|
+
const tenantId = typeof params.tenantId === "string" ? params.tenantId : ctx.tenantId;
|
|
5296
|
+
const experiment = await ctx.db.store.getExperiment(tenantId, entityId);
|
|
5297
|
+
if (!experiment) return null;
|
|
5298
|
+
const target = typeof binding.targetState === "function" ? binding.targetState(parameters) : binding.targetState;
|
|
5299
|
+
const valid = experimentStateMachine.transitions.some(
|
|
5300
|
+
(transition2) => transition2.from === experiment.state && transition2.to === target && transition2.causedByAction === definition.actionId
|
|
5301
|
+
);
|
|
5302
|
+
return valid ? null : `Transition from "${experiment.state}" to "${target}" via action "${definition.actionId}" is not defined for Experiment.`;
|
|
5303
|
+
}
|
|
5304
|
+
async function findExperiment(ctx, params) {
|
|
5305
|
+
if (typeof params.experimentId !== "string") return null;
|
|
5306
|
+
const tenantId = typeof params.tenantId === "string" ? params.tenantId : ctx.tenantId;
|
|
5307
|
+
return ctx.db.store.getExperiment(tenantId, params.experimentId);
|
|
5308
|
+
}
|
|
5309
|
+
function actionParams(ctx) {
|
|
5310
|
+
return isRecord(ctx.parameters) ? ctx.parameters : {};
|
|
5311
|
+
}
|
|
5312
|
+
function outcome(policy, blocked, reason) {
|
|
5313
|
+
return {
|
|
5314
|
+
policyId: policy.policyId,
|
|
5315
|
+
policyVersion: policy.version,
|
|
5316
|
+
policyKind: "code",
|
|
5317
|
+
result: blocked ? "block" : "pass",
|
|
5318
|
+
reason
|
|
5319
|
+
};
|
|
5320
|
+
}
|
|
5321
|
+
async function appendGovernanceEvent(ctx, parameters, type, payload) {
|
|
5322
|
+
const params = isRecord(parameters) ? parameters : {};
|
|
5323
|
+
await ctx.db.store.appendEvent({
|
|
5324
|
+
id: crypto$1.randomUUID(),
|
|
5325
|
+
type,
|
|
5326
|
+
tenantId: typeof params.tenantId === "string" ? params.tenantId : ctx.tenantId,
|
|
5327
|
+
experimentId: typeof params.experimentId === "string" ? params.experimentId : "*",
|
|
5328
|
+
actorId: ctx.actorId,
|
|
5329
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5330
|
+
payload: {
|
|
5331
|
+
actionInvocationId: ctx.actionInvocationId,
|
|
5332
|
+
correlationId: ctx.correlationId,
|
|
5333
|
+
actorType: ctx.actorType,
|
|
5334
|
+
...payload
|
|
5335
|
+
}
|
|
5336
|
+
});
|
|
5337
|
+
}
|
|
5338
|
+
function isRecord(value) {
|
|
5339
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
5340
|
+
}
|
|
4689
5341
|
var Invoker = class {
|
|
4690
5342
|
constructor(services) {
|
|
4691
5343
|
this.services = services;
|
|
@@ -4724,17 +5376,198 @@ var Invoker = class {
|
|
|
4724
5376
|
correlationId: options.correlationId ?? (this.services.uuid ?? crypto$1.randomUUID)(),
|
|
4725
5377
|
db: this.services
|
|
4726
5378
|
};
|
|
4727
|
-
if (!def.handler) {
|
|
4728
|
-
return { success: false, error: `Action ${actionId} has no handler` };
|
|
4729
|
-
}
|
|
4730
5379
|
try {
|
|
4731
|
-
return await def
|
|
5380
|
+
return await executeGovernedExperimentAction(def, parsed.data, ctx);
|
|
4732
5381
|
} catch (e) {
|
|
4733
5382
|
const err = e;
|
|
4734
5383
|
return { success: false, error: err.message ?? String(e) };
|
|
4735
5384
|
}
|
|
4736
5385
|
}
|
|
4737
5386
|
};
|
|
5387
|
+
function requireResourceStore(store) {
|
|
5388
|
+
if (!store.getResource || !store.listResources || !store.putResource) {
|
|
5389
|
+
throw new Error("Control-plane store does not support workspace resources");
|
|
5390
|
+
}
|
|
5391
|
+
return {
|
|
5392
|
+
get: store.getResource.bind(store),
|
|
5393
|
+
list: store.listResources.bind(store),
|
|
5394
|
+
put: store.putResource.bind(store),
|
|
5395
|
+
nextVersion: store.nextResourceVersion?.bind(store)
|
|
5396
|
+
};
|
|
5397
|
+
}
|
|
5398
|
+
var upsertWorkspaceResource = {
|
|
5399
|
+
actionId: "experiment.workspace_resource_upsert",
|
|
5400
|
+
namespace: "experiment",
|
|
5401
|
+
version: 1,
|
|
5402
|
+
schema: UpsertWorkspaceResourceInput,
|
|
5403
|
+
emitsEvents: ["workspace_resource.upserted"],
|
|
5404
|
+
idempotent: true,
|
|
5405
|
+
mutatesDomain: true,
|
|
5406
|
+
async handler(ctx, params) {
|
|
5407
|
+
const input = UpsertWorkspaceResourceInput.parse(params);
|
|
5408
|
+
const resource = WorkspaceResource.parse({ ...input.resource, tenantId: input.tenantId });
|
|
5409
|
+
const store = requireResourceStore(ctx.db.store);
|
|
5410
|
+
await store.put(resource);
|
|
5411
|
+
await ctx.db.store.appendEvent({
|
|
5412
|
+
id: crypto$1.randomUUID(),
|
|
5413
|
+
type: "workspace_resource.upserted",
|
|
5414
|
+
tenantId: input.tenantId,
|
|
5415
|
+
experimentId: `workspace:${resource.kind}:${resource.id}`,
|
|
5416
|
+
actorId: ctx.actorId,
|
|
5417
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5418
|
+
payload: {
|
|
5419
|
+
actionInvocationId: ctx.actionInvocationId,
|
|
5420
|
+
correlationId: ctx.correlationId,
|
|
5421
|
+
actorType: ctx.actorType,
|
|
5422
|
+
resourceKind: resource.kind,
|
|
5423
|
+
resourceId: resource.id
|
|
5424
|
+
}
|
|
5425
|
+
});
|
|
5426
|
+
return { success: true, data: { resource } };
|
|
5427
|
+
}
|
|
5428
|
+
};
|
|
5429
|
+
var publishEnvironment = {
|
|
5430
|
+
actionId: "experiment.environment_publish",
|
|
5431
|
+
namespace: "experiment",
|
|
5432
|
+
version: 1,
|
|
5433
|
+
schema: PublishEnvironmentInput,
|
|
5434
|
+
emitsEvents: ["environment.published"],
|
|
5435
|
+
idempotent: false,
|
|
5436
|
+
mutatesDomain: true,
|
|
5437
|
+
async handler(ctx, params) {
|
|
5438
|
+
const input = PublishEnvironmentInput.parse(params);
|
|
5439
|
+
const store = requireResourceStore(ctx.db.store);
|
|
5440
|
+
if (!store.nextVersion)
|
|
5441
|
+
throw new Error("Control-plane store does not support resource versions");
|
|
5442
|
+
const environment = Environment.parse(
|
|
5443
|
+
await store.get(input.tenantId, "environment", input.environmentId)
|
|
5444
|
+
);
|
|
5445
|
+
const features = (await store.list(input.tenantId, "feature")).filter((resource) => resource.kind === "feature").filter((feature) => feature.projectId === environment.projectId && !feature.archived);
|
|
5446
|
+
const featureIds = new Set(features.map((feature) => feature.id));
|
|
5447
|
+
const rules = (await store.list(input.tenantId, "rule")).filter((resource) => resource.kind === "rule").filter(
|
|
5448
|
+
(rule) => rule.environmentId === environment.id && featureIds.has(rule.featureId) && rule.enabled
|
|
5449
|
+
).sort((a, b) => a.priority - b.priority || a.id.localeCompare(b.id));
|
|
5450
|
+
const snapshot = { features, rules };
|
|
5451
|
+
const resourceHash = crypto$1.createHash("sha256").update(stableJson(snapshot)).digest("hex");
|
|
5452
|
+
const version = await store.nextVersion(input.tenantId, `environment:${environment.id}`);
|
|
5453
|
+
const publication = {
|
|
5454
|
+
id: crypto$1.randomUUID(),
|
|
5455
|
+
kind: "publication",
|
|
5456
|
+
tenantId: input.tenantId,
|
|
5457
|
+
environmentId: environment.id,
|
|
5458
|
+
version,
|
|
5459
|
+
status: "published",
|
|
5460
|
+
resourceHash,
|
|
5461
|
+
manifestVersion: await ctx.db.store.currentManifestVersion(input.tenantId),
|
|
5462
|
+
publishedBy: input.publishedBy,
|
|
5463
|
+
publishedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5464
|
+
snapshot
|
|
5465
|
+
};
|
|
5466
|
+
await store.put(publication);
|
|
5467
|
+
await ctx.db.store.appendEvent({
|
|
5468
|
+
id: crypto$1.randomUUID(),
|
|
5469
|
+
type: "environment.published",
|
|
5470
|
+
tenantId: input.tenantId,
|
|
5471
|
+
experimentId: `workspace:environment:${environment.id}`,
|
|
5472
|
+
actorId: ctx.actorId,
|
|
5473
|
+
at: publication.publishedAt,
|
|
5474
|
+
payload: {
|
|
5475
|
+
actionInvocationId: ctx.actionInvocationId,
|
|
5476
|
+
correlationId: ctx.correlationId,
|
|
5477
|
+
actorType: ctx.actorType,
|
|
5478
|
+
environmentId: environment.id,
|
|
5479
|
+
version,
|
|
5480
|
+
resourceHash,
|
|
5481
|
+
featureCount: features.length,
|
|
5482
|
+
ruleCount: rules.length
|
|
5483
|
+
}
|
|
5484
|
+
});
|
|
5485
|
+
return { success: true, data: { publication } };
|
|
5486
|
+
}
|
|
5487
|
+
};
|
|
5488
|
+
var promoteEnvironment = {
|
|
5489
|
+
actionId: "experiment.environment_promote",
|
|
5490
|
+
namespace: "experiment",
|
|
5491
|
+
version: 1,
|
|
5492
|
+
schema: PromoteEnvironmentInput,
|
|
5493
|
+
emitsEvents: ["environment.promoted"],
|
|
5494
|
+
idempotent: false,
|
|
5495
|
+
mutatesDomain: true,
|
|
5496
|
+
async handler(ctx, params) {
|
|
5497
|
+
const input = PromoteEnvironmentInput.parse(params);
|
|
5498
|
+
const store = requireResourceStore(ctx.db.store);
|
|
5499
|
+
const source = Environment.parse(
|
|
5500
|
+
await store.get(input.tenantId, "environment", input.sourceEnvironmentId)
|
|
5501
|
+
);
|
|
5502
|
+
const target = Environment.parse(
|
|
5503
|
+
await store.get(input.tenantId, "environment", input.targetEnvironmentId)
|
|
5504
|
+
);
|
|
5505
|
+
if (source.projectId !== target.projectId) {
|
|
5506
|
+
throw new Error("Source and target environments must belong to the same project");
|
|
5507
|
+
}
|
|
5508
|
+
if (target.rank <= source.rank) {
|
|
5509
|
+
throw new Error("Promotions must move to a higher-ranked environment");
|
|
5510
|
+
}
|
|
5511
|
+
const publications = (await store.list(input.tenantId, "publication")).filter(
|
|
5512
|
+
(resource) => resource.kind === "publication" && resource.environmentId === source.id
|
|
5513
|
+
).sort((a, b) => b.version - a.version);
|
|
5514
|
+
const sourcePublication = publications[0];
|
|
5515
|
+
if (!sourcePublication) throw new Error("Source environment has no published version");
|
|
5516
|
+
const currentTargetRules = (await store.list(input.tenantId, "rule")).filter(
|
|
5517
|
+
(resource) => resource.kind === "rule" && resource.environmentId === target.id && resource.enabled
|
|
5518
|
+
);
|
|
5519
|
+
const at = (/* @__PURE__ */ new Date()).toISOString();
|
|
5520
|
+
for (const rule of currentTargetRules) {
|
|
5521
|
+
await store.put({ ...rule, enabled: false, updatedAt: at });
|
|
5522
|
+
}
|
|
5523
|
+
const promotedRules = sourcePublication.snapshot.rules.map((rule) => ({
|
|
5524
|
+
...rule,
|
|
5525
|
+
id: crypto$1.randomUUID(),
|
|
5526
|
+
environmentId: target.id,
|
|
5527
|
+
createdAt: at,
|
|
5528
|
+
updatedAt: at
|
|
5529
|
+
}));
|
|
5530
|
+
for (const rule of promotedRules) await store.put(rule);
|
|
5531
|
+
await ctx.db.store.appendEvent({
|
|
5532
|
+
id: crypto$1.randomUUID(),
|
|
5533
|
+
type: "environment.promoted",
|
|
5534
|
+
tenantId: input.tenantId,
|
|
5535
|
+
experimentId: `workspace:environment:${target.id}`,
|
|
5536
|
+
actorId: ctx.actorId,
|
|
5537
|
+
at,
|
|
5538
|
+
payload: {
|
|
5539
|
+
actionInvocationId: ctx.actionInvocationId,
|
|
5540
|
+
correlationId: ctx.correlationId,
|
|
5541
|
+
actorType: ctx.actorType,
|
|
5542
|
+
sourceEnvironmentId: source.id,
|
|
5543
|
+
sourceVersion: sourcePublication.version,
|
|
5544
|
+
targetEnvironmentId: target.id,
|
|
5545
|
+
promotedRuleCount: promotedRules.length
|
|
5546
|
+
}
|
|
5547
|
+
});
|
|
5548
|
+
return {
|
|
5549
|
+
success: true,
|
|
5550
|
+
data: {
|
|
5551
|
+
sourceEnvironmentId: source.id,
|
|
5552
|
+
sourceVersion: sourcePublication.version,
|
|
5553
|
+
targetEnvironmentId: target.id,
|
|
5554
|
+
promotedRuleCount: promotedRules.length
|
|
5555
|
+
}
|
|
5556
|
+
};
|
|
5557
|
+
}
|
|
5558
|
+
};
|
|
5559
|
+
function stableJson(value) {
|
|
5560
|
+
if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
|
|
5561
|
+
if (value && typeof value === "object") {
|
|
5562
|
+
return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, nested]) => `${JSON.stringify(key)}:${stableJson(nested)}`).join(",")}}`;
|
|
5563
|
+
}
|
|
5564
|
+
return JSON.stringify(value);
|
|
5565
|
+
}
|
|
5566
|
+
var workspaceActions = [
|
|
5567
|
+
upsertWorkspaceResource,
|
|
5568
|
+
publishEnvironment,
|
|
5569
|
+
promoteEnvironment
|
|
5570
|
+
];
|
|
4738
5571
|
var NAMESPACE = "experiment";
|
|
4739
5572
|
var VERSION = 1;
|
|
4740
5573
|
var now = () => (/* @__PURE__ */ new Date()).toISOString();
|
|
@@ -4781,6 +5614,10 @@ var createExperiment = {
|
|
|
4781
5614
|
});
|
|
4782
5615
|
}
|
|
4783
5616
|
const ts = now();
|
|
5617
|
+
const compiledSampleRate = input.sampleRate ?? (input.holdback !== void 0 ? 1 - input.holdback : void 0) ?? input.audience?.sampleRate ?? 1;
|
|
5618
|
+
if (input.divertTo && !input.variants.some((v) => v.key === input.divertTo)) {
|
|
5619
|
+
throw new ValidationFailed(`divertTo references unknown variant: ${input.divertTo}`);
|
|
5620
|
+
}
|
|
4784
5621
|
const experiment = {
|
|
4785
5622
|
id: input.id,
|
|
4786
5623
|
name: input.name,
|
|
@@ -4788,7 +5625,7 @@ var createExperiment = {
|
|
|
4788
5625
|
state: "draft",
|
|
4789
5626
|
salt: input.salt ?? input.id,
|
|
4790
5627
|
audience: {
|
|
4791
|
-
sampleRate:
|
|
5628
|
+
sampleRate: compiledSampleRate,
|
|
4792
5629
|
rule: input.audience?.rule
|
|
4793
5630
|
},
|
|
4794
5631
|
variants: input.variants,
|
|
@@ -4800,17 +5637,30 @@ var createExperiment = {
|
|
|
4800
5637
|
isPrimary: m.isPrimary ?? false,
|
|
4801
5638
|
isGuardrail: m.isGuardrail ?? false
|
|
4802
5639
|
})),
|
|
5640
|
+
trigger: input.trigger,
|
|
5641
|
+
manualExposure: input.manualExposure,
|
|
5642
|
+
divertTo: input.divertTo,
|
|
5643
|
+
sharedJs: input.sharedJs,
|
|
5644
|
+
sharedCss: input.sharedCss,
|
|
5645
|
+
metadata: input.metadata,
|
|
4803
5646
|
approval: null,
|
|
4804
5647
|
killReason: null,
|
|
4805
5648
|
ownerId: input.ownerId,
|
|
4806
5649
|
tenantId,
|
|
5650
|
+
projectId: input.projectId,
|
|
5651
|
+
propertyId: input.propertyId,
|
|
5652
|
+
featureId: input.featureId,
|
|
5653
|
+
environmentIds: input.environmentIds,
|
|
5654
|
+
workload: input.workload,
|
|
4807
5655
|
createdAt: ts,
|
|
4808
5656
|
updatedAt: ts,
|
|
4809
5657
|
startedAt: null,
|
|
4810
5658
|
endedAt: null
|
|
4811
5659
|
};
|
|
4812
5660
|
await store.putExperiment(experiment);
|
|
4813
|
-
await store.appendEvent(
|
|
5661
|
+
await store.appendEvent(
|
|
5662
|
+
event("experiment.created", experiment, ctx, { name: experiment.name })
|
|
5663
|
+
);
|
|
4814
5664
|
return { success: true, data: { experimentId: experiment.id } };
|
|
4815
5665
|
}
|
|
4816
5666
|
};
|
|
@@ -4823,6 +5673,14 @@ function lifecycle(actionId, schema, evt, fn, options = {}) {
|
|
|
4823
5673
|
emitsEvents: [evt],
|
|
4824
5674
|
idempotent: false,
|
|
4825
5675
|
mutatesDomain: true,
|
|
5676
|
+
...options.platformPolicies ? { policies: options.platformPolicies } : {},
|
|
5677
|
+
...options.targetState ? {
|
|
5678
|
+
stateMachine: {
|
|
5679
|
+
entityType: "Experiment",
|
|
5680
|
+
targetState: options.targetState,
|
|
5681
|
+
getEntityId: (params) => params.experimentId
|
|
5682
|
+
}
|
|
5683
|
+
} : {},
|
|
4826
5684
|
async handler(ctx, params) {
|
|
4827
5685
|
const p = params;
|
|
4828
5686
|
const store = ctx.db.store;
|
|
@@ -4842,7 +5700,8 @@ var submitForReview = lifecycle(
|
|
|
4842
5700
|
"experiment.submit_for_review",
|
|
4843
5701
|
SubmitForReviewInput,
|
|
4844
5702
|
"experiment.submitted_for_review",
|
|
4845
|
-
(e) => transition(e, "submitForReview")
|
|
5703
|
+
(e) => transition(e, "submitForReview"),
|
|
5704
|
+
{ targetState: "review" }
|
|
4846
5705
|
);
|
|
4847
5706
|
var approve = lifecycle(
|
|
4848
5707
|
"experiment.approve",
|
|
@@ -4857,6 +5716,8 @@ var approve = lifecycle(
|
|
|
4857
5716
|
}
|
|
4858
5717
|
}),
|
|
4859
5718
|
{
|
|
5719
|
+
targetState: "approved",
|
|
5720
|
+
platformPolicies: ["experiment.separation_of_duties.v1"],
|
|
4860
5721
|
policy(e, p) {
|
|
4861
5722
|
if (e.ownerId === p.approverId) {
|
|
4862
5723
|
throw new PolicyDenied("approver cannot be the experiment owner", {
|
|
@@ -4875,6 +5736,8 @@ var start = lifecycle(
|
|
|
4875
5736
|
startedAt: now()
|
|
4876
5737
|
}),
|
|
4877
5738
|
{
|
|
5739
|
+
targetState: "running",
|
|
5740
|
+
platformPolicies: ["experiment.approved_to_start.v1"],
|
|
4878
5741
|
policy(e) {
|
|
4879
5742
|
if (!e.approval) {
|
|
4880
5743
|
throw new PolicyDenied("experiment must be approved before starting");
|
|
@@ -4886,13 +5749,15 @@ var pauseAction = lifecycle(
|
|
|
4886
5749
|
"experiment.pause",
|
|
4887
5750
|
PauseInput,
|
|
4888
5751
|
"experiment.paused",
|
|
4889
|
-
(e) => transition(e, "pause")
|
|
5752
|
+
(e) => transition(e, "pause"),
|
|
5753
|
+
{ targetState: "paused" }
|
|
4890
5754
|
);
|
|
4891
5755
|
var resume = lifecycle(
|
|
4892
5756
|
"experiment.resume",
|
|
4893
5757
|
ResumeInput,
|
|
4894
5758
|
"experiment.resumed",
|
|
4895
|
-
(e) => transition(e, "resume")
|
|
5759
|
+
(e) => transition(e, "resume"),
|
|
5760
|
+
{ targetState: "running" }
|
|
4896
5761
|
);
|
|
4897
5762
|
var kill = lifecycle(
|
|
4898
5763
|
"experiment.kill",
|
|
@@ -4902,7 +5767,8 @@ var kill = lifecycle(
|
|
|
4902
5767
|
...transition(e, "kill"),
|
|
4903
5768
|
killReason: p.reason ?? "unspecified",
|
|
4904
5769
|
endedAt: now()
|
|
4905
|
-
})
|
|
5770
|
+
}),
|
|
5771
|
+
{ targetState: "killed" }
|
|
4906
5772
|
);
|
|
4907
5773
|
var declareWinner = lifecycle(
|
|
4908
5774
|
"experiment.declare_winner",
|
|
@@ -4913,7 +5779,8 @@ var declareWinner = lifecycle(
|
|
|
4913
5779
|
throw new ValidationFailed(`unknown winningVariant: ${p.winningVariant}`);
|
|
4914
5780
|
}
|
|
4915
5781
|
return { ...transition(e, "declareWinner"), endedAt: now() };
|
|
4916
|
-
}
|
|
5782
|
+
},
|
|
5783
|
+
{ targetState: "concluded" }
|
|
4917
5784
|
);
|
|
4918
5785
|
var update = {
|
|
4919
5786
|
actionId: "experiment.update",
|
|
@@ -4923,6 +5790,7 @@ var update = {
|
|
|
4923
5790
|
emitsEvents: ["experiment.updated", "experiment.metrics_updated", "experiment.variant_updated"],
|
|
4924
5791
|
idempotent: false,
|
|
4925
5792
|
mutatesDomain: true,
|
|
5793
|
+
policies: ["experiment.freeze_variant_set.v1"],
|
|
4926
5794
|
async handler(ctx, params) {
|
|
4927
5795
|
const p = params;
|
|
4928
5796
|
const store = ctx.db.store;
|
|
@@ -4939,15 +5807,30 @@ var update = {
|
|
|
4939
5807
|
);
|
|
4940
5808
|
}
|
|
4941
5809
|
}
|
|
5810
|
+
if (p.spec.divertTo && !p.spec.variants.some((v) => v.key === p.spec.divertTo)) {
|
|
5811
|
+
throw new ValidationFailed(`divertTo references unknown variant: ${p.spec.divertTo}`);
|
|
5812
|
+
}
|
|
5813
|
+
const compiledSampleRate = p.spec.sampleRate ?? (p.spec.holdback !== void 0 ? 1 - p.spec.holdback : void 0) ?? p.spec.audience?.sampleRate ?? e.audience.sampleRate;
|
|
4942
5814
|
const updated = {
|
|
4943
5815
|
...e,
|
|
4944
5816
|
name: p.spec.name,
|
|
4945
5817
|
description: p.spec.description,
|
|
5818
|
+
projectId: p.spec.projectId ?? e.projectId,
|
|
5819
|
+
propertyId: p.spec.propertyId ?? e.propertyId,
|
|
5820
|
+
featureId: p.spec.featureId ?? e.featureId,
|
|
5821
|
+
environmentIds: p.spec.environmentIds ?? e.environmentIds,
|
|
5822
|
+
workload: p.spec.workload ?? e.workload,
|
|
4946
5823
|
audience: {
|
|
4947
5824
|
...e.audience,
|
|
4948
|
-
sampleRate:
|
|
5825
|
+
sampleRate: compiledSampleRate
|
|
4949
5826
|
},
|
|
4950
5827
|
variants: p.spec.variants,
|
|
5828
|
+
trigger: p.spec.trigger ?? e.trigger,
|
|
5829
|
+
manualExposure: p.spec.manualExposure ?? e.manualExposure,
|
|
5830
|
+
divertTo: p.spec.divertTo ?? e.divertTo,
|
|
5831
|
+
sharedJs: p.spec.sharedJs ?? e.sharedJs,
|
|
5832
|
+
sharedCss: p.spec.sharedCss ?? e.sharedCss,
|
|
5833
|
+
metadata: p.spec.metadata ?? e.metadata,
|
|
4951
5834
|
metrics: (p.spec.metrics ?? e.metrics).map((m) => ({
|
|
4952
5835
|
key: m.key,
|
|
4953
5836
|
name: m.name,
|
|
@@ -5013,7 +5896,8 @@ var experimentActions = [
|
|
|
5013
5896
|
kill,
|
|
5014
5897
|
declareWinner,
|
|
5015
5898
|
update,
|
|
5016
|
-
guardrailBreach
|
|
5899
|
+
guardrailBreach,
|
|
5900
|
+
...workspaceActions
|
|
5017
5901
|
];
|
|
5018
5902
|
function createExperimentModule(args) {
|
|
5019
5903
|
const services = { store: args.store };
|
|
@@ -5063,6 +5947,126 @@ function cryptoUuid() {
|
|
|
5063
5947
|
}
|
|
5064
5948
|
|
|
5065
5949
|
// ../warehouse/dist/index.js
|
|
5950
|
+
function mean(values) {
|
|
5951
|
+
return values.length === 0 ? 0 : values.reduce((sum, value) => sum + value, 0) / values.length;
|
|
5952
|
+
}
|
|
5953
|
+
function variance(values) {
|
|
5954
|
+
if (values.length === 0) return 0;
|
|
5955
|
+
const average = mean(values);
|
|
5956
|
+
return mean(values.map((value) => (value - average) ** 2));
|
|
5957
|
+
}
|
|
5958
|
+
function covariance(left, right) {
|
|
5959
|
+
if (left.length === 0 || left.length !== right.length) return 0;
|
|
5960
|
+
const leftMean = mean(left);
|
|
5961
|
+
const rightMean = mean(right);
|
|
5962
|
+
return mean(left.map((value, index) => (value - leftMean) * ((right[index] ?? 0) - rightMean)));
|
|
5963
|
+
}
|
|
5964
|
+
function percentile(values, quantile) {
|
|
5965
|
+
if (values.length === 0) return null;
|
|
5966
|
+
const sorted = [...values].sort((left, right) => left - right);
|
|
5967
|
+
const index = (sorted.length - 1) * quantile;
|
|
5968
|
+
const lower = Math.floor(index);
|
|
5969
|
+
const upper = Math.ceil(index);
|
|
5970
|
+
if (lower === upper) return sorted[lower] ?? null;
|
|
5971
|
+
const fraction = index - lower;
|
|
5972
|
+
return (sorted[lower] ?? 0) * (1 - fraction) + (sorted[upper] ?? 0) * fraction;
|
|
5973
|
+
}
|
|
5974
|
+
function parseDimensions(value) {
|
|
5975
|
+
if (!value) return {};
|
|
5976
|
+
if (typeof value !== "string") return value;
|
|
5977
|
+
try {
|
|
5978
|
+
const parsed = JSON.parse(value);
|
|
5979
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
|
|
5980
|
+
return Object.fromEntries(
|
|
5981
|
+
Object.entries(parsed).filter(
|
|
5982
|
+
(entry) => typeof entry[1] === "string"
|
|
5983
|
+
)
|
|
5984
|
+
);
|
|
5985
|
+
} catch {
|
|
5986
|
+
return {};
|
|
5987
|
+
}
|
|
5988
|
+
}
|
|
5989
|
+
function buildExperimentAnalytics(subjects, query) {
|
|
5990
|
+
const prePeriodDays = query.prePeriodDays ?? 14;
|
|
5991
|
+
const outcomes = subjects.map((subject) => subject.conversionDepth > 0 ? 1 : 0);
|
|
5992
|
+
const covariates = subjects.map((subject) => subject.prePeriodDepth);
|
|
5993
|
+
const covariateVariance = variance(covariates);
|
|
5994
|
+
const theta = covariateVariance > 0 ? covariance(outcomes, covariates) / covariateVariance : 0;
|
|
5995
|
+
const covariateMean = mean(covariates);
|
|
5996
|
+
const adjusted = outcomes.map(
|
|
5997
|
+
(outcome2, index) => outcome2 - theta * ((covariates[index] ?? 0) - covariateMean)
|
|
5998
|
+
);
|
|
5999
|
+
const outcomeVariance = variance(outcomes);
|
|
6000
|
+
const adjustedVariance = variance(adjusted);
|
|
6001
|
+
const available = covariates.some((value) => value > 0) && covariateVariance > 0;
|
|
6002
|
+
const varianceReduction = available && outcomeVariance > 0 ? 1 - adjustedVariance / outcomeVariance : null;
|
|
6003
|
+
const variantKeys = [...new Set(subjects.map((subject) => subject.variantKey))].sort();
|
|
6004
|
+
const adjustedRate = /* @__PURE__ */ new Map();
|
|
6005
|
+
for (const variantKey of variantKeys) {
|
|
6006
|
+
const values = adjusted.filter((_, index) => subjects[index]?.variantKey === variantKey);
|
|
6007
|
+
adjustedRate.set(variantKey, mean(values));
|
|
6008
|
+
}
|
|
6009
|
+
const controlRate = adjustedRate.get(variantKeys[0] ?? "") ?? 0;
|
|
6010
|
+
const variants = variantKeys.map((variantKey) => {
|
|
6011
|
+
const cohort = subjects.filter((subject) => subject.variantKey === variantKey);
|
|
6012
|
+
const times = cohort.filter((subject) => subject.firstConversionAt).map(
|
|
6013
|
+
(subject) => new Date(subject.firstConversionAt).getTime() - new Date(subject.firstExposureAt).getTime()
|
|
6014
|
+
).filter((value) => Number.isFinite(value) && value >= 0);
|
|
6015
|
+
const rate = adjustedRate.get(variantKey) ?? 0;
|
|
6016
|
+
return {
|
|
6017
|
+
variantKey,
|
|
6018
|
+
exposedSubjects: cohort.length,
|
|
6019
|
+
convertedSubjects: cohort.filter((subject) => subject.conversionDepth > 0).length,
|
|
6020
|
+
meanTimeToConvertMs: times.length > 0 ? mean(times) : null,
|
|
6021
|
+
medianTimeToConvertMs: percentile(times, 0.5),
|
|
6022
|
+
p90TimeToConvertMs: percentile(times, 0.9),
|
|
6023
|
+
meanConversionDepth: mean(cohort.map((subject) => subject.conversionDepth)),
|
|
6024
|
+
conversionDepth: {
|
|
6025
|
+
oneOrMore: cohort.filter((subject) => subject.conversionDepth >= 1).length,
|
|
6026
|
+
twoOrMore: cohort.filter((subject) => subject.conversionDepth >= 2).length,
|
|
6027
|
+
threeOrMore: cohort.filter((subject) => subject.conversionDepth >= 3).length
|
|
6028
|
+
},
|
|
6029
|
+
cupedAdjustedRate: available ? rate : null,
|
|
6030
|
+
cupedLift: available && variantKey !== variantKeys[0] ? rate - controlRate : null
|
|
6031
|
+
};
|
|
6032
|
+
});
|
|
6033
|
+
const segments = [];
|
|
6034
|
+
if (query.segmentKey) {
|
|
6035
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
6036
|
+
for (const subject of subjects) {
|
|
6037
|
+
const segmentValue = parseDimensions(subject.dimensions)[query.segmentKey] ?? "(unknown)";
|
|
6038
|
+
const key = `${segmentValue}\0${subject.variantKey}`;
|
|
6039
|
+
const rows = grouped.get(key) ?? [];
|
|
6040
|
+
rows.push(subject);
|
|
6041
|
+
grouped.set(key, rows);
|
|
6042
|
+
}
|
|
6043
|
+
for (const [key, cohort] of grouped) {
|
|
6044
|
+
const [segmentValue = "(unknown)", variantKey = ""] = key.split("\0");
|
|
6045
|
+
const conversionCount = cohort.filter((subject) => subject.conversionDepth > 0).length;
|
|
6046
|
+
segments.push({
|
|
6047
|
+
segmentValue,
|
|
6048
|
+
variantKey,
|
|
6049
|
+
exposureCount: cohort.length,
|
|
6050
|
+
conversionCount,
|
|
6051
|
+
conversionRate: cohort.length === 0 ? 0 : conversionCount / cohort.length
|
|
6052
|
+
});
|
|
6053
|
+
}
|
|
6054
|
+
segments.sort(
|
|
6055
|
+
(left, right) => left.segmentValue.localeCompare(right.segmentValue) || left.variantKey.localeCompare(right.variantKey)
|
|
6056
|
+
);
|
|
6057
|
+
}
|
|
6058
|
+
return {
|
|
6059
|
+
variants,
|
|
6060
|
+
segments,
|
|
6061
|
+
...query.segmentKey ? { segmentKey: query.segmentKey } : {},
|
|
6062
|
+
cuped: {
|
|
6063
|
+
available,
|
|
6064
|
+
prePeriodDays,
|
|
6065
|
+
theta: available ? theta : null,
|
|
6066
|
+
varianceReduction
|
|
6067
|
+
}
|
|
6068
|
+
};
|
|
6069
|
+
}
|
|
5066
6070
|
var LocalWarehouse = class {
|
|
5067
6071
|
constructor(dir) {
|
|
5068
6072
|
this.dir = dir;
|
|
@@ -5146,8 +6150,48 @@ var LocalWarehouse = class {
|
|
|
5146
6150
|
rows.sort((a, b) => a.variantKey.localeCompare(b.variantKey));
|
|
5147
6151
|
return rows;
|
|
5148
6152
|
}
|
|
6153
|
+
async analyze(query) {
|
|
6154
|
+
const exposures = this.firstExposures(query);
|
|
6155
|
+
const prePeriodMs = (query.prePeriodDays ?? 14) * 864e5;
|
|
6156
|
+
return buildExperimentAnalytics(
|
|
6157
|
+
[...exposures.values()].map((exposure) => {
|
|
6158
|
+
const firstAt = new Date(exposure.at).getTime();
|
|
6159
|
+
const matching = this.state.conversions.filter(
|
|
6160
|
+
(conversion) => conversion.tenantId === query.tenantId && conversion.subjectId === exposure.subjectId && conversion.eventName === query.metricEventName
|
|
6161
|
+
).sort((left, right) => left.at.localeCompare(right.at));
|
|
6162
|
+
const post = matching.filter(
|
|
6163
|
+
(conversion) => conversion.at >= exposure.at && (!query.untilIso || conversion.at < query.untilIso)
|
|
6164
|
+
);
|
|
6165
|
+
const pre = matching.filter((conversion) => {
|
|
6166
|
+
const timestamp = new Date(conversion.at).getTime();
|
|
6167
|
+
return timestamp < firstAt && timestamp >= firstAt - prePeriodMs;
|
|
6168
|
+
});
|
|
6169
|
+
return {
|
|
6170
|
+
subjectId: exposure.subjectId,
|
|
6171
|
+
variantKey: exposure.variantKey,
|
|
6172
|
+
firstExposureAt: exposure.at,
|
|
6173
|
+
firstConversionAt: post[0]?.at,
|
|
6174
|
+
conversionDepth: post.length,
|
|
6175
|
+
prePeriodDepth: pre.length,
|
|
6176
|
+
dimensions: exposure.dimensions
|
|
6177
|
+
};
|
|
6178
|
+
}),
|
|
6179
|
+
query
|
|
6180
|
+
);
|
|
6181
|
+
}
|
|
5149
6182
|
async close() {
|
|
5150
6183
|
}
|
|
6184
|
+
firstExposures(query) {
|
|
6185
|
+
const exposures = this.state.exposures.filter(
|
|
6186
|
+
(exposure) => exposure.tenantId === query.tenantId && exposure.experimentId === query.experimentId && (!query.fromIso || exposure.at >= query.fromIso) && (!query.untilIso || exposure.at < query.untilIso)
|
|
6187
|
+
);
|
|
6188
|
+
const first = /* @__PURE__ */ new Map();
|
|
6189
|
+
for (const exposure of exposures) {
|
|
6190
|
+
const prior = first.get(exposure.subjectId);
|
|
6191
|
+
if (!prior || exposure.at < prior.at) first.set(exposure.subjectId, exposure);
|
|
6192
|
+
}
|
|
6193
|
+
return first;
|
|
6194
|
+
}
|
|
5151
6195
|
};
|
|
5152
6196
|
async function readNdjson(path) {
|
|
5153
6197
|
const fs = await import('fs/promises');
|
|
@@ -5209,9 +6253,7 @@ async function cmdApply(dir, options = {}) {
|
|
|
5209
6253
|
process.stdout.write(formatPlan(p));
|
|
5210
6254
|
process.stdout.write("\n");
|
|
5211
6255
|
if (p.blocked.length > 0) {
|
|
5212
|
-
process.stderr.write(
|
|
5213
|
-
Apply blocked. Resolve the issues above and re-run.
|
|
5214
|
-
`);
|
|
6256
|
+
process.stderr.write("\nApply blocked. Resolve the issues above and re-run.\n");
|
|
5215
6257
|
return 2;
|
|
5216
6258
|
}
|
|
5217
6259
|
if (options.dryRun || p.actions.length === 0) {
|
|
@@ -5239,11 +6281,11 @@ async function invokePlanned(ws, a, ownerId, approverId) {
|
|
|
5239
6281
|
);
|
|
5240
6282
|
}
|
|
5241
6283
|
if (a.actionId === "experiment.submit_for_review" || a.actionId === "experiment.start") {
|
|
5242
|
-
return ws.module.invoker.invoke(
|
|
5243
|
-
a.
|
|
5244
|
-
|
|
5245
|
-
|
|
5246
|
-
);
|
|
6284
|
+
return ws.module.invoker.invoke(a.actionId, a.params, {
|
|
6285
|
+
tenantId: a.params.tenantId,
|
|
6286
|
+
actorId: ownerId,
|
|
6287
|
+
actorType: "natural_person"
|
|
6288
|
+
});
|
|
5247
6289
|
}
|
|
5248
6290
|
if (a.actionId === "experiment.approve") {
|
|
5249
6291
|
return ws.module.invoker.invoke(
|
|
@@ -5253,17 +6295,17 @@ async function invokePlanned(ws, a, ownerId, approverId) {
|
|
|
5253
6295
|
);
|
|
5254
6296
|
}
|
|
5255
6297
|
if (a.actionId === "experiment.update") {
|
|
5256
|
-
return ws.module.invoker.invoke(
|
|
5257
|
-
|
|
5258
|
-
|
|
5259
|
-
|
|
5260
|
-
);
|
|
6298
|
+
return ws.module.invoker.invoke("experiment.update", a.params, {
|
|
6299
|
+
tenantId: a.params.tenantId,
|
|
6300
|
+
actorId: ownerId,
|
|
6301
|
+
actorType: "natural_person"
|
|
6302
|
+
});
|
|
5261
6303
|
}
|
|
5262
|
-
return ws.module.invoker.invoke(
|
|
5263
|
-
|
|
5264
|
-
|
|
5265
|
-
|
|
5266
|
-
);
|
|
6304
|
+
return ws.module.invoker.invoke("experiment.kill", a.params, {
|
|
6305
|
+
tenantId: a.params.tenantId,
|
|
6306
|
+
actorId: ownerId,
|
|
6307
|
+
actorType: "natural_person"
|
|
6308
|
+
});
|
|
5267
6309
|
}
|
|
5268
6310
|
function assertOk(label, result) {
|
|
5269
6311
|
if (!result.success) throw new Error(`${label}: ${result.error}`);
|
|
@@ -5288,8 +6330,8 @@ function twoSidedPFromZ(z) {
|
|
|
5288
6330
|
}
|
|
5289
6331
|
function probit(p) {
|
|
5290
6332
|
if (p <= 0 || p >= 1) {
|
|
5291
|
-
if (p === 0) return
|
|
5292
|
-
if (p === 1) return
|
|
6333
|
+
if (p === 0) return Number.NEGATIVE_INFINITY;
|
|
6334
|
+
if (p === 1) return Number.POSITIVE_INFINITY;
|
|
5293
6335
|
throw new Error(`probit: p out of range: ${p}`);
|
|
5294
6336
|
}
|
|
5295
6337
|
const a = [
|
|
@@ -5315,12 +6357,7 @@ function probit(p) {
|
|
|
5315
6357
|
4.374664141464968,
|
|
5316
6358
|
2.938163982698783
|
|
5317
6359
|
];
|
|
5318
|
-
const d = [
|
|
5319
|
-
0.007784695709041462,
|
|
5320
|
-
0.3224671290700398,
|
|
5321
|
-
2.445134137142996,
|
|
5322
|
-
3.754408661907416
|
|
5323
|
-
];
|
|
6360
|
+
const d = [0.007784695709041462, 0.3224671290700398, 2.445134137142996, 3.754408661907416];
|
|
5324
6361
|
const pLow = 0.02425;
|
|
5325
6362
|
const pHigh = 1 - pLow;
|
|
5326
6363
|
let q;
|
|
@@ -5371,14 +6408,10 @@ function twoProportionZ(control, treatment, level = 0.95) {
|
|
|
5371
6408
|
const p1 = control.successes / control.trials;
|
|
5372
6409
|
const p2 = treatment.successes / treatment.trials;
|
|
5373
6410
|
const pPooled = (control.successes + treatment.successes) / (control.trials + treatment.trials);
|
|
5374
|
-
const seZ = Math.sqrt(
|
|
5375
|
-
pPooled * (1 - pPooled) * (1 / control.trials + 1 / treatment.trials)
|
|
5376
|
-
);
|
|
6411
|
+
const seZ = Math.sqrt(pPooled * (1 - pPooled) * (1 / control.trials + 1 / treatment.trials));
|
|
5377
6412
|
const z = seZ === 0 ? 0 : (p2 - p1) / seZ;
|
|
5378
6413
|
const pValue = twoSidedPFromZ(z);
|
|
5379
|
-
const seCi = Math.sqrt(
|
|
5380
|
-
p1 * (1 - p1) / control.trials + p2 * (1 - p2) / treatment.trials
|
|
5381
|
-
);
|
|
6414
|
+
const seCi = Math.sqrt(p1 * (1 - p1) / control.trials + p2 * (1 - p2) / treatment.trials);
|
|
5382
6415
|
const zs = zStar(level);
|
|
5383
6416
|
const lift = p2 - p1;
|
|
5384
6417
|
return {
|
|
@@ -5476,11 +6509,11 @@ function lnGamma(z) {
|
|
|
5476
6509
|
if (z < 0.5) {
|
|
5477
6510
|
return Math.log(Math.PI / Math.sin(Math.PI * z)) - lnGamma(1 - z);
|
|
5478
6511
|
}
|
|
5479
|
-
z
|
|
6512
|
+
const zz = z - 1;
|
|
5480
6513
|
let x = c[0];
|
|
5481
|
-
for (let i = 1; i < g + 2; i++) x += c[i] / (
|
|
5482
|
-
const t =
|
|
5483
|
-
return 0.5 * Math.log(2 * Math.PI) + (
|
|
6514
|
+
for (let i = 1; i < g + 2; i++) x += c[i] / (zz + i);
|
|
6515
|
+
const t = zz + g + 0.5;
|
|
6516
|
+
return 0.5 * Math.log(2 * Math.PI) + (zz + 0.5) * Math.log(t) - t + Math.log(x);
|
|
5484
6517
|
}
|
|
5485
6518
|
function buildReport(args) {
|
|
5486
6519
|
const level = args.level ?? 0.95;
|
|
@@ -5508,9 +6541,7 @@ function buildReport(args) {
|
|
|
5508
6541
|
});
|
|
5509
6542
|
const totalExposures = args.rows.reduce((s, r) => s + r.exposureCount, 0);
|
|
5510
6543
|
const totalConversions = args.rows.reduce((s, r) => s + r.conversionCount, 0);
|
|
5511
|
-
const expected = args.rows.map(
|
|
5512
|
-
(r) => args.expectedSplit?.[r.variantKey] ?? 1 / args.rows.length
|
|
5513
|
-
);
|
|
6544
|
+
const expected = args.rows.map((r) => args.expectedSplit?.[r.variantKey] ?? 1 / args.rows.length);
|
|
5514
6545
|
const sumExp = expected.reduce((a, b) => a + b, 0);
|
|
5515
6546
|
const normalizedExpected = expected.map((e) => e / sumExp);
|
|
5516
6547
|
const srm = srmChiSquare({
|
|
@@ -5593,7 +6624,8 @@ Experiment: ${exp.name} (${exp.id})
|
|
|
5593
6624
|
printTable(lines);
|
|
5594
6625
|
process.stdout.write(
|
|
5595
6626
|
`
|
|
5596
|
-
SRM \u03C7\xB2=${report.srm.chiSquare.toFixed(3)} df=${report.srm.degreesOfFreedom} p=${formatP(report.srm.pValue)}
|
|
6627
|
+
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" : ""}
|
|
6628
|
+
`
|
|
5597
6629
|
);
|
|
5598
6630
|
return 0;
|
|
5599
6631
|
}
|
|
@@ -5687,13 +6719,17 @@ async function cmdDev(options = {}) {
|
|
|
5687
6719
|
res.statusCode = 400;
|
|
5688
6720
|
res.setHeader("content-type", "application/json");
|
|
5689
6721
|
res.end(JSON.stringify({ error: "invalid exposure", issues: parsed.error.issues }));
|
|
5690
|
-
log(
|
|
6722
|
+
log(
|
|
6723
|
+
`POST /v1/exposure 400 invalid: ${parsed.error.issues.map((i) => i.path.join(".")).join(",")}`
|
|
6724
|
+
);
|
|
5691
6725
|
return;
|
|
5692
6726
|
}
|
|
5693
6727
|
await ws.warehouse.recordExposures([parsed.data]);
|
|
5694
6728
|
res.statusCode = 204;
|
|
5695
6729
|
res.end();
|
|
5696
|
-
log(
|
|
6730
|
+
log(
|
|
6731
|
+
`POST /v1/exposure ${parsed.data.experimentId} ${parsed.data.variantKey} ${parsed.data.subjectId}`
|
|
6732
|
+
);
|
|
5697
6733
|
return;
|
|
5698
6734
|
}
|
|
5699
6735
|
if (req.method === "POST" && url.pathname === "/v1/conversion") {
|
|
@@ -5707,7 +6743,9 @@ async function cmdDev(options = {}) {
|
|
|
5707
6743
|
res.statusCode = 400;
|
|
5708
6744
|
res.setHeader("content-type", "application/json");
|
|
5709
6745
|
res.end(JSON.stringify({ error: "invalid conversion", issues: parsed.error.issues }));
|
|
5710
|
-
log(
|
|
6746
|
+
log(
|
|
6747
|
+
`POST /v1/conversion 400 invalid: ${parsed.error.issues.map((i) => i.path.join(".")).join(",")}`
|
|
6748
|
+
);
|
|
5711
6749
|
return;
|
|
5712
6750
|
}
|
|
5713
6751
|
await ws.warehouse.recordConversions([parsed.data]);
|
|
@@ -5758,9 +6796,9 @@ To find the process on Linux/macOS:
|
|
|
5758
6796
|
throw e;
|
|
5759
6797
|
}
|
|
5760
6798
|
log(`fx dev \u2014 listening on http://127.0.0.1:${port}`);
|
|
5761
|
-
log(
|
|
5762
|
-
log(
|
|
5763
|
-
log(
|
|
6799
|
+
log(" GET /manifest");
|
|
6800
|
+
log(" POST /v1/exposure");
|
|
6801
|
+
log(" POST /v1/conversion");
|
|
5764
6802
|
log(` workspace=${ws.root}`);
|
|
5765
6803
|
await new Promise((resolveStop) => {
|
|
5766
6804
|
const stop = () => {
|
|
@@ -5851,8 +6889,8 @@ function hexEncode(bytes) {
|
|
|
5851
6889
|
}
|
|
5852
6890
|
async function getSubtle() {
|
|
5853
6891
|
if (typeof crypto !== "undefined" && crypto.subtle) return crypto.subtle;
|
|
5854
|
-
const { webcrypto } = await import('crypto');
|
|
5855
|
-
return
|
|
6892
|
+
const { webcrypto: webcrypto2 } = await import('crypto');
|
|
6893
|
+
return webcrypto2.subtle;
|
|
5856
6894
|
}
|
|
5857
6895
|
async function signManifest(manifest, key) {
|
|
5858
6896
|
const subtle = await getSubtle2();
|
|
@@ -5876,13 +6914,13 @@ async function signManifest(manifest, key) {
|
|
|
5876
6914
|
}
|
|
5877
6915
|
async function getSubtle2() {
|
|
5878
6916
|
if (typeof crypto !== "undefined" && crypto.subtle) return crypto.subtle;
|
|
5879
|
-
const { webcrypto } = await import('crypto');
|
|
5880
|
-
return
|
|
6917
|
+
const { webcrypto: webcrypto2 } = await import('crypto');
|
|
6918
|
+
return webcrypto2.subtle;
|
|
5881
6919
|
}
|
|
5882
6920
|
function hexDecode(hex) {
|
|
5883
6921
|
if (hex.length % 2 !== 0) throw new Error("hexDecode: odd length");
|
|
5884
6922
|
const out = new Uint8Array(hex.length / 2);
|
|
5885
|
-
for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
6923
|
+
for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
5886
6924
|
return out;
|
|
5887
6925
|
}
|
|
5888
6926
|
function ed25519PrivateKeyToPkcs8(seed) {
|
|
@@ -5927,8 +6965,8 @@ async function generateKeypair(keyId) {
|
|
|
5927
6965
|
}
|
|
5928
6966
|
async function getSubtle4() {
|
|
5929
6967
|
if (typeof crypto !== "undefined" && crypto.subtle) return crypto.subtle;
|
|
5930
|
-
const { webcrypto } = await import('crypto');
|
|
5931
|
-
return
|
|
6968
|
+
const { webcrypto: webcrypto2 } = await import('crypto');
|
|
6969
|
+
return webcrypto2.subtle;
|
|
5932
6970
|
}
|
|
5933
6971
|
|
|
5934
6972
|
// src/commands/publish.ts
|
|
@@ -5978,8 +7016,46 @@ async function cmdPublish(options = {}) {
|
|
|
5978
7016
|
process.stdout.write(`Published to ${options.remoteUrl}
|
|
5979
7017
|
`);
|
|
5980
7018
|
}
|
|
7019
|
+
if (options.staticDir) {
|
|
7020
|
+
const out = path.resolve(options.staticDir);
|
|
7021
|
+
await promises.mkdir(out, { recursive: true });
|
|
7022
|
+
await promises.writeFile(path.join(out, "manifest.json"), JSON.stringify(signed), "utf8");
|
|
7023
|
+
const tagLoader = await locateTagLoaderBundle();
|
|
7024
|
+
if (tagLoader) {
|
|
7025
|
+
await promises.copyFile(tagLoader.js, path.join(out, "experiments.tag.global.js"));
|
|
7026
|
+
if (tagLoader.map) {
|
|
7027
|
+
await promises.copyFile(tagLoader.map, path.join(out, "experiments.tag.global.js.map"));
|
|
7028
|
+
}
|
|
7029
|
+
process.stdout.write(
|
|
7030
|
+
`Static export written to ${out} (manifest.json + experiments.tag.global.js)
|
|
7031
|
+
`
|
|
7032
|
+
);
|
|
7033
|
+
} else {
|
|
7034
|
+
process.stderr.write(
|
|
7035
|
+
`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.
|
|
7036
|
+
`
|
|
7037
|
+
);
|
|
7038
|
+
}
|
|
7039
|
+
}
|
|
5981
7040
|
return 0;
|
|
5982
7041
|
}
|
|
7042
|
+
async function locateTagLoaderBundle() {
|
|
7043
|
+
const req = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('fx.cjs', document.baseURI).href)));
|
|
7044
|
+
try {
|
|
7045
|
+
const js = req.resolve("@fabricorg/experiments-web/tag-loader");
|
|
7046
|
+
await promises.stat(js);
|
|
7047
|
+
let map = null;
|
|
7048
|
+
try {
|
|
7049
|
+
const m = req.resolve("@fabricorg/experiments-web/tag-loader.map");
|
|
7050
|
+
await promises.stat(m);
|
|
7051
|
+
map = m;
|
|
7052
|
+
} catch {
|
|
7053
|
+
}
|
|
7054
|
+
return { js, map };
|
|
7055
|
+
} catch {
|
|
7056
|
+
return null;
|
|
7057
|
+
}
|
|
7058
|
+
}
|
|
5983
7059
|
async function loadOrCreateKey(fxDir, keyId) {
|
|
5984
7060
|
const path$1 = path.join(fxDir, "keys", `${keyId}.json`);
|
|
5985
7061
|
try {
|
|
@@ -5989,15 +7065,1611 @@ async function loadOrCreateKey(fxDir, keyId) {
|
|
|
5989
7065
|
const kp = await generateKeypair(keyId);
|
|
5990
7066
|
await promises.mkdir(path.dirname(path$1), { recursive: true });
|
|
5991
7067
|
await promises.writeFile(path$1, JSON.stringify(kp, null, 2), "utf8");
|
|
5992
|
-
await promises.writeFile(
|
|
5993
|
-
|
|
5994
|
-
|
|
7068
|
+
await promises.writeFile(path.join(fxDir, "keys", `${keyId}.pub`), `${kp.publicKeyHex}
|
|
7069
|
+
`, "utf8");
|
|
7070
|
+
return kp;
|
|
7071
|
+
}
|
|
7072
|
+
}
|
|
7073
|
+
async function cmdImportMojito(inputDir, options = {}) {
|
|
7074
|
+
const root = path.resolve(inputDir);
|
|
7075
|
+
const outDir = path.resolve(options.outputDir ?? path.join(root, "converted"));
|
|
7076
|
+
await promises.mkdir(outDir, { recursive: true });
|
|
7077
|
+
const waves = await findWaves(root);
|
|
7078
|
+
if (waves.length === 0) {
|
|
7079
|
+
process.stderr.write(`No Mojito waves found under ${root}.
|
|
7080
|
+
`);
|
|
7081
|
+
return 1;
|
|
7082
|
+
}
|
|
7083
|
+
const results = [];
|
|
7084
|
+
for (const waveDir of waves) {
|
|
7085
|
+
try {
|
|
7086
|
+
const r = await convertWave(waveDir, outDir);
|
|
7087
|
+
results.push(r);
|
|
7088
|
+
} catch (e) {
|
|
7089
|
+
results.push({
|
|
7090
|
+
source: waveDir,
|
|
7091
|
+
target: "",
|
|
7092
|
+
warnings: [`failed to convert: ${e.message}`]
|
|
7093
|
+
});
|
|
7094
|
+
}
|
|
7095
|
+
}
|
|
7096
|
+
process.stdout.write(
|
|
7097
|
+
`Converted ${results.length} wave${results.length === 1 ? "" : "s"} \u2192 ${outDir}
|
|
7098
|
+
|
|
7099
|
+
`
|
|
7100
|
+
);
|
|
7101
|
+
for (const r of results) {
|
|
7102
|
+
process.stdout.write(
|
|
7103
|
+
` ${path.basename(r.source)} \u2192 ${r.target ? path.basename(r.target) : "(failed)"}
|
|
7104
|
+
`
|
|
7105
|
+
);
|
|
7106
|
+
for (const w of r.warnings) process.stdout.write(` ! ${w}
|
|
7107
|
+
`);
|
|
7108
|
+
}
|
|
7109
|
+
const failed = results.filter((r) => !r.target).length;
|
|
7110
|
+
return failed === 0 ? 0 : 2;
|
|
7111
|
+
}
|
|
7112
|
+
async function findWaves(root) {
|
|
7113
|
+
const out = [];
|
|
7114
|
+
const entries = await promises.readdir(root, { withFileTypes: true });
|
|
7115
|
+
for (const e of entries) {
|
|
7116
|
+
if (!e.isDirectory()) continue;
|
|
7117
|
+
const dir = path.join(root, e.name);
|
|
7118
|
+
try {
|
|
7119
|
+
const st = await promises.stat(path.join(dir, "config.yml"));
|
|
7120
|
+
if (st.isFile()) out.push(dir);
|
|
7121
|
+
} catch {
|
|
7122
|
+
}
|
|
7123
|
+
}
|
|
7124
|
+
return out;
|
|
7125
|
+
}
|
|
7126
|
+
async function convertWave(waveDir, outDir) {
|
|
7127
|
+
const warnings = [];
|
|
7128
|
+
const cfgText = await promises.readFile(path.join(waveDir, "config.yml"), "utf8");
|
|
7129
|
+
const cfg = yaml.parse(cfgText);
|
|
7130
|
+
if (!cfg.id || !cfg.name || !cfg.recipes) {
|
|
7131
|
+
throw new Error("config.yml missing id, name, or recipes");
|
|
7132
|
+
}
|
|
7133
|
+
const variants = [];
|
|
7134
|
+
const recipeRates = Object.values(cfg.recipes).map((r) => r.sampleRate).filter((v) => typeof v === "number");
|
|
7135
|
+
const allRecipesWeighted = recipeRates.length > 0 && recipeRates.length === Object.keys(cfg.recipes).length;
|
|
7136
|
+
for (const [key, recipe] of Object.entries(cfg.recipes)) {
|
|
7137
|
+
const variant = {
|
|
7138
|
+
key: normalizeKey(key),
|
|
7139
|
+
name: recipe.name ?? key
|
|
7140
|
+
};
|
|
7141
|
+
if (typeof recipe.sampleRate === "number") {
|
|
7142
|
+
if (allRecipesWeighted) {
|
|
7143
|
+
variant.weight = Math.round(recipe.sampleRate * 1e4);
|
|
7144
|
+
} else {
|
|
7145
|
+
variant.recipeSampleRate = recipe.sampleRate;
|
|
7146
|
+
}
|
|
7147
|
+
}
|
|
7148
|
+
if (recipe.js) {
|
|
7149
|
+
try {
|
|
7150
|
+
variant.js = await promises.readFile(path.join(waveDir, recipe.js), "utf8");
|
|
7151
|
+
} catch {
|
|
7152
|
+
warnings.push(`recipe ${key}: js file not found: ${recipe.js}`);
|
|
7153
|
+
}
|
|
7154
|
+
}
|
|
7155
|
+
if (recipe.css) {
|
|
7156
|
+
try {
|
|
7157
|
+
variant.css = await promises.readFile(path.join(waveDir, recipe.css), "utf8");
|
|
7158
|
+
} catch {
|
|
7159
|
+
warnings.push(`recipe ${key}: css file not found: ${recipe.css}`);
|
|
7160
|
+
}
|
|
7161
|
+
}
|
|
7162
|
+
variants.push(variant);
|
|
7163
|
+
}
|
|
7164
|
+
let triggerNote = null;
|
|
7165
|
+
if (cfg.trigger) {
|
|
7166
|
+
triggerNote = await promises.readFile(path.join(waveDir, cfg.trigger), "utf8").catch(() => "");
|
|
7167
|
+
if (triggerNote) {
|
|
7168
|
+
warnings.push(
|
|
7169
|
+
"trigger.js was not auto-converted \u2014 review and translate to a Trigger DSL or host-supplied trigger override."
|
|
7170
|
+
);
|
|
7171
|
+
}
|
|
7172
|
+
}
|
|
7173
|
+
let sharedJs;
|
|
7174
|
+
let sharedCss;
|
|
7175
|
+
if (cfg.js) {
|
|
7176
|
+
sharedJs = await promises.readFile(path.join(waveDir, cfg.js), "utf8").catch(() => {
|
|
7177
|
+
warnings.push(`shared js file not found: ${cfg.js}`);
|
|
7178
|
+
return void 0;
|
|
7179
|
+
});
|
|
7180
|
+
}
|
|
7181
|
+
if (cfg.css) {
|
|
7182
|
+
sharedCss = await promises.readFile(path.join(waveDir, cfg.css), "utf8").catch(() => {
|
|
7183
|
+
warnings.push(`shared css file not found: ${cfg.css}`);
|
|
7184
|
+
return void 0;
|
|
7185
|
+
});
|
|
7186
|
+
}
|
|
7187
|
+
const spec = {
|
|
7188
|
+
id: cfg.id.toLowerCase(),
|
|
7189
|
+
name: cfg.name,
|
|
7190
|
+
sampleRate: cfg.sampleRate ?? 1,
|
|
7191
|
+
variants
|
|
7192
|
+
};
|
|
7193
|
+
if (cfg.divertTo) spec.divertTo = normalizeKey(cfg.divertTo);
|
|
7194
|
+
if (cfg.manualExposure) spec.manualExposure = true;
|
|
7195
|
+
if (sharedJs) spec.sharedJs = sharedJs;
|
|
7196
|
+
if (sharedCss) spec.sharedCss = sharedCss;
|
|
7197
|
+
if (triggerNote) spec.trigger = { kind: "auto" };
|
|
7198
|
+
const header = [
|
|
7199
|
+
"# Imported from Mojito wave",
|
|
7200
|
+
`# Source: ${waveDir}`,
|
|
7201
|
+
cfg.state ? `# Original state: ${cfg.state}` : null,
|
|
7202
|
+
triggerNote ? "#" : null,
|
|
7203
|
+
triggerNote ? "# Original trigger.js (NOT auto-applied):" : null,
|
|
7204
|
+
triggerNote ? triggerNote.split("\n").map((l) => `# ${l}`).join("\n") : null
|
|
7205
|
+
].filter((l) => l !== null).join("\n");
|
|
7206
|
+
const yamlBody = yaml.stringify(spec);
|
|
7207
|
+
const target = path.join(outDir, `${spec.id}.yaml`);
|
|
7208
|
+
await promises.writeFile(target, `${header}
|
|
7209
|
+
${yamlBody}`, "utf8");
|
|
7210
|
+
return { source: waveDir, target, warnings };
|
|
7211
|
+
}
|
|
7212
|
+
function normalizeKey(k) {
|
|
7213
|
+
return k.toLowerCase().replace(/[^a-z0-9_-]/g, "-");
|
|
7214
|
+
}
|
|
7215
|
+
|
|
7216
|
+
// ../api-protocol/dist/index.js
|
|
7217
|
+
var Empty = external_exports.object({});
|
|
7218
|
+
var TenantSelf = external_exports.object({
|
|
7219
|
+
organization: external_exports.object({
|
|
7220
|
+
id: external_exports.string(),
|
|
7221
|
+
name: external_exports.string(),
|
|
7222
|
+
slug: external_exports.string(),
|
|
7223
|
+
createdAt: external_exports.string().datetime()
|
|
7224
|
+
}),
|
|
7225
|
+
member: external_exports.object({
|
|
7226
|
+
role: external_exports.enum(["owner", "admin", "experimenter", "viewer"])
|
|
7227
|
+
}),
|
|
7228
|
+
user: external_exports.object({
|
|
7229
|
+
id: external_exports.string(),
|
|
7230
|
+
email: external_exports.string().email(),
|
|
7231
|
+
name: external_exports.string().nullable()
|
|
7232
|
+
})
|
|
7233
|
+
});
|
|
7234
|
+
var ProjectListResponse = external_exports.object({ projects: external_exports.array(Project) });
|
|
7235
|
+
var PropertyListResponse = external_exports.object({ properties: external_exports.array(Property) });
|
|
7236
|
+
var EnvironmentListResponse = external_exports.object({ environments: external_exports.array(Environment) });
|
|
7237
|
+
var FeatureListResponse = external_exports.object({ features: external_exports.array(Feature) });
|
|
7238
|
+
var FeatureRuleListResponse = external_exports.object({ rules: external_exports.array(FeatureRule) });
|
|
7239
|
+
var PublicationListResponse = external_exports.object({ publications: external_exports.array(EnvironmentPublication) });
|
|
7240
|
+
var PromoteEnvironmentInput2 = external_exports.object({ sourceEnvironmentId: external_exports.string().uuid() });
|
|
7241
|
+
var PromoteEnvironmentResponse = external_exports.object({
|
|
7242
|
+
sourceEnvironmentId: external_exports.string().uuid(),
|
|
7243
|
+
sourceVersion: external_exports.number().int().positive(),
|
|
7244
|
+
targetEnvironmentId: external_exports.string().uuid(),
|
|
7245
|
+
promotedRuleCount: external_exports.number().int().nonnegative()
|
|
7246
|
+
});
|
|
7247
|
+
var ExperimentSummary = external_exports.object({
|
|
7248
|
+
id: Experiment.shape.id,
|
|
7249
|
+
name: Experiment.shape.name,
|
|
7250
|
+
state: ExperimentState,
|
|
7251
|
+
updatedAt: external_exports.string().datetime()
|
|
7252
|
+
});
|
|
7253
|
+
var ExperimentListResponse = external_exports.object({
|
|
7254
|
+
experiments: external_exports.array(ExperimentSummary)
|
|
7255
|
+
});
|
|
7256
|
+
var CreateExperimentInput2 = ExperimentSpecBase;
|
|
7257
|
+
var CreateExperimentResponse = external_exports.object({
|
|
7258
|
+
experimentId: ExperimentId,
|
|
7259
|
+
idempotent: external_exports.boolean().optional()
|
|
7260
|
+
});
|
|
7261
|
+
var AggregateRow = external_exports.object({
|
|
7262
|
+
variantKey: external_exports.string(),
|
|
7263
|
+
exposureCount: external_exports.number().int().nonnegative(),
|
|
7264
|
+
conversionCount: external_exports.number().int().nonnegative(),
|
|
7265
|
+
conversionSum: external_exports.number(),
|
|
7266
|
+
failureCount: external_exports.number().int().nonnegative().default(0)
|
|
7267
|
+
});
|
|
7268
|
+
var AggregateInput = external_exports.object({
|
|
7269
|
+
metric: external_exports.string().min(1).max(120),
|
|
7270
|
+
fromIso: external_exports.string().datetime().optional(),
|
|
7271
|
+
untilIso: external_exports.string().datetime().optional(),
|
|
7272
|
+
segmentKey: external_exports.string().min(1).max(80).regex(/^[A-Za-z0-9_.-]+$/).optional(),
|
|
7273
|
+
prePeriodDays: external_exports.coerce.number().int().min(1).max(365).optional()
|
|
7274
|
+
});
|
|
7275
|
+
var AggregateResponse = external_exports.object({
|
|
7276
|
+
experimentId: ExperimentId,
|
|
7277
|
+
metric: external_exports.string(),
|
|
7278
|
+
rows: external_exports.array(AggregateRow),
|
|
7279
|
+
/** ISO datetime — when this aggregate was computed. SDKs may cache by this. */
|
|
7280
|
+
computedAt: external_exports.string().datetime(),
|
|
7281
|
+
analytics: external_exports.object({
|
|
7282
|
+
variants: external_exports.array(
|
|
7283
|
+
external_exports.object({
|
|
7284
|
+
variantKey: external_exports.string(),
|
|
7285
|
+
exposedSubjects: external_exports.number().int().nonnegative(),
|
|
7286
|
+
convertedSubjects: external_exports.number().int().nonnegative(),
|
|
7287
|
+
meanTimeToConvertMs: external_exports.number().nonnegative().nullable(),
|
|
7288
|
+
medianTimeToConvertMs: external_exports.number().nonnegative().nullable(),
|
|
7289
|
+
p90TimeToConvertMs: external_exports.number().nonnegative().nullable(),
|
|
7290
|
+
meanConversionDepth: external_exports.number().nonnegative(),
|
|
7291
|
+
conversionDepth: external_exports.object({
|
|
7292
|
+
oneOrMore: external_exports.number().int().nonnegative(),
|
|
7293
|
+
twoOrMore: external_exports.number().int().nonnegative(),
|
|
7294
|
+
threeOrMore: external_exports.number().int().nonnegative()
|
|
7295
|
+
}),
|
|
7296
|
+
cupedAdjustedRate: external_exports.number().nullable(),
|
|
7297
|
+
cupedLift: external_exports.number().nullable()
|
|
7298
|
+
})
|
|
7299
|
+
),
|
|
7300
|
+
segments: external_exports.array(
|
|
7301
|
+
external_exports.object({
|
|
7302
|
+
segmentValue: external_exports.string(),
|
|
7303
|
+
variantKey: external_exports.string(),
|
|
7304
|
+
exposureCount: external_exports.number().int().nonnegative(),
|
|
7305
|
+
conversionCount: external_exports.number().int().nonnegative(),
|
|
7306
|
+
conversionRate: external_exports.number().min(0).max(1)
|
|
7307
|
+
})
|
|
7308
|
+
),
|
|
7309
|
+
segmentKey: external_exports.string().optional(),
|
|
7310
|
+
cuped: external_exports.object({
|
|
7311
|
+
available: external_exports.boolean(),
|
|
7312
|
+
prePeriodDays: external_exports.number().int().positive(),
|
|
7313
|
+
theta: external_exports.number().nullable(),
|
|
7314
|
+
varianceReduction: external_exports.number().nullable()
|
|
7315
|
+
})
|
|
7316
|
+
}).optional()
|
|
7317
|
+
});
|
|
7318
|
+
var InvokeActionInput = external_exports.object({
|
|
7319
|
+
actionId: ActionId,
|
|
7320
|
+
params: external_exports.record(external_exports.unknown()),
|
|
7321
|
+
/** Optional client-supplied idempotency key. */
|
|
7322
|
+
idempotencyKey: external_exports.string().min(8).max(128).optional()
|
|
7323
|
+
});
|
|
7324
|
+
var InvokeActionResponse = external_exports.object({
|
|
7325
|
+
success: external_exports.boolean(),
|
|
7326
|
+
data: external_exports.record(external_exports.unknown()).optional(),
|
|
7327
|
+
error: external_exports.string().optional()
|
|
7328
|
+
});
|
|
7329
|
+
var EdgePushResult = external_exports.object({
|
|
7330
|
+
pushed: external_exports.boolean(),
|
|
7331
|
+
reason: external_exports.string().optional(),
|
|
7332
|
+
status: external_exports.number().int().optional()
|
|
7333
|
+
});
|
|
7334
|
+
var PublishManifestResponse = external_exports.object({
|
|
7335
|
+
manifestVersion: external_exports.number().int().nonnegative(),
|
|
7336
|
+
contentHash: external_exports.string().regex(/^[0-9a-f]{64}$/),
|
|
7337
|
+
experimentCount: external_exports.number().int().nonnegative(),
|
|
7338
|
+
/** Edge push status. `pushed: false` with `reason: 'unconfigured'` is normal in local dev. */
|
|
7339
|
+
edgePush: EdgePushResult
|
|
7340
|
+
});
|
|
7341
|
+
var ManifestKey = external_exports.object({
|
|
7342
|
+
keyId: external_exports.string(),
|
|
7343
|
+
publicKeyHex: external_exports.string().regex(/^[0-9a-f]+$/),
|
|
7344
|
+
status: external_exports.enum(["active", "retiring", "retired"]),
|
|
7345
|
+
createdAt: external_exports.string().datetime(),
|
|
7346
|
+
retiredAt: external_exports.string().datetime().nullable()
|
|
7347
|
+
});
|
|
7348
|
+
var ManifestKeysResponse = external_exports.object({ keys: external_exports.array(ManifestKey) });
|
|
7349
|
+
var PreviewSignInput = external_exports.object({
|
|
7350
|
+
experimentId: ExperimentId,
|
|
7351
|
+
variantKey: external_exports.string().min(1).max(32),
|
|
7352
|
+
/** Token TTL in seconds. Clamped server-side to [60, 3600]; default 900. */
|
|
7353
|
+
ttlSeconds: external_exports.number().int().min(60).max(3600).optional()
|
|
7354
|
+
});
|
|
7355
|
+
var PreviewSignResponse = external_exports.object({
|
|
7356
|
+
token: external_exports.string(),
|
|
7357
|
+
/** ISO datetime when the token expires. */
|
|
7358
|
+
expiresAt: external_exports.string().datetime(),
|
|
7359
|
+
/** ID of the public JWKS key used to sign — exposed for debugging only. */
|
|
7360
|
+
keyId: external_exports.string(),
|
|
7361
|
+
/** Unique JWT id for audit/debugging and future replay controls. */
|
|
7362
|
+
jti: external_exports.string()
|
|
7363
|
+
});
|
|
7364
|
+
var AuditEvent = external_exports.object({
|
|
7365
|
+
id: external_exports.string(),
|
|
7366
|
+
type: external_exports.string(),
|
|
7367
|
+
experimentId: external_exports.string(),
|
|
7368
|
+
actorId: external_exports.string(),
|
|
7369
|
+
at: external_exports.string().datetime(),
|
|
7370
|
+
payload: external_exports.record(external_exports.unknown())
|
|
7371
|
+
});
|
|
7372
|
+
var AuditListResponse = external_exports.object({ events: external_exports.array(AuditEvent) });
|
|
7373
|
+
var AuditExport = external_exports.object({
|
|
7374
|
+
id: external_exports.string(),
|
|
7375
|
+
destinationKind: external_exports.enum(["s3", "r2", "splunk-hec"]),
|
|
7376
|
+
status: external_exports.enum(["active", "paused", "failed"]),
|
|
7377
|
+
lastCursorAt: external_exports.string().datetime().nullable()
|
|
7378
|
+
});
|
|
7379
|
+
var AuditExportListResponse = external_exports.object({ exports: external_exports.array(AuditExport) });
|
|
7380
|
+
var CreateAuditExportInput = external_exports.object({
|
|
7381
|
+
destinationKind: external_exports.enum(["s3", "r2", "splunk-hec"]),
|
|
7382
|
+
/** Free-form config; encrypted at rest. Schema enforced by destination kind. */
|
|
7383
|
+
config: external_exports.record(external_exports.unknown())
|
|
7384
|
+
});
|
|
7385
|
+
var ApiKeySummary = external_exports.object({
|
|
7386
|
+
id: external_exports.string(),
|
|
7387
|
+
name: external_exports.string(),
|
|
7388
|
+
prefix: external_exports.string(),
|
|
7389
|
+
role: external_exports.enum(["owner", "admin", "experimenter", "viewer"]),
|
|
7390
|
+
scopes: external_exports.array(external_exports.enum(["read", "write", "admin"])),
|
|
7391
|
+
createdAt: external_exports.string().datetime(),
|
|
7392
|
+
lastUsedAt: external_exports.string().datetime().nullable(),
|
|
7393
|
+
expiresAt: external_exports.string().datetime().nullable()
|
|
7394
|
+
});
|
|
7395
|
+
var ApiKeyListResponse = external_exports.object({ keys: external_exports.array(ApiKeySummary) });
|
|
7396
|
+
var CreateApiKeyInput = external_exports.object({
|
|
7397
|
+
name: external_exports.string().min(1).max(120),
|
|
7398
|
+
/** ISO datetime of expiry; null for non-expiring (not recommended in prod). */
|
|
7399
|
+
expiresAt: external_exports.string().datetime().nullable(),
|
|
7400
|
+
/** Role assigned to the key. Defaults to the creator's role. */
|
|
7401
|
+
role: external_exports.enum(["owner", "admin", "experimenter", "viewer"]).optional(),
|
|
7402
|
+
/** Permission scopes assigned to the key. Defaults are derived from role. */
|
|
7403
|
+
scopes: external_exports.array(external_exports.enum(["read", "write", "admin"])).optional()
|
|
7404
|
+
});
|
|
7405
|
+
var CreateApiKeyResponse = ApiKeySummary.extend({
|
|
7406
|
+
/** Plaintext key, returned exactly once at creation time. */
|
|
7407
|
+
key: external_exports.string()
|
|
7408
|
+
});
|
|
7409
|
+
var SamlConfig = external_exports.object({
|
|
7410
|
+
enabled: external_exports.boolean(),
|
|
7411
|
+
connectionId: external_exports.string().min(1).max(200).nullable(),
|
|
7412
|
+
issuer: external_exports.string().min(1).max(500).nullable(),
|
|
7413
|
+
ssoUrl: external_exports.string().url().nullable(),
|
|
7414
|
+
certificate: external_exports.string().min(1).max(1e4).nullable()
|
|
7415
|
+
}).refine(
|
|
7416
|
+
(value) => !value.enabled || Boolean(value.connectionId && value.issuer && value.ssoUrl && value.certificate),
|
|
7417
|
+
{
|
|
7418
|
+
message: "connectionId, issuer, ssoUrl, certificate required when SAML is enabled"
|
|
7419
|
+
}
|
|
7420
|
+
);
|
|
7421
|
+
var TestRunStatus = external_exports.enum(["running", "passed", "failed", "skipped", "canceled"]);
|
|
7422
|
+
var TestCaseStatus = external_exports.enum([
|
|
7423
|
+
"passed",
|
|
7424
|
+
"failed",
|
|
7425
|
+
"skipped",
|
|
7426
|
+
"pending",
|
|
7427
|
+
"undefined",
|
|
7428
|
+
"unknown"
|
|
7429
|
+
]);
|
|
7430
|
+
var TestCaseResult = external_exports.object({
|
|
7431
|
+
id: external_exports.string().max(240).optional(),
|
|
7432
|
+
name: external_exports.string().min(1).max(500),
|
|
7433
|
+
uri: external_exports.string().max(1e3).optional(),
|
|
7434
|
+
status: TestCaseStatus,
|
|
7435
|
+
durationMs: external_exports.number().int().nonnegative().max(864e5),
|
|
7436
|
+
tags: external_exports.array(external_exports.string().max(120)).max(100).default([]),
|
|
7437
|
+
error: external_exports.string().max(65536).optional(),
|
|
7438
|
+
statementId: external_exports.string().max(240).optional(),
|
|
7439
|
+
resourceUrl: external_exports.string().url().max(4e3).optional(),
|
|
7440
|
+
details: external_exports.record(external_exports.unknown()).optional()
|
|
7441
|
+
});
|
|
7442
|
+
var TestRunSummary = external_exports.object({
|
|
7443
|
+
total: external_exports.number().int().nonnegative(),
|
|
7444
|
+
passed: external_exports.number().int().nonnegative(),
|
|
7445
|
+
failed: external_exports.number().int().nonnegative(),
|
|
7446
|
+
skipped: external_exports.number().int().nonnegative(),
|
|
7447
|
+
pending: external_exports.number().int().nonnegative().default(0)
|
|
7448
|
+
});
|
|
7449
|
+
var TestRunArtifact = external_exports.object({
|
|
7450
|
+
name: external_exports.string().min(1).max(240),
|
|
7451
|
+
url: external_exports.string().url().max(4e3),
|
|
7452
|
+
mediaType: external_exports.string().max(240).optional()
|
|
7453
|
+
});
|
|
7454
|
+
var CreateTestRunInput = external_exports.object({
|
|
7455
|
+
externalId: external_exports.string().min(1).max(300).optional(),
|
|
7456
|
+
source: external_exports.enum(["bdd", "live-suite", "junit", "cli", "other"]),
|
|
7457
|
+
suite: external_exports.string().min(1).max(240),
|
|
7458
|
+
status: TestRunStatus,
|
|
7459
|
+
startedAt: external_exports.string().datetime().nullable().optional(),
|
|
7460
|
+
finishedAt: external_exports.string().datetime().nullable().optional(),
|
|
7461
|
+
durationMs: external_exports.number().int().nonnegative().max(6048e5).default(0),
|
|
7462
|
+
summary: TestRunSummary,
|
|
7463
|
+
environment: external_exports.record(external_exports.unknown()).default({}),
|
|
7464
|
+
revision: external_exports.record(external_exports.unknown()).default({}),
|
|
7465
|
+
cases: external_exports.array(TestCaseResult).max(2e3).default([]),
|
|
7466
|
+
artifacts: external_exports.array(TestRunArtifact).max(100).default([])
|
|
7467
|
+
});
|
|
7468
|
+
var TestRun = CreateTestRunInput.extend({
|
|
7469
|
+
id: external_exports.string().uuid(),
|
|
7470
|
+
orgId: external_exports.string(),
|
|
7471
|
+
createdBy: external_exports.string(),
|
|
7472
|
+
createdAt: external_exports.string().datetime(),
|
|
7473
|
+
updatedAt: external_exports.string().datetime()
|
|
7474
|
+
});
|
|
7475
|
+
var TestRunListInput = external_exports.object({
|
|
7476
|
+
status: TestRunStatus.optional(),
|
|
7477
|
+
source: CreateTestRunInput.shape.source.optional(),
|
|
7478
|
+
suite: external_exports.string().min(1).max(240).optional(),
|
|
7479
|
+
limit: external_exports.coerce.number().int().min(1).max(200).optional()
|
|
7480
|
+
});
|
|
7481
|
+
var TestRunListResponse = external_exports.object({
|
|
7482
|
+
runs: external_exports.array(TestRun.omit({ cases: true }))
|
|
7483
|
+
});
|
|
7484
|
+
var endpoints = {
|
|
7485
|
+
"tenants.me": {
|
|
7486
|
+
method: "GET",
|
|
7487
|
+
path: "/v1/tenants/me",
|
|
7488
|
+
params: Empty,
|
|
7489
|
+
response: TenantSelf,
|
|
7490
|
+
mutates: false,
|
|
7491
|
+
requiresRole: null
|
|
7492
|
+
},
|
|
7493
|
+
"experiments.list": {
|
|
7494
|
+
method: "GET",
|
|
7495
|
+
path: "/v1/orgs/:orgId/experiments",
|
|
7496
|
+
params: Empty,
|
|
7497
|
+
response: ExperimentListResponse,
|
|
7498
|
+
mutates: false,
|
|
7499
|
+
requiresRole: "viewer"
|
|
7500
|
+
},
|
|
7501
|
+
"experiments.create": {
|
|
7502
|
+
method: "POST",
|
|
7503
|
+
path: "/v1/orgs/:orgId/experiments",
|
|
7504
|
+
params: CreateExperimentInput2,
|
|
7505
|
+
response: CreateExperimentResponse,
|
|
7506
|
+
mutates: true,
|
|
7507
|
+
requiresRole: "experimenter"
|
|
7508
|
+
},
|
|
7509
|
+
"experiments.get": {
|
|
7510
|
+
method: "GET",
|
|
7511
|
+
path: "/v1/orgs/:orgId/experiments/:experimentId",
|
|
7512
|
+
params: Empty,
|
|
7513
|
+
response: Experiment,
|
|
7514
|
+
mutates: false,
|
|
7515
|
+
requiresRole: "viewer"
|
|
7516
|
+
},
|
|
7517
|
+
"experiments.invokeAction": {
|
|
7518
|
+
method: "POST",
|
|
7519
|
+
path: "/v1/orgs/:orgId/experiments/actions",
|
|
7520
|
+
params: InvokeActionInput,
|
|
7521
|
+
response: InvokeActionResponse,
|
|
7522
|
+
mutates: true,
|
|
7523
|
+
requiresRole: "experimenter"
|
|
7524
|
+
},
|
|
7525
|
+
"experiments.aggregate": {
|
|
7526
|
+
method: "GET",
|
|
7527
|
+
path: "/v1/orgs/:orgId/experiments/:experimentId/aggregate",
|
|
7528
|
+
params: AggregateInput,
|
|
7529
|
+
response: AggregateResponse,
|
|
7530
|
+
mutates: false,
|
|
7531
|
+
requiresRole: "viewer"
|
|
7532
|
+
},
|
|
7533
|
+
"projects.list": {
|
|
7534
|
+
method: "GET",
|
|
7535
|
+
path: "/v1/orgs/:orgId/projects",
|
|
7536
|
+
params: Empty,
|
|
7537
|
+
response: ProjectListResponse,
|
|
7538
|
+
mutates: false,
|
|
7539
|
+
requiresRole: "viewer"
|
|
7540
|
+
},
|
|
7541
|
+
"projects.create": {
|
|
7542
|
+
method: "POST",
|
|
7543
|
+
path: "/v1/orgs/:orgId/projects",
|
|
7544
|
+
params: CreateProjectInput,
|
|
7545
|
+
response: Project,
|
|
7546
|
+
mutates: true,
|
|
7547
|
+
requiresRole: "experimenter"
|
|
7548
|
+
},
|
|
7549
|
+
"properties.list": {
|
|
7550
|
+
method: "GET",
|
|
7551
|
+
path: "/v1/orgs/:orgId/projects/:projectId/properties",
|
|
7552
|
+
params: Empty,
|
|
7553
|
+
response: PropertyListResponse,
|
|
7554
|
+
mutates: false,
|
|
7555
|
+
requiresRole: "viewer"
|
|
7556
|
+
},
|
|
7557
|
+
"properties.create": {
|
|
7558
|
+
method: "POST",
|
|
7559
|
+
path: "/v1/orgs/:orgId/projects/:projectId/properties",
|
|
7560
|
+
params: CreatePropertyInput,
|
|
7561
|
+
response: Property,
|
|
7562
|
+
mutates: true,
|
|
7563
|
+
requiresRole: "experimenter"
|
|
7564
|
+
},
|
|
7565
|
+
"environments.list": {
|
|
7566
|
+
method: "GET",
|
|
7567
|
+
path: "/v1/orgs/:orgId/projects/:projectId/environments",
|
|
7568
|
+
params: Empty,
|
|
7569
|
+
response: EnvironmentListResponse,
|
|
7570
|
+
mutates: false,
|
|
7571
|
+
requiresRole: "viewer"
|
|
7572
|
+
},
|
|
7573
|
+
"environments.create": {
|
|
7574
|
+
method: "POST",
|
|
7575
|
+
path: "/v1/orgs/:orgId/projects/:projectId/environments",
|
|
7576
|
+
params: CreateEnvironmentInput,
|
|
7577
|
+
response: Environment,
|
|
7578
|
+
mutates: true,
|
|
7579
|
+
requiresRole: "experimenter"
|
|
7580
|
+
},
|
|
7581
|
+
"features.list": {
|
|
7582
|
+
method: "GET",
|
|
7583
|
+
path: "/v1/orgs/:orgId/projects/:projectId/features",
|
|
7584
|
+
params: Empty,
|
|
7585
|
+
response: FeatureListResponse,
|
|
7586
|
+
mutates: false,
|
|
7587
|
+
requiresRole: "viewer"
|
|
7588
|
+
},
|
|
7589
|
+
"features.create": {
|
|
7590
|
+
method: "POST",
|
|
7591
|
+
path: "/v1/orgs/:orgId/projects/:projectId/features",
|
|
7592
|
+
params: CreateFeatureInput,
|
|
7593
|
+
response: Feature,
|
|
7594
|
+
mutates: true,
|
|
7595
|
+
requiresRole: "experimenter"
|
|
7596
|
+
},
|
|
7597
|
+
"rules.list": {
|
|
7598
|
+
method: "GET",
|
|
7599
|
+
path: "/v1/orgs/:orgId/features/:featureId/rules",
|
|
7600
|
+
params: Empty,
|
|
7601
|
+
response: FeatureRuleListResponse,
|
|
7602
|
+
mutates: false,
|
|
7603
|
+
requiresRole: "viewer"
|
|
7604
|
+
},
|
|
7605
|
+
"rules.create": {
|
|
7606
|
+
method: "POST",
|
|
7607
|
+
path: "/v1/orgs/:orgId/features/:featureId/rules",
|
|
7608
|
+
params: CreateFeatureRuleInput,
|
|
7609
|
+
response: FeatureRule,
|
|
7610
|
+
mutates: true,
|
|
7611
|
+
requiresRole: "experimenter"
|
|
7612
|
+
},
|
|
7613
|
+
"environments.publish": {
|
|
7614
|
+
method: "POST",
|
|
7615
|
+
path: "/v1/orgs/:orgId/environments/:environmentId/publish",
|
|
7616
|
+
params: Empty,
|
|
7617
|
+
response: EnvironmentPublication,
|
|
7618
|
+
mutates: true,
|
|
7619
|
+
requiresRole: "experimenter"
|
|
7620
|
+
},
|
|
7621
|
+
"environments.publications": {
|
|
7622
|
+
method: "GET",
|
|
7623
|
+
path: "/v1/orgs/:orgId/environments/:environmentId/publications",
|
|
7624
|
+
params: Empty,
|
|
7625
|
+
response: PublicationListResponse,
|
|
7626
|
+
mutates: false,
|
|
7627
|
+
requiresRole: "viewer"
|
|
7628
|
+
},
|
|
7629
|
+
"environments.promote": {
|
|
7630
|
+
method: "POST",
|
|
7631
|
+
path: "/v1/orgs/:orgId/environments/:environmentId/promote",
|
|
7632
|
+
params: PromoteEnvironmentInput2,
|
|
7633
|
+
response: PromoteEnvironmentResponse,
|
|
7634
|
+
mutates: true,
|
|
7635
|
+
requiresRole: "experimenter"
|
|
7636
|
+
},
|
|
7637
|
+
"configuration.getPublished": {
|
|
7638
|
+
method: "GET",
|
|
7639
|
+
path: "/v1/orgs/:orgId/environments/:environmentId/configuration",
|
|
7640
|
+
params: Empty,
|
|
7641
|
+
response: EnvironmentPublication,
|
|
7642
|
+
mutates: false,
|
|
7643
|
+
requiresRole: "viewer"
|
|
7644
|
+
},
|
|
7645
|
+
"manifests.publish": {
|
|
7646
|
+
method: "POST",
|
|
7647
|
+
path: "/v1/orgs/:orgId/manifests/publish",
|
|
7648
|
+
params: Empty,
|
|
7649
|
+
response: PublishManifestResponse,
|
|
7650
|
+
mutates: true,
|
|
7651
|
+
requiresRole: "experimenter"
|
|
7652
|
+
},
|
|
7653
|
+
"manifests.getKeys": {
|
|
7654
|
+
method: "GET",
|
|
7655
|
+
path: "/v1/orgs/:orgId/manifests/keys",
|
|
7656
|
+
params: Empty,
|
|
7657
|
+
response: ManifestKeysResponse,
|
|
7658
|
+
mutates: false,
|
|
7659
|
+
requiresRole: "admin"
|
|
7660
|
+
},
|
|
7661
|
+
"manifests.rotateKey": {
|
|
7662
|
+
method: "POST",
|
|
7663
|
+
path: "/v1/orgs/:orgId/manifests/keys/rotate",
|
|
7664
|
+
params: external_exports.object({ keyId: external_exports.string().min(1).max(128) }),
|
|
7665
|
+
response: ManifestKey,
|
|
7666
|
+
mutates: true,
|
|
7667
|
+
requiresRole: "admin"
|
|
7668
|
+
},
|
|
7669
|
+
"manifests.retireKey": {
|
|
7670
|
+
method: "POST",
|
|
7671
|
+
path: "/v1/orgs/:orgId/manifests/keys/retire",
|
|
7672
|
+
params: external_exports.object({ keyId: external_exports.string() }),
|
|
7673
|
+
response: ManifestKey,
|
|
7674
|
+
mutates: true,
|
|
7675
|
+
requiresRole: "admin"
|
|
7676
|
+
},
|
|
7677
|
+
"preview.sign": {
|
|
7678
|
+
method: "POST",
|
|
7679
|
+
path: "/v1/orgs/:orgId/preview/sign",
|
|
7680
|
+
params: PreviewSignInput,
|
|
7681
|
+
response: PreviewSignResponse,
|
|
7682
|
+
mutates: true,
|
|
7683
|
+
requiresRole: "experimenter"
|
|
7684
|
+
},
|
|
7685
|
+
"audit.list": {
|
|
7686
|
+
method: "GET",
|
|
7687
|
+
path: "/v1/orgs/:orgId/audit",
|
|
7688
|
+
params: Empty,
|
|
7689
|
+
response: AuditListResponse,
|
|
7690
|
+
mutates: false,
|
|
7691
|
+
requiresRole: "viewer"
|
|
7692
|
+
},
|
|
7693
|
+
"audit.exports.list": {
|
|
7694
|
+
method: "GET",
|
|
7695
|
+
path: "/v1/orgs/:orgId/audit/exports",
|
|
7696
|
+
params: Empty,
|
|
7697
|
+
response: AuditExportListResponse,
|
|
7698
|
+
mutates: false,
|
|
7699
|
+
requiresRole: "admin"
|
|
7700
|
+
},
|
|
7701
|
+
"audit.exports.create": {
|
|
7702
|
+
method: "POST",
|
|
7703
|
+
path: "/v1/orgs/:orgId/audit/exports",
|
|
7704
|
+
params: CreateAuditExportInput,
|
|
7705
|
+
response: AuditExport,
|
|
7706
|
+
mutates: true,
|
|
7707
|
+
requiresRole: "admin"
|
|
7708
|
+
},
|
|
7709
|
+
"audit.exports.delete": {
|
|
7710
|
+
method: "DELETE",
|
|
7711
|
+
path: "/v1/orgs/:orgId/audit/exports/:exportId",
|
|
7712
|
+
params: Empty,
|
|
7713
|
+
response: external_exports.object({ ok: external_exports.literal(true) }),
|
|
7714
|
+
mutates: true,
|
|
7715
|
+
requiresRole: "admin"
|
|
7716
|
+
},
|
|
7717
|
+
"apiKeys.list": {
|
|
7718
|
+
method: "GET",
|
|
7719
|
+
path: "/v1/orgs/:orgId/api-keys",
|
|
7720
|
+
params: Empty,
|
|
7721
|
+
response: ApiKeyListResponse,
|
|
7722
|
+
mutates: false,
|
|
7723
|
+
requiresRole: "admin"
|
|
7724
|
+
},
|
|
7725
|
+
"apiKeys.create": {
|
|
7726
|
+
method: "POST",
|
|
7727
|
+
path: "/v1/orgs/:orgId/api-keys",
|
|
7728
|
+
params: CreateApiKeyInput,
|
|
7729
|
+
response: CreateApiKeyResponse,
|
|
7730
|
+
mutates: true,
|
|
7731
|
+
requiresRole: "admin"
|
|
7732
|
+
},
|
|
7733
|
+
"apiKeys.revoke": {
|
|
7734
|
+
method: "DELETE",
|
|
7735
|
+
path: "/v1/orgs/:orgId/api-keys/:keyId",
|
|
7736
|
+
params: Empty,
|
|
7737
|
+
response: external_exports.object({ ok: external_exports.literal(true) }),
|
|
7738
|
+
mutates: true,
|
|
7739
|
+
requiresRole: "admin"
|
|
7740
|
+
},
|
|
7741
|
+
"saml.get": {
|
|
7742
|
+
method: "GET",
|
|
7743
|
+
path: "/v1/orgs/:orgId/saml",
|
|
7744
|
+
params: Empty,
|
|
7745
|
+
response: SamlConfig,
|
|
7746
|
+
mutates: false,
|
|
7747
|
+
requiresRole: "owner"
|
|
7748
|
+
},
|
|
7749
|
+
"saml.update": {
|
|
7750
|
+
method: "POST",
|
|
7751
|
+
path: "/v1/orgs/:orgId/saml",
|
|
7752
|
+
params: SamlConfig,
|
|
7753
|
+
response: SamlConfig,
|
|
7754
|
+
mutates: true,
|
|
7755
|
+
requiresRole: "owner"
|
|
7756
|
+
},
|
|
7757
|
+
"testRuns.list": {
|
|
7758
|
+
method: "GET",
|
|
7759
|
+
path: "/v1/orgs/:orgId/test-runs",
|
|
7760
|
+
params: TestRunListInput,
|
|
7761
|
+
response: TestRunListResponse,
|
|
7762
|
+
mutates: false,
|
|
7763
|
+
requiresRole: "viewer"
|
|
7764
|
+
},
|
|
7765
|
+
"testRuns.create": {
|
|
7766
|
+
method: "POST",
|
|
7767
|
+
path: "/v1/orgs/:orgId/test-runs",
|
|
7768
|
+
params: CreateTestRunInput,
|
|
7769
|
+
response: TestRun,
|
|
7770
|
+
mutates: true,
|
|
7771
|
+
requiresRole: "experimenter"
|
|
7772
|
+
},
|
|
7773
|
+
"testRuns.get": {
|
|
7774
|
+
method: "GET",
|
|
7775
|
+
path: "/v1/orgs/:orgId/test-runs/:runId",
|
|
7776
|
+
params: Empty,
|
|
7777
|
+
response: TestRun,
|
|
7778
|
+
mutates: false,
|
|
7779
|
+
requiresRole: "viewer"
|
|
7780
|
+
}
|
|
7781
|
+
};
|
|
7782
|
+
function buildPath(template, pathParams) {
|
|
7783
|
+
return template.replace(/:([a-zA-Z][a-zA-Z0-9_]*)/g, (_, name) => {
|
|
7784
|
+
const v = pathParams[name];
|
|
7785
|
+
if (v == null) throw new Error(`Missing path parameter: ${name}`);
|
|
7786
|
+
return encodeURIComponent(v);
|
|
7787
|
+
});
|
|
7788
|
+
}
|
|
7789
|
+
external_exports.object({
|
|
7790
|
+
code: external_exports.enum([
|
|
7791
|
+
"UNAUTHENTICATED",
|
|
7792
|
+
"FORBIDDEN",
|
|
7793
|
+
"NOT_FOUND",
|
|
7794
|
+
"VALIDATION_FAILED",
|
|
7795
|
+
"CONFLICT",
|
|
7796
|
+
"RATE_LIMITED",
|
|
7797
|
+
"INTERNAL"
|
|
7798
|
+
]),
|
|
7799
|
+
message: external_exports.string(),
|
|
7800
|
+
details: external_exports.record(external_exports.unknown()).optional()
|
|
7801
|
+
});
|
|
7802
|
+
|
|
7803
|
+
// ../api-client/dist/index.js
|
|
7804
|
+
var ApiError2 = class extends Error {
|
|
7805
|
+
constructor(status, code, message, details) {
|
|
7806
|
+
super(message);
|
|
7807
|
+
this.status = status;
|
|
7808
|
+
this.code = code;
|
|
7809
|
+
this.details = details;
|
|
7810
|
+
this.name = "ApiError";
|
|
7811
|
+
}
|
|
7812
|
+
status;
|
|
7813
|
+
code;
|
|
7814
|
+
details;
|
|
7815
|
+
};
|
|
7816
|
+
var ApiClient = class {
|
|
7817
|
+
constructor(opts) {
|
|
7818
|
+
this.opts = opts;
|
|
7819
|
+
this.fetchImpl = opts.fetchImpl ?? globalThis.fetch;
|
|
7820
|
+
if (!this.fetchImpl) throw new Error("ApiClient: no fetch available");
|
|
7821
|
+
}
|
|
7822
|
+
opts;
|
|
7823
|
+
fetchImpl;
|
|
7824
|
+
async call(name, params, pathParams) {
|
|
7825
|
+
const def = endpoints[name];
|
|
7826
|
+
const merged = {
|
|
7827
|
+
orgId: this.opts.defaultOrgId,
|
|
7828
|
+
...pathParams ?? {}
|
|
7829
|
+
};
|
|
7830
|
+
const url = new URL(buildPath(def.path, merged), this.opts.baseUrl);
|
|
7831
|
+
const init = {
|
|
7832
|
+
method: def.method,
|
|
7833
|
+
headers: {
|
|
7834
|
+
accept: "application/json",
|
|
7835
|
+
// Hosted Fabric API keys use their own header so upstream auth
|
|
7836
|
+
// middleware cannot mistake them for OAuth bearer credentials.
|
|
7837
|
+
...this.opts.apiKey ? { "x-api-key": this.opts.apiKey } : {}
|
|
7838
|
+
},
|
|
7839
|
+
credentials: "include"
|
|
7840
|
+
};
|
|
7841
|
+
if (def.method === "GET" || def.method === "DELETE") {
|
|
7842
|
+
for (const [k, v] of Object.entries(params)) {
|
|
7843
|
+
if (v != null) url.searchParams.set(k, String(v));
|
|
7844
|
+
}
|
|
7845
|
+
} else {
|
|
7846
|
+
init.headers = { ...init.headers, "content-type": "application/json" };
|
|
7847
|
+
init.body = JSON.stringify(params ?? {});
|
|
7848
|
+
}
|
|
7849
|
+
const attempts = this.opts.retry?.attempts ?? 3;
|
|
7850
|
+
const base = this.opts.retry?.baseDelayMs ?? 250;
|
|
7851
|
+
let lastErr;
|
|
7852
|
+
for (let i = 0; i < attempts; i++) {
|
|
7853
|
+
try {
|
|
7854
|
+
const r = await this.fetchImpl(url.toString(), init);
|
|
7855
|
+
if (r.ok) {
|
|
7856
|
+
if (r.status === 204) return void 0;
|
|
7857
|
+
return await r.json();
|
|
7858
|
+
}
|
|
7859
|
+
if (r.status < 500) {
|
|
7860
|
+
const body = await safeJson(r);
|
|
7861
|
+
const err = body?.error;
|
|
7862
|
+
throw new ApiError2(
|
|
7863
|
+
r.status,
|
|
7864
|
+
err?.code ?? "UNKNOWN",
|
|
7865
|
+
err?.message ?? r.statusText,
|
|
7866
|
+
err?.details
|
|
7867
|
+
);
|
|
7868
|
+
}
|
|
7869
|
+
lastErr = new ApiError2(r.status, "INTERNAL", `${r.status} ${r.statusText}`);
|
|
7870
|
+
} catch (e) {
|
|
7871
|
+
if (e instanceof ApiError2 && e.status < 500) throw e;
|
|
7872
|
+
lastErr = e;
|
|
7873
|
+
}
|
|
7874
|
+
await sleep(base * 2 ** i + Math.random() * 100);
|
|
7875
|
+
}
|
|
7876
|
+
throw lastErr;
|
|
7877
|
+
}
|
|
7878
|
+
// ---- Convenience namespaces (typed shortcuts) -----------------------------
|
|
7879
|
+
tenants = {
|
|
7880
|
+
me: () => this.call("tenants.me", {})
|
|
7881
|
+
};
|
|
7882
|
+
experiments = {
|
|
7883
|
+
list: (orgId) => this.call("experiments.list", {}, orgId ? { orgId } : void 0),
|
|
7884
|
+
get: (experimentId, orgId) => this.call("experiments.get", {}, orgId ? { orgId, experimentId } : { experimentId }),
|
|
7885
|
+
invokeAction: (params, orgId) => this.call("experiments.invokeAction", params, orgId ? { orgId } : void 0),
|
|
7886
|
+
aggregate: (experimentId, params, orgId) => this.call(
|
|
7887
|
+
"experiments.aggregate",
|
|
7888
|
+
params,
|
|
7889
|
+
orgId ? { orgId, experimentId } : { experimentId }
|
|
7890
|
+
)
|
|
7891
|
+
};
|
|
7892
|
+
projects = {
|
|
7893
|
+
list: (orgId) => this.call("projects.list", {}, orgId ? { orgId } : void 0),
|
|
7894
|
+
create: (params, orgId) => this.call("projects.create", params, orgId ? { orgId } : void 0)
|
|
7895
|
+
};
|
|
7896
|
+
properties = {
|
|
7897
|
+
list: (projectId, orgId) => this.call("properties.list", {}, orgId ? { orgId, projectId } : { projectId }),
|
|
7898
|
+
create: (projectId, params, orgId) => this.call("properties.create", params, orgId ? { orgId, projectId } : { projectId })
|
|
7899
|
+
};
|
|
7900
|
+
environments = {
|
|
7901
|
+
list: (projectId, orgId) => this.call("environments.list", {}, orgId ? { orgId, projectId } : { projectId }),
|
|
7902
|
+
create: (projectId, params, orgId) => this.call("environments.create", params, orgId ? { orgId, projectId } : { projectId }),
|
|
7903
|
+
publish: (environmentId, orgId) => this.call(
|
|
7904
|
+
"environments.publish",
|
|
7905
|
+
{},
|
|
7906
|
+
orgId ? { orgId, environmentId } : { environmentId }
|
|
7907
|
+
),
|
|
7908
|
+
publications: (environmentId, orgId) => this.call(
|
|
7909
|
+
"environments.publications",
|
|
7910
|
+
{},
|
|
7911
|
+
orgId ? { orgId, environmentId } : { environmentId }
|
|
7912
|
+
),
|
|
7913
|
+
promote: (environmentId, params, orgId) => this.call(
|
|
7914
|
+
"environments.promote",
|
|
7915
|
+
params,
|
|
7916
|
+
orgId ? { orgId, environmentId } : { environmentId }
|
|
7917
|
+
),
|
|
7918
|
+
configuration: (environmentId, orgId) => this.call(
|
|
7919
|
+
"configuration.getPublished",
|
|
7920
|
+
{},
|
|
7921
|
+
orgId ? { orgId, environmentId } : { environmentId }
|
|
7922
|
+
)
|
|
7923
|
+
};
|
|
7924
|
+
features = {
|
|
7925
|
+
list: (projectId, orgId) => this.call("features.list", {}, orgId ? { orgId, projectId } : { projectId }),
|
|
7926
|
+
create: (projectId, params, orgId) => this.call("features.create", params, orgId ? { orgId, projectId } : { projectId })
|
|
7927
|
+
};
|
|
7928
|
+
rules = {
|
|
7929
|
+
list: (featureId, orgId) => this.call("rules.list", {}, orgId ? { orgId, featureId } : { featureId }),
|
|
7930
|
+
create: (featureId, params, orgId) => this.call("rules.create", params, orgId ? { orgId, featureId } : { featureId })
|
|
7931
|
+
};
|
|
7932
|
+
manifests = {
|
|
7933
|
+
publish: (orgId) => this.call("manifests.publish", {}, orgId ? { orgId } : void 0),
|
|
7934
|
+
getKeys: (orgId) => this.call("manifests.getKeys", {}, orgId ? { orgId } : void 0),
|
|
7935
|
+
rotateKey: (keyId, orgId) => this.call("manifests.rotateKey", { keyId }, orgId ? { orgId } : void 0),
|
|
7936
|
+
retireKey: (keyId, orgId) => this.call("manifests.retireKey", { keyId }, orgId ? { orgId } : void 0)
|
|
7937
|
+
};
|
|
7938
|
+
audit = {
|
|
7939
|
+
list: (orgId) => this.call("audit.list", {}, orgId ? { orgId } : void 0)
|
|
7940
|
+
};
|
|
7941
|
+
preview = {
|
|
7942
|
+
sign: (params, orgId) => this.call("preview.sign", params, orgId ? { orgId } : void 0)
|
|
7943
|
+
};
|
|
7944
|
+
apiKeys = {
|
|
7945
|
+
list: (orgId) => this.call("apiKeys.list", {}, orgId ? { orgId } : void 0),
|
|
7946
|
+
create: (params, orgId) => this.call("apiKeys.create", params, orgId ? { orgId } : void 0),
|
|
7947
|
+
revoke: (keyId, orgId) => this.call("apiKeys.revoke", {}, orgId ? { orgId, keyId } : { keyId })
|
|
7948
|
+
};
|
|
7949
|
+
saml = {
|
|
7950
|
+
get: (orgId) => this.call("saml.get", {}, orgId ? { orgId } : void 0),
|
|
7951
|
+
update: (params, orgId) => this.call("saml.update", params, orgId ? { orgId } : void 0)
|
|
7952
|
+
};
|
|
7953
|
+
testRuns = {
|
|
7954
|
+
list: (params = {}, orgId) => this.call("testRuns.list", params, orgId ? { orgId } : void 0),
|
|
7955
|
+
get: (runId, orgId) => this.call("testRuns.get", {}, orgId ? { orgId, runId } : { runId }),
|
|
7956
|
+
create: (params, orgId) => this.call("testRuns.create", params, orgId ? { orgId } : void 0)
|
|
7957
|
+
};
|
|
7958
|
+
};
|
|
7959
|
+
async function safeJson(r) {
|
|
7960
|
+
try {
|
|
7961
|
+
return await r.json();
|
|
7962
|
+
} catch {
|
|
7963
|
+
return null;
|
|
7964
|
+
}
|
|
7965
|
+
}
|
|
7966
|
+
function sleep(ms) {
|
|
7967
|
+
return new Promise((resolve11) => setTimeout(resolve11, ms));
|
|
7968
|
+
}
|
|
7969
|
+
|
|
7970
|
+
// src/commands/preview.ts
|
|
7971
|
+
var LOCAL_SECRET_FILE = "preview-secret";
|
|
7972
|
+
async function cmdPreview(experimentId, options) {
|
|
7973
|
+
if (!options.variantKey) {
|
|
7974
|
+
process.stderr.write(
|
|
7975
|
+
"Usage: fx preview <experimentId> --variant <key> [--ttl 900] [--origin https://...]\n"
|
|
7976
|
+
);
|
|
7977
|
+
return 1;
|
|
7978
|
+
}
|
|
7979
|
+
const tenantId = options.tenantId ?? "default";
|
|
7980
|
+
const ttl = clamp(options.ttlSeconds ?? 900, 60, 3600);
|
|
7981
|
+
const exp = Math.floor(Date.now() / 1e3) + ttl;
|
|
7982
|
+
let token;
|
|
7983
|
+
let signerId;
|
|
7984
|
+
if (options.apiUrl && options.apiKey && !options.local) {
|
|
7985
|
+
const client = new ApiClient({
|
|
7986
|
+
baseUrl: options.apiUrl,
|
|
7987
|
+
apiKey: options.apiKey,
|
|
7988
|
+
defaultOrgId: tenantId
|
|
7989
|
+
});
|
|
7990
|
+
const r = await client.call(
|
|
7991
|
+
"preview.sign",
|
|
7992
|
+
{
|
|
7993
|
+
experimentId,
|
|
7994
|
+
variantKey: options.variantKey,
|
|
7995
|
+
ttlSeconds: ttl
|
|
7996
|
+
},
|
|
7997
|
+
{ orgId: tenantId }
|
|
7998
|
+
);
|
|
7999
|
+
token = r.token;
|
|
8000
|
+
signerId = r.keyId;
|
|
8001
|
+
} else {
|
|
8002
|
+
const ws = await loadWorkspace();
|
|
8003
|
+
const secretFile = path.join(ws.fxDir, LOCAL_SECRET_FILE);
|
|
8004
|
+
let secret;
|
|
8005
|
+
if (fs.existsSync(secretFile)) {
|
|
8006
|
+
secret = new Uint8Array(Buffer.from(fs.readFileSync(secretFile, "utf8"), "hex"));
|
|
8007
|
+
} else {
|
|
8008
|
+
secret = crypto$1.webcrypto.getRandomValues(new Uint8Array(32));
|
|
8009
|
+
fs.writeFileSync(secretFile, Buffer.from(secret).toString("hex"), { mode: 384 });
|
|
8010
|
+
process.stderr.write(`(generated local preview secret at ${secretFile})
|
|
8011
|
+
`);
|
|
8012
|
+
}
|
|
8013
|
+
token = await signHs256(
|
|
8014
|
+
{ experimentId, variantKey: options.variantKey, tenantId, exp },
|
|
8015
|
+
secret
|
|
8016
|
+
);
|
|
8017
|
+
signerId = "local-hs256";
|
|
8018
|
+
}
|
|
8019
|
+
const params = new URLSearchParams({
|
|
8020
|
+
fxpreview: `${experimentId}:${options.variantKey}`,
|
|
8021
|
+
fxtoken: token
|
|
8022
|
+
});
|
|
8023
|
+
const url = options.origin ? `${options.origin.replace(/\/$/, "")}/?${params.toString()}` : `?${params.toString()}`;
|
|
8024
|
+
process.stdout.write(
|
|
8025
|
+
[
|
|
8026
|
+
`Experiment: ${experimentId}`,
|
|
8027
|
+
`Variant: ${options.variantKey}`,
|
|
8028
|
+
`Tenant: ${tenantId}`,
|
|
8029
|
+
`Expires: ${new Date(exp * 1e3).toISOString()} (TTL ${ttl}s)`,
|
|
8030
|
+
`Signer: ${signerId}`,
|
|
8031
|
+
"",
|
|
8032
|
+
url,
|
|
8033
|
+
""
|
|
8034
|
+
].join("\n")
|
|
8035
|
+
);
|
|
8036
|
+
return 0;
|
|
8037
|
+
}
|
|
8038
|
+
function clamp(n, min, max) {
|
|
8039
|
+
if (n < min) return min;
|
|
8040
|
+
if (n > max) return max;
|
|
8041
|
+
return n;
|
|
8042
|
+
}
|
|
8043
|
+
function b64url(bytes) {
|
|
8044
|
+
const data = typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes;
|
|
8045
|
+
return Buffer.from(data).toString("base64url");
|
|
8046
|
+
}
|
|
8047
|
+
async function signHs256(claim, secret) {
|
|
8048
|
+
const header = { alg: "HS256", typ: "JWT" };
|
|
8049
|
+
const h = b64url(JSON.stringify(header));
|
|
8050
|
+
const p = b64url(JSON.stringify(claim));
|
|
8051
|
+
const signing = `${h}.${p}`;
|
|
8052
|
+
const key = await crypto$1.webcrypto.subtle.importKey(
|
|
8053
|
+
"raw",
|
|
8054
|
+
secret,
|
|
8055
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
8056
|
+
false,
|
|
8057
|
+
["sign"]
|
|
8058
|
+
);
|
|
8059
|
+
const sig = new Uint8Array(
|
|
8060
|
+
await crypto$1.webcrypto.subtle.sign("HMAC", key, new TextEncoder().encode(signing))
|
|
8061
|
+
);
|
|
8062
|
+
return `${signing}.${b64url(sig)}`;
|
|
8063
|
+
}
|
|
8064
|
+
async function cmdPush(dir, options = {}) {
|
|
8065
|
+
const apiUrl = options.apiUrl ?? process.env.FX_API_URL;
|
|
8066
|
+
const apiKey = options.apiKey ?? process.env.FX_API_KEY;
|
|
8067
|
+
const tenantId = options.tenantId ?? process.env.FX_ORG_ID ?? "default";
|
|
8068
|
+
if (!apiUrl || !apiKey) {
|
|
8069
|
+
process.stderr.write(
|
|
8070
|
+
"Usage: fx push <dir> --api-url <url> --api-key <key> [--tenant <orgId>]\n"
|
|
8071
|
+
);
|
|
8072
|
+
return 1;
|
|
8073
|
+
}
|
|
8074
|
+
const api = new ApiClient({ baseUrl: apiUrl, apiKey, defaultOrgId: tenantId });
|
|
8075
|
+
const specs = (await loadExperimentDir(path.resolve(dir))).map((s) => s.spec);
|
|
8076
|
+
const summaries = (await api.experiments.list()).experiments;
|
|
8077
|
+
const current = [];
|
|
8078
|
+
for (const summary of summaries) {
|
|
8079
|
+
current.push(await api.experiments.get(summary.id));
|
|
8080
|
+
}
|
|
8081
|
+
const p = plan({
|
|
8082
|
+
specs,
|
|
8083
|
+
current,
|
|
8084
|
+
tenantId,
|
|
8085
|
+
ownerId: options.ownerId ?? "cli",
|
|
8086
|
+
approverId: options.approverId ?? "cli-reviewer",
|
|
8087
|
+
allowDeletes: options.allowDeletes
|
|
8088
|
+
});
|
|
8089
|
+
process.stdout.write(formatPlan(p));
|
|
8090
|
+
process.stdout.write("\n");
|
|
8091
|
+
if (p.blocked.length > 0) {
|
|
8092
|
+
process.stderr.write("\nPush blocked. Resolve the issues above and re-run.\n");
|
|
8093
|
+
return 2;
|
|
8094
|
+
}
|
|
8095
|
+
if (options.dryRun || p.actions.length === 0) return 0;
|
|
8096
|
+
for (const action of p.actions) {
|
|
8097
|
+
const result = await invokeHostedPlanned(
|
|
8098
|
+
api,
|
|
8099
|
+
action,
|
|
8100
|
+
options.ownerId ?? "cli",
|
|
8101
|
+
options.approverId ?? "cli-reviewer"
|
|
8102
|
+
);
|
|
8103
|
+
if (!result.success) throw new Error(`${action.actionId}: ${result.error ?? "failed"}`);
|
|
8104
|
+
}
|
|
8105
|
+
if (options.publish !== false) {
|
|
8106
|
+
const manifest = await api.manifests.publish();
|
|
8107
|
+
process.stdout.write(
|
|
8108
|
+
`
|
|
8109
|
+
Manifest v${manifest.manifestVersion} published (${manifest.experimentCount} live experiment${manifest.experimentCount === 1 ? "" : "s"}).
|
|
8110
|
+
`
|
|
8111
|
+
);
|
|
8112
|
+
}
|
|
8113
|
+
return 0;
|
|
8114
|
+
}
|
|
8115
|
+
async function invokeHostedPlanned(api, action, ownerId, approverId) {
|
|
8116
|
+
if (action.actionId === "experiment.create") {
|
|
8117
|
+
return api.experiments.invokeAction({
|
|
8118
|
+
actionId: "experiment.create",
|
|
8119
|
+
params: { ...action.params.spec, ownerId, tenantId: action.params.tenantId }
|
|
8120
|
+
});
|
|
8121
|
+
}
|
|
8122
|
+
if (action.actionId === "experiment.approve") {
|
|
8123
|
+
return api.experiments.invokeAction({
|
|
8124
|
+
actionId: action.actionId,
|
|
8125
|
+
params: { ...action.params, approverId }
|
|
8126
|
+
});
|
|
8127
|
+
}
|
|
8128
|
+
return api.experiments.invokeAction(action);
|
|
8129
|
+
}
|
|
8130
|
+
var FILES = {
|
|
8131
|
+
"package.json": `${JSON.stringify(
|
|
8132
|
+
{
|
|
8133
|
+
private: true,
|
|
8134
|
+
type: "module",
|
|
8135
|
+
scripts: { test: "cucumber-js", "test:pretty": "cucumber-js --format pretty" },
|
|
8136
|
+
devDependencies: {
|
|
8137
|
+
"@cucumber/cucumber": "^13.0.0",
|
|
8138
|
+
"@duckdb/node-api": "^1.5.0",
|
|
8139
|
+
"@fabricorg/databricks-bdd": "^0.3.1",
|
|
8140
|
+
tsx: "^4.19.2",
|
|
8141
|
+
typescript: "^5.8.3"
|
|
8142
|
+
}
|
|
8143
|
+
},
|
|
8144
|
+
null,
|
|
8145
|
+
2
|
|
8146
|
+
)}
|
|
8147
|
+
`,
|
|
8148
|
+
"cucumber.mjs": `export default {
|
|
8149
|
+
paths: ['features/**/*.feature'],
|
|
8150
|
+
import: ['features/support/steps.ts'],
|
|
8151
|
+
format: [
|
|
8152
|
+
'progress',
|
|
8153
|
+
['junit', 'reports/bdd-junit.xml'],
|
|
8154
|
+
['html', 'reports/bdd.html'],
|
|
8155
|
+
['rerun', 'reports/rerun.txt'],
|
|
8156
|
+
['@fabricorg/databricks-bdd/evidence-formatter', 'reports/evidence.json'],
|
|
8157
|
+
],
|
|
8158
|
+
};
|
|
5995
8159
|
`,
|
|
5996
|
-
|
|
8160
|
+
"features/support/steps.ts": `import '@fabricorg/databricks-bdd/steps';
|
|
8161
|
+
`,
|
|
8162
|
+
"features/databricks.feature": `Feature: Databricks SQL contract
|
|
8163
|
+
|
|
8164
|
+
Scenario: A seeded table is queryable
|
|
8165
|
+
Given catalog "fx_test" and schema "scenarios"
|
|
8166
|
+
And a table "example_events" with:
|
|
8167
|
+
| id | event_name |
|
|
8168
|
+
| 1 | signup |
|
|
8169
|
+
When I query table "example_events"
|
|
8170
|
+
Then the result has 1 rows
|
|
8171
|
+
`,
|
|
8172
|
+
"fixtures/example.json": `${JSON.stringify(
|
|
8173
|
+
{
|
|
8174
|
+
table: "example_events",
|
|
8175
|
+
schema: "id BIGINT, event_name STRING",
|
|
8176
|
+
rows: [[1, "signup"]]
|
|
8177
|
+
},
|
|
8178
|
+
null,
|
|
8179
|
+
2
|
|
8180
|
+
)}
|
|
8181
|
+
`,
|
|
8182
|
+
".env.databricks.example": `DBX_TEST_PROFILE=local
|
|
8183
|
+
# Live runs additionally require DBX_TEST_LIVE=1, DATABRICKS_HOST,
|
|
8184
|
+
# DATABRICKS_WAREHOUSE_ID, DBX_TEST_CATALOG/SCHEMA, and an auth method.
|
|
8185
|
+
`
|
|
8186
|
+
};
|
|
8187
|
+
async function cmdInitDatabricksTests(directory = "databricks-tests", options = {}) {
|
|
8188
|
+
const root = path.resolve(directory);
|
|
8189
|
+
for (const relative of Object.keys(FILES)) {
|
|
8190
|
+
const path$1 = path.join(root, relative);
|
|
8191
|
+
if (!options.force && await exists(path$1)) {
|
|
8192
|
+
throw new Error(`${path$1} already exists; pass --force to overwrite`);
|
|
8193
|
+
}
|
|
8194
|
+
}
|
|
8195
|
+
for (const [relative, contents] of Object.entries(FILES)) {
|
|
8196
|
+
const path$1 = path.join(root, relative);
|
|
8197
|
+
await promises.mkdir(path.join(path$1, ".."), { recursive: true });
|
|
8198
|
+
await promises.writeFile(path$1, contents, "utf8");
|
|
8199
|
+
}
|
|
8200
|
+
process.stdout.write(`Databricks test scaffold written to ${root}
|
|
8201
|
+
`);
|
|
8202
|
+
return 0;
|
|
8203
|
+
}
|
|
8204
|
+
async function exists(path) {
|
|
8205
|
+
try {
|
|
8206
|
+
await promises.access(path);
|
|
8207
|
+
return true;
|
|
8208
|
+
} catch {
|
|
8209
|
+
return false;
|
|
8210
|
+
}
|
|
8211
|
+
}
|
|
8212
|
+
var DEFAULT_STATE = ".fx/databricks-test-environments.json";
|
|
8213
|
+
async function cmdTestEnv(action, options = {}) {
|
|
8214
|
+
const env = options.env ?? process.env;
|
|
8215
|
+
if (env.DBX_TEST_LIVE !== "1") throw new Error("fx test env requires DBX_TEST_LIVE=1");
|
|
8216
|
+
switch (action) {
|
|
8217
|
+
case "create":
|
|
8218
|
+
await createTestEnvironment(options);
|
|
8219
|
+
return 0;
|
|
8220
|
+
case "destroy":
|
|
8221
|
+
await destroyTestEnvironment(options);
|
|
8222
|
+
return 0;
|
|
8223
|
+
case "list":
|
|
8224
|
+
await listTestEnvironments(options);
|
|
8225
|
+
return 0;
|
|
8226
|
+
case "reap":
|
|
8227
|
+
await reapTestEnvironments(options);
|
|
8228
|
+
return 0;
|
|
8229
|
+
default:
|
|
8230
|
+
throw new Error("Usage: fx test env <create|destroy|list|reap> [--name <name>]");
|
|
8231
|
+
}
|
|
8232
|
+
}
|
|
8233
|
+
async function createTestEnvironment(options) {
|
|
8234
|
+
const env = options.env ?? process.env;
|
|
8235
|
+
const name = requireName(options.name);
|
|
8236
|
+
const catalog = validateIdentifier(options.catalog ?? env.DBX_TEST_CATALOG, "catalog");
|
|
8237
|
+
const schema = validateIdentifier(toSchemaName(name), "schema");
|
|
8238
|
+
const statePath = options.statePath ?? DEFAULT_STATE;
|
|
8239
|
+
const state = await readState(statePath);
|
|
8240
|
+
if (state.environments.some((item) => item.name === name)) {
|
|
8241
|
+
throw new Error(`Test environment '${name}' already exists in ${statePath}`);
|
|
8242
|
+
}
|
|
8243
|
+
const ttlMs = parseTtl(options.ttl ?? "24h");
|
|
8244
|
+
const factory = options.contextFactory ?? databricksTestkit.createWorkspaceContext;
|
|
8245
|
+
const admin = await factory({
|
|
8246
|
+
env: { ...env, DBX_TEST_SCHEMA: void 0 },
|
|
8247
|
+
cleanupFixtures: false
|
|
8248
|
+
});
|
|
8249
|
+
let lakebase;
|
|
8250
|
+
try {
|
|
8251
|
+
await admin.exec(`CREATE SCHEMA IF NOT EXISTS ${catalog}.${schema}`);
|
|
8252
|
+
if (options.principal) {
|
|
8253
|
+
const principal = quotePrincipal(options.principal);
|
|
8254
|
+
if (options.grantCatalog !== false) {
|
|
8255
|
+
await admin.exec(`GRANT USE CATALOG ON CATALOG ${catalog} TO ${principal}`);
|
|
8256
|
+
}
|
|
8257
|
+
await admin.exec(
|
|
8258
|
+
`GRANT USE SCHEMA, CREATE TABLE, MODIFY, SELECT ON SCHEMA ${catalog}.${schema} TO ${principal}`
|
|
8259
|
+
);
|
|
8260
|
+
}
|
|
8261
|
+
const expiresAt = new Date(now2(options).getTime() + ttlMs).toISOString();
|
|
8262
|
+
await admin.exec(
|
|
8263
|
+
`ALTER SCHEMA ${catalog}.${schema} SET DBPROPERTIES ('fx.test_env' = 'true', 'fx.expires_at' = '${expiresAt}')`
|
|
5997
8264
|
);
|
|
5998
|
-
|
|
8265
|
+
if (options.seedDir) {
|
|
8266
|
+
const scoped = await factory({
|
|
8267
|
+
env: { ...env, DBX_TEST_CATALOG: catalog, DBX_TEST_SCHEMA: schema },
|
|
8268
|
+
cleanupFixtures: false
|
|
8269
|
+
});
|
|
8270
|
+
try {
|
|
8271
|
+
for (const fixture of await readSeedFixtures(options.seedDir)) {
|
|
8272
|
+
await scoped.loadFixture(fixture);
|
|
8273
|
+
}
|
|
8274
|
+
} finally {
|
|
8275
|
+
await scoped.close();
|
|
8276
|
+
}
|
|
8277
|
+
}
|
|
8278
|
+
if (options.lakebaseBranch) {
|
|
8279
|
+
lakebase = await databricksTestkit.createEphemeralLakebaseBranch({
|
|
8280
|
+
env,
|
|
8281
|
+
...options.lakebaseClient ? { client: options.lakebaseClient } : {},
|
|
8282
|
+
...options.lakebaseProject ? { project: options.lakebaseProject } : {},
|
|
8283
|
+
branchId: databricksTestkit.toLakebaseBranchId(name),
|
|
8284
|
+
ttlMs,
|
|
8285
|
+
now: options.now
|
|
8286
|
+
});
|
|
8287
|
+
}
|
|
8288
|
+
const created = {
|
|
8289
|
+
name,
|
|
8290
|
+
catalog,
|
|
8291
|
+
schema,
|
|
8292
|
+
...options.principal ? { principal: options.principal } : {},
|
|
8293
|
+
createdAt: now2(options).toISOString(),
|
|
8294
|
+
expiresAt,
|
|
8295
|
+
...lakebase ? { lakebase } : {}
|
|
8296
|
+
};
|
|
8297
|
+
state.environments.push(created);
|
|
8298
|
+
await writeState(statePath, state);
|
|
8299
|
+
process.stdout.write(`${JSON.stringify(created)}
|
|
8300
|
+
`);
|
|
8301
|
+
return created;
|
|
8302
|
+
} catch (error) {
|
|
8303
|
+
if (lakebase) {
|
|
8304
|
+
await databricksTestkit.deleteEphemeralLakebaseBranch(lakebase, {
|
|
8305
|
+
env,
|
|
8306
|
+
...options.lakebaseClient ? { client: options.lakebaseClient } : {}
|
|
8307
|
+
}).catch(() => void 0);
|
|
8308
|
+
}
|
|
8309
|
+
await admin.exec(`DROP SCHEMA IF EXISTS ${catalog}.${schema} CASCADE`).catch(() => void 0);
|
|
8310
|
+
throw error;
|
|
8311
|
+
} finally {
|
|
8312
|
+
await admin.close();
|
|
5999
8313
|
}
|
|
6000
8314
|
}
|
|
8315
|
+
async function destroyTestEnvironment(options) {
|
|
8316
|
+
const name = requireName(options.name);
|
|
8317
|
+
const env = options.env ?? process.env;
|
|
8318
|
+
const statePath = options.statePath ?? DEFAULT_STATE;
|
|
8319
|
+
const state = await readState(statePath);
|
|
8320
|
+
const target = state.environments.find((item) => item.name === name);
|
|
8321
|
+
if (!target) throw new Error(`Unknown test environment '${name}'`);
|
|
8322
|
+
const factory = options.contextFactory ?? databricksTestkit.createWorkspaceContext;
|
|
8323
|
+
const admin = await factory({
|
|
8324
|
+
env: { ...env, DBX_TEST_SCHEMA: void 0 },
|
|
8325
|
+
cleanupFixtures: false
|
|
8326
|
+
});
|
|
8327
|
+
try {
|
|
8328
|
+
await admin.exec(`DROP SCHEMA IF EXISTS ${target.catalog}.${target.schema} CASCADE`);
|
|
8329
|
+
if (target.lakebase) {
|
|
8330
|
+
await databricksTestkit.deleteEphemeralLakebaseBranch(target.lakebase, {
|
|
8331
|
+
env,
|
|
8332
|
+
...options.lakebaseClient ? { client: options.lakebaseClient } : {}
|
|
8333
|
+
});
|
|
8334
|
+
}
|
|
8335
|
+
} finally {
|
|
8336
|
+
await admin.close();
|
|
8337
|
+
}
|
|
8338
|
+
state.environments = state.environments.filter((item) => item.name !== name);
|
|
8339
|
+
await writeState(statePath, state);
|
|
8340
|
+
}
|
|
8341
|
+
async function listTestEnvironments(options = {}) {
|
|
8342
|
+
const state = await readState(options.statePath ?? DEFAULT_STATE);
|
|
8343
|
+
for (const item of state.environments) process.stdout.write(`${JSON.stringify(item)}
|
|
8344
|
+
`);
|
|
8345
|
+
return state.environments;
|
|
8346
|
+
}
|
|
8347
|
+
async function reapTestEnvironments(options = {}) {
|
|
8348
|
+
const state = options.remote ? { environments: await discoverRemoteEnvironments(options) } : await readState(options.statePath ?? DEFAULT_STATE);
|
|
8349
|
+
const expired = state.environments.filter(
|
|
8350
|
+
(item) => Date.parse(item.expiresAt) <= now2(options).getTime()
|
|
8351
|
+
);
|
|
8352
|
+
if (options.remote && expired.length > 0) {
|
|
8353
|
+
const env = options.env ?? process.env;
|
|
8354
|
+
const factory = options.contextFactory ?? databricksTestkit.createWorkspaceContext;
|
|
8355
|
+
const admin = await factory({
|
|
8356
|
+
env: { ...env, DBX_TEST_SCHEMA: void 0 },
|
|
8357
|
+
cleanupFixtures: false
|
|
8358
|
+
});
|
|
8359
|
+
try {
|
|
8360
|
+
for (const item of expired) {
|
|
8361
|
+
await admin.exec(`DROP SCHEMA IF EXISTS ${item.catalog}.${item.schema} CASCADE`);
|
|
8362
|
+
}
|
|
8363
|
+
} finally {
|
|
8364
|
+
await admin.close();
|
|
8365
|
+
}
|
|
8366
|
+
} else {
|
|
8367
|
+
for (const item of expired) await destroyTestEnvironment({ ...options, name: item.name });
|
|
8368
|
+
}
|
|
8369
|
+
return expired.map((item) => item.name);
|
|
8370
|
+
}
|
|
8371
|
+
async function discoverRemoteEnvironments(options = {}) {
|
|
8372
|
+
const env = options.env ?? process.env;
|
|
8373
|
+
const catalog = validateIdentifier(options.catalog ?? env.DBX_TEST_CATALOG, "catalog");
|
|
8374
|
+
const factory = options.contextFactory ?? databricksTestkit.createWorkspaceContext;
|
|
8375
|
+
const admin = await factory({
|
|
8376
|
+
env: { ...env, DBX_TEST_SCHEMA: void 0 },
|
|
8377
|
+
cleanupFixtures: false
|
|
8378
|
+
});
|
|
8379
|
+
try {
|
|
8380
|
+
const schemas = await admin.query(`SHOW SCHEMAS IN ${catalog} LIKE 'fx_*'`);
|
|
8381
|
+
const found = [];
|
|
8382
|
+
for (const row of schemas) {
|
|
8383
|
+
const schema = String(row.databaseName ?? row.namespace ?? row.schemaName ?? "");
|
|
8384
|
+
if (!/^fx_[A-Za-z0-9_]+$/.test(schema)) continue;
|
|
8385
|
+
const description = await admin.query(`DESCRIBE SCHEMA EXTENDED ${catalog}.${schema}`);
|
|
8386
|
+
const properties = description.map((item) => String(item.database_description_value ?? item.info_value ?? "")).join(" ");
|
|
8387
|
+
const expiresAt = properties.match(
|
|
8388
|
+
/fx\.expires_at[^0-9]*(\d{4}-\d{2}-\d{2}T[^'"),\]]+)/
|
|
8389
|
+
)?.[1];
|
|
8390
|
+
if (!expiresAt || Number.isNaN(Date.parse(expiresAt))) continue;
|
|
8391
|
+
found.push({
|
|
8392
|
+
name: schema.replace(/^fx_/, "").replaceAll("_", "-"),
|
|
8393
|
+
catalog,
|
|
8394
|
+
schema,
|
|
8395
|
+
createdAt: "",
|
|
8396
|
+
expiresAt
|
|
8397
|
+
});
|
|
8398
|
+
}
|
|
8399
|
+
return found;
|
|
8400
|
+
} finally {
|
|
8401
|
+
await admin.close();
|
|
8402
|
+
}
|
|
8403
|
+
}
|
|
8404
|
+
function now2(options) {
|
|
8405
|
+
return options.now?.() ?? /* @__PURE__ */ new Date();
|
|
8406
|
+
}
|
|
8407
|
+
function requireName(value) {
|
|
8408
|
+
if (!value) throw new Error("Test environment name is required (--name <name>)");
|
|
8409
|
+
if (!/^[A-Za-z0-9_-]+$/.test(value)) throw new Error(`Invalid test environment name '${value}'`);
|
|
8410
|
+
return value;
|
|
8411
|
+
}
|
|
8412
|
+
function toSchemaName(name) {
|
|
8413
|
+
const normalized = name.toLowerCase().replaceAll("-", "_");
|
|
8414
|
+
return normalized.startsWith("fx_") ? normalized : `fx_${normalized}`;
|
|
8415
|
+
}
|
|
8416
|
+
function validateIdentifier(value, label) {
|
|
8417
|
+
if (!value || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) {
|
|
8418
|
+
throw new Error(`A safe ${label} identifier is required, got '${value ?? ""}'`);
|
|
8419
|
+
}
|
|
8420
|
+
return value;
|
|
8421
|
+
}
|
|
8422
|
+
function quotePrincipal(value) {
|
|
8423
|
+
if (!value || value.includes("`")) {
|
|
8424
|
+
throw new Error("Principal must be non-empty and cannot contain backticks");
|
|
8425
|
+
}
|
|
8426
|
+
return `\`${value}\``;
|
|
8427
|
+
}
|
|
8428
|
+
function parseTtl(value) {
|
|
8429
|
+
const match = value.match(/^(\d+)(m|h|d)$/);
|
|
8430
|
+
if (!match) throw new Error(`TTL must look like 30m, 24h, or 7d; got '${value}'`);
|
|
8431
|
+
const amount = Number(match[1]);
|
|
8432
|
+
const unit = match[2];
|
|
8433
|
+
return amount * (unit === "m" ? 6e4 : unit === "h" ? 36e5 : 864e5);
|
|
8434
|
+
}
|
|
8435
|
+
async function readSeedFixtures(directory) {
|
|
8436
|
+
const files = (await promises.readdir(directory)).filter((file) => file.endsWith(".json")).sort();
|
|
8437
|
+
const fixtures = [];
|
|
8438
|
+
for (const file of files) {
|
|
8439
|
+
const parsed = JSON.parse(await promises.readFile(path.join(directory, file), "utf8"));
|
|
8440
|
+
fixtures.push(...Array.isArray(parsed) ? parsed : [parsed]);
|
|
8441
|
+
}
|
|
8442
|
+
return fixtures;
|
|
8443
|
+
}
|
|
8444
|
+
async function readState(path) {
|
|
8445
|
+
try {
|
|
8446
|
+
return JSON.parse(await promises.readFile(path, "utf8"));
|
|
8447
|
+
} catch (error) {
|
|
8448
|
+
if (error.code === "ENOENT") {
|
|
8449
|
+
return { schemaVersion: 1, environments: [] };
|
|
8450
|
+
}
|
|
8451
|
+
throw error;
|
|
8452
|
+
}
|
|
8453
|
+
}
|
|
8454
|
+
async function writeState(path$1, state) {
|
|
8455
|
+
await promises.mkdir(path.dirname(path$1), { recursive: true });
|
|
8456
|
+
await promises.writeFile(path$1, `${JSON.stringify(state, null, 2)}
|
|
8457
|
+
`, "utf8");
|
|
8458
|
+
}
|
|
8459
|
+
async function cmdTestPublish(evidencePath, options = {}) {
|
|
8460
|
+
const env = options.env ?? process.env;
|
|
8461
|
+
const apiUrl = options.apiUrl ?? env.FX_API_URL;
|
|
8462
|
+
const apiKey = options.apiKey ?? env.FX_API_KEY;
|
|
8463
|
+
const tenantId = options.tenantId ?? env.FX_ORG_ID;
|
|
8464
|
+
if (!apiUrl || !apiKey || !tenantId) {
|
|
8465
|
+
process.stderr.write(
|
|
8466
|
+
"Usage: fx test publish <evidence.json> --api-url <url> --api-key <key> --tenant <orgId>\n"
|
|
8467
|
+
);
|
|
8468
|
+
return 1;
|
|
8469
|
+
}
|
|
8470
|
+
const evidence = parseEvidenceText(await promises.readFile(path.resolve(evidencePath), "utf8"));
|
|
8471
|
+
const input = normalizeTestEvidence(evidence, { ...options, env });
|
|
8472
|
+
const api = new ApiClient({ baseUrl: apiUrl, apiKey, defaultOrgId: tenantId });
|
|
8473
|
+
const created = await api.testRuns.create(input);
|
|
8474
|
+
process.stdout.write(
|
|
8475
|
+
`Published ${created.source} run ${created.id}: ${created.status} (${created.summary.passed}/${created.summary.total} passed)
|
|
8476
|
+
`
|
|
8477
|
+
);
|
|
8478
|
+
return 0;
|
|
8479
|
+
}
|
|
8480
|
+
function normalizeTestEvidence(value, options = {}) {
|
|
8481
|
+
if (!value || typeof value !== "object") throw new Error("Evidence must be a JSON object");
|
|
8482
|
+
const evidence = value;
|
|
8483
|
+
const env = options.env ?? process.env;
|
|
8484
|
+
const kind = String(evidence.kind ?? "");
|
|
8485
|
+
const revision = compact({
|
|
8486
|
+
repository: env.GITHUB_REPOSITORY,
|
|
8487
|
+
sha: env.GITHUB_SHA,
|
|
8488
|
+
branch: env.GITHUB_REF_NAME,
|
|
8489
|
+
runId: env.GITHUB_RUN_ID,
|
|
8490
|
+
runAttempt: env.GITHUB_RUN_ATTEMPT,
|
|
8491
|
+
runUrl: options.runUrl ?? (env.GITHUB_SERVER_URL && env.GITHUB_REPOSITORY && env.GITHUB_RUN_ID ? `${env.GITHUB_SERVER_URL}/${env.GITHUB_REPOSITORY}/actions/runs/${env.GITHUB_RUN_ID}` : void 0)
|
|
8492
|
+
});
|
|
8493
|
+
const artifacts = typeof revision.runUrl === "string" ? [{ name: "CI run", url: revision.runUrl, mediaType: "text/html" }] : [];
|
|
8494
|
+
const externalId = options.externalId ?? (env.GITHUB_REPOSITORY && env.GITHUB_RUN_ID ? `${kind}:${env.GITHUB_REPOSITORY}:${env.GITHUB_RUN_ID}:${env.GITHUB_RUN_ATTEMPT ?? "1"}` : void 0);
|
|
8495
|
+
if (kind === "databricks-bdd") {
|
|
8496
|
+
const cases = arrayOfRecords(evidence.scenarios).map((scenario, index) => {
|
|
8497
|
+
const failures = arrayOfRecords(scenario.failures);
|
|
8498
|
+
const statementId = failures.find((failure) => typeof failure.statementId === "string")?.statementId;
|
|
8499
|
+
return {
|
|
8500
|
+
id: `${scenario.uri ?? "scenario"}:${index}`,
|
|
8501
|
+
name: String(scenario.name ?? `Scenario ${index + 1}`),
|
|
8502
|
+
...typeof scenario.uri === "string" ? { uri: scenario.uri } : {},
|
|
8503
|
+
status: normalizeCaseStatus(scenario.status),
|
|
8504
|
+
durationMs: nonnegativeNumber(scenario.durationMs),
|
|
8505
|
+
tags: Array.isArray(scenario.tags) ? scenario.tags.map(String) : [],
|
|
8506
|
+
...typeof scenario.error === "string" ? { error: scenario.error } : {},
|
|
8507
|
+
...statementId ? { statementId } : {},
|
|
8508
|
+
...statementId && env.DATABRICKS_HOST ? {
|
|
8509
|
+
resourceUrl: `${env.DATABRICKS_HOST.replace(/\/$/, "")}/sql/history?uuid=${encodeURIComponent(statementId)}`
|
|
8510
|
+
} : {},
|
|
8511
|
+
...failures.length > 0 ? { details: { failures } } : {}
|
|
8512
|
+
};
|
|
8513
|
+
});
|
|
8514
|
+
const summary = summarize(cases);
|
|
8515
|
+
return {
|
|
8516
|
+
...externalId ? { externalId } : {},
|
|
8517
|
+
source: "bdd",
|
|
8518
|
+
suite: options.suite ?? "Databricks BDD",
|
|
8519
|
+
status: evidence.success === false ? "failed" : summary.total === summary.skipped ? "skipped" : "passed",
|
|
8520
|
+
startedAt: null,
|
|
8521
|
+
finishedAt: isoOrNull(evidence.finishedAt),
|
|
8522
|
+
durationMs: cases.reduce((sum, item) => sum + item.durationMs, 0),
|
|
8523
|
+
summary,
|
|
8524
|
+
environment: compact({ profile: evidence.profile }),
|
|
8525
|
+
revision,
|
|
8526
|
+
cases,
|
|
8527
|
+
artifacts
|
|
8528
|
+
};
|
|
8529
|
+
}
|
|
8530
|
+
if (kind === "databricks-live-suite") {
|
|
8531
|
+
const cases = arrayOfRecords(evidence.results).map((result) => ({
|
|
8532
|
+
id: String(result.id ?? ""),
|
|
8533
|
+
name: String(result.description ?? result.id ?? "Live check"),
|
|
8534
|
+
status: result.status === "pass" ? "passed" : result.status === "fail" ? "failed" : "skipped",
|
|
8535
|
+
durationMs: nonnegativeNumber(result.durationMs),
|
|
8536
|
+
tags: [],
|
|
8537
|
+
...typeof result.error === "string" ? { error: result.error } : {},
|
|
8538
|
+
...result.details && typeof result.details === "object" ? { details: result.details } : {}
|
|
8539
|
+
}));
|
|
8540
|
+
const summary = summarize(cases);
|
|
8541
|
+
return {
|
|
8542
|
+
...externalId ? { externalId } : {},
|
|
8543
|
+
source: "live-suite",
|
|
8544
|
+
suite: options.suite ?? "Databricks live suite",
|
|
8545
|
+
status: evidence.success === false ? "failed" : "passed",
|
|
8546
|
+
startedAt: isoOrNull(evidence.startedAt),
|
|
8547
|
+
finishedAt: isoOrNull(evidence.finishedAt),
|
|
8548
|
+
durationMs: cases.reduce((sum, item) => sum + item.durationMs, 0),
|
|
8549
|
+
summary,
|
|
8550
|
+
environment: compact({
|
|
8551
|
+
profile: "live",
|
|
8552
|
+
cloud: env.DBX_TEST_CLOUD ?? "azure",
|
|
8553
|
+
workspace: env.DATABRICKS_HOST,
|
|
8554
|
+
warehouseId: env.DATABRICKS_WAREHOUSE_ID,
|
|
8555
|
+
runtime: env.DBX_TEST_RUNTIME_VERSION,
|
|
8556
|
+
compute: env.DBX_TEST_COMPUTE
|
|
8557
|
+
}),
|
|
8558
|
+
revision,
|
|
8559
|
+
cases,
|
|
8560
|
+
artifacts
|
|
8561
|
+
};
|
|
8562
|
+
}
|
|
8563
|
+
if (kind === "junit") {
|
|
8564
|
+
const cases = arrayOfRecords(evidence.cases).map((testCase, index) => ({
|
|
8565
|
+
id: String(testCase.id ?? `junit:${index}`),
|
|
8566
|
+
name: String(testCase.name ?? `Test ${index + 1}`),
|
|
8567
|
+
...typeof testCase.uri === "string" ? { uri: testCase.uri } : {},
|
|
8568
|
+
status: normalizeCaseStatus(testCase.status),
|
|
8569
|
+
durationMs: nonnegativeNumber(testCase.durationMs),
|
|
8570
|
+
tags: [],
|
|
8571
|
+
...typeof testCase.error === "string" ? { error: testCase.error } : {}
|
|
8572
|
+
}));
|
|
8573
|
+
const summary = summarize(cases);
|
|
8574
|
+
return {
|
|
8575
|
+
...externalId ? { externalId } : {},
|
|
8576
|
+
source: "junit",
|
|
8577
|
+
suite: options.suite ?? String(evidence.suite ?? "JUnit test suite"),
|
|
8578
|
+
status: summary.failed > 0 ? "failed" : summary.total === summary.skipped ? "skipped" : "passed",
|
|
8579
|
+
startedAt: null,
|
|
8580
|
+
finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
8581
|
+
durationMs: cases.reduce((sum, item) => sum + item.durationMs, 0),
|
|
8582
|
+
summary,
|
|
8583
|
+
environment: compact({ profile: env.DBX_TEST_PROFILE, workspace: env.DATABRICKS_HOST }),
|
|
8584
|
+
revision,
|
|
8585
|
+
cases,
|
|
8586
|
+
artifacts
|
|
8587
|
+
};
|
|
8588
|
+
}
|
|
8589
|
+
throw new Error(`Unsupported evidence kind '${kind || "(missing)"}'`);
|
|
8590
|
+
}
|
|
8591
|
+
function parseEvidenceText(text) {
|
|
8592
|
+
if (!text.trimStart().startsWith("<")) return JSON.parse(text);
|
|
8593
|
+
const parsed = new fastXmlParser.XMLParser({ ignoreAttributes: false, attributeNamePrefix: "@_" }).parse(
|
|
8594
|
+
text
|
|
8595
|
+
);
|
|
8596
|
+
const suites = collectSuites(parsed.testsuites ?? parsed.testsuite);
|
|
8597
|
+
const cases = suites.flatMap(
|
|
8598
|
+
(suite, suiteIndex) => asRecords(suite.testcase).map((testCase, caseIndex) => {
|
|
8599
|
+
const failure = testCase.failure ?? testCase.error;
|
|
8600
|
+
const skipped = testCase.skipped;
|
|
8601
|
+
const error = xmlText(failure);
|
|
8602
|
+
return {
|
|
8603
|
+
id: `${suite["@_name"] ?? suiteIndex}:${testCase["@_name"] ?? caseIndex}`,
|
|
8604
|
+
name: String(testCase["@_name"] ?? `Test ${caseIndex + 1}`),
|
|
8605
|
+
uri: String(testCase["@_classname"] ?? suite["@_name"] ?? ""),
|
|
8606
|
+
status: failure ? "failed" : skipped ? "skipped" : "passed",
|
|
8607
|
+
durationMs: Math.round(Number(testCase["@_time"] ?? 0) * 1e3),
|
|
8608
|
+
...error ? { error } : {}
|
|
8609
|
+
};
|
|
8610
|
+
})
|
|
8611
|
+
);
|
|
8612
|
+
return {
|
|
8613
|
+
kind: "junit",
|
|
8614
|
+
suite: suites.map((suite) => String(suite["@_name"] ?? "")).filter(Boolean).join(", "),
|
|
8615
|
+
cases
|
|
8616
|
+
};
|
|
8617
|
+
}
|
|
8618
|
+
function summarize(cases) {
|
|
8619
|
+
return {
|
|
8620
|
+
total: cases.length,
|
|
8621
|
+
passed: cases.filter((item) => item.status === "passed").length,
|
|
8622
|
+
failed: cases.filter((item) => item.status === "failed").length,
|
|
8623
|
+
skipped: cases.filter((item) => item.status === "skipped").length,
|
|
8624
|
+
pending: cases.filter((item) => item.status === "pending" || item.status === "undefined").length
|
|
8625
|
+
};
|
|
8626
|
+
}
|
|
8627
|
+
function normalizeCaseStatus(value) {
|
|
8628
|
+
const status = String(value ?? "unknown").toLowerCase();
|
|
8629
|
+
if (["passed", "failed", "skipped", "pending", "undefined"].includes(status)) {
|
|
8630
|
+
return status;
|
|
8631
|
+
}
|
|
8632
|
+
return "unknown";
|
|
8633
|
+
}
|
|
8634
|
+
function arrayOfRecords(value) {
|
|
8635
|
+
return Array.isArray(value) ? value.filter(
|
|
8636
|
+
(item) => Boolean(item && typeof item === "object")
|
|
8637
|
+
) : [];
|
|
8638
|
+
}
|
|
8639
|
+
function collectSuites(value) {
|
|
8640
|
+
return asRecords(value).flatMap((item) => [
|
|
8641
|
+
...item.testcase ? [item] : [],
|
|
8642
|
+
...collectSuites(item.testsuite)
|
|
8643
|
+
]);
|
|
8644
|
+
}
|
|
8645
|
+
function asRecords(value) {
|
|
8646
|
+
if (Array.isArray(value)) {
|
|
8647
|
+
return value.filter(
|
|
8648
|
+
(item) => Boolean(item && typeof item === "object")
|
|
8649
|
+
);
|
|
8650
|
+
}
|
|
8651
|
+
return value && typeof value === "object" ? [value] : [];
|
|
8652
|
+
}
|
|
8653
|
+
function xmlText(value) {
|
|
8654
|
+
if (typeof value === "string") return value;
|
|
8655
|
+
if (value && typeof value === "object") {
|
|
8656
|
+
const record = value;
|
|
8657
|
+
const message = [record["@_message"], record["#text"]].filter(Boolean).map(String).join("\n");
|
|
8658
|
+
return message || void 0;
|
|
8659
|
+
}
|
|
8660
|
+
return void 0;
|
|
8661
|
+
}
|
|
8662
|
+
function compact(value) {
|
|
8663
|
+
return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
|
|
8664
|
+
}
|
|
8665
|
+
function nonnegativeNumber(value) {
|
|
8666
|
+
const number = Number(value ?? 0);
|
|
8667
|
+
return Number.isFinite(number) && number >= 0 ? Math.round(number) : 0;
|
|
8668
|
+
}
|
|
8669
|
+
function isoOrNull(value) {
|
|
8670
|
+
if (typeof value !== "string" || Number.isNaN(Date.parse(value))) return null;
|
|
8671
|
+
return new Date(value).toISOString();
|
|
8672
|
+
}
|
|
6001
8673
|
|
|
6002
8674
|
// src/bin/fx.ts
|
|
6003
8675
|
var HELP = `fx \u2014 Fabric Experiments CLI
|
|
@@ -6008,11 +8680,17 @@ USAGE
|
|
|
6008
8680
|
COMMANDS
|
|
6009
8681
|
validate <dir> Lint experiment YAML files in <dir>.
|
|
6010
8682
|
plan <dir> Show diff between YAML and live control plane.
|
|
6011
|
-
apply <dir> Apply YAML to the control plane (idempotent).
|
|
8683
|
+
apply <dir> Apply YAML to the local control plane (idempotent).
|
|
8684
|
+
push <dir> Push YAML to the hosted API and publish manifest.
|
|
6012
8685
|
dev Start local dev server (manifest + exposure ingest).
|
|
6013
8686
|
publish Sign current manifest; optionally push to manifest-worker.
|
|
6014
8687
|
report <experimentId> Print frequentist results for an experiment.
|
|
6015
8688
|
kill <experimentId> Kill a running experiment. Requires --reason.
|
|
8689
|
+
import-mojito <dir> Import a directory of Mojito waves into Fabric YAML.
|
|
8690
|
+
preview <experimentId> Mint a signed preview link for a variant. Requires --variant.
|
|
8691
|
+
test env <action> Create, destroy, list, or reap Databricks test environments.
|
|
8692
|
+
test publish <file> Publish BDD/live evidence to Studio Quality.
|
|
8693
|
+
init databricks-tests Scaffold a Databricks BDD test project.
|
|
6016
8694
|
|
|
6017
8695
|
GLOBAL FLAGS
|
|
6018
8696
|
--tenant <id> Tenant scope (default: default)
|
|
@@ -6021,17 +8699,31 @@ GLOBAL FLAGS
|
|
|
6021
8699
|
--reason <text> kill reason
|
|
6022
8700
|
--owner <id> apply owner id
|
|
6023
8701
|
--approver <id> apply approver id
|
|
6024
|
-
--dry-run apply: do not mutate
|
|
6025
|
-
--allow-deletes apply/plan: allow killing experiments removed from YAML
|
|
8702
|
+
--dry-run apply/push: do not mutate
|
|
8703
|
+
--allow-deletes apply/plan/push: allow killing experiments removed from YAML
|
|
6026
8704
|
--json plan: emit machine-readable output
|
|
6027
8705
|
--remote-url <url> publish: post to a manifest-worker
|
|
6028
8706
|
--admin-token <tok> publish: bearer token for --remote-url
|
|
8707
|
+
--static <dir> publish: write signed manifest + tag-loader bundle to <dir>
|
|
8708
|
+
--api-url <url> push/preview: hosted API base URL
|
|
8709
|
+
--api-key <key> push/preview: hosted API key
|
|
8710
|
+
--no-publish push: apply actions without publishing manifest
|
|
8711
|
+
--name <name> test env: environment name (for example pr-1234)
|
|
8712
|
+
--seed <dir> test env create: JSON fixture directory
|
|
8713
|
+
--ttl <duration> test env create: lifetime such as 24h or 7d
|
|
8714
|
+
--principal <id> test env create: principal receiving scoped grants
|
|
8715
|
+
--skip-catalog-grant principal already has USE CATALOG (least-privilege bootstrap)
|
|
8716
|
+
--lakebase-branch test env create: clone a TTL-scoped Lakebase branch
|
|
8717
|
+
--lakebase-project <name> Lakebase project resource (projects/<id>)
|
|
8718
|
+
--suite <name> test publish: display name for the suite
|
|
8719
|
+
--external-id <id> test publish: idempotent CI run identifier
|
|
8720
|
+
--run-url <url> test publish: CI artifact/run link
|
|
6029
8721
|
--key-id <id> publish: keyId to sign with (default: dev-default)
|
|
6030
8722
|
-h, --help print this help
|
|
6031
8723
|
-v, --version print version
|
|
6032
8724
|
`;
|
|
6033
|
-
var VERSION2 = "0.
|
|
6034
|
-
function
|
|
8725
|
+
var VERSION2 = "0.6.1";
|
|
8726
|
+
function parse2(argv) {
|
|
6035
8727
|
const positional = [];
|
|
6036
8728
|
const flags = {};
|
|
6037
8729
|
let command = "";
|
|
@@ -6065,7 +8757,7 @@ function parse(argv) {
|
|
|
6065
8757
|
return { command, positional, flags };
|
|
6066
8758
|
}
|
|
6067
8759
|
async function main() {
|
|
6068
|
-
const args =
|
|
8760
|
+
const args = parse2(process.argv.slice(2));
|
|
6069
8761
|
if (args.flags.h || args.flags.help) {
|
|
6070
8762
|
process.stdout.write(HELP);
|
|
6071
8763
|
return 0;
|
|
@@ -6100,6 +8792,17 @@ async function main() {
|
|
|
6100
8792
|
dryRun: args.flags["dry-run"] === true,
|
|
6101
8793
|
allowDeletes
|
|
6102
8794
|
});
|
|
8795
|
+
case "push":
|
|
8796
|
+
return cmdPush(args.positional[0] ?? ".", {
|
|
8797
|
+
tenantId,
|
|
8798
|
+
ownerId: args.flags.owner,
|
|
8799
|
+
approverId: args.flags.approver,
|
|
8800
|
+
dryRun: args.flags["dry-run"] === true,
|
|
8801
|
+
allowDeletes,
|
|
8802
|
+
apiUrl: args.flags["api-url"],
|
|
8803
|
+
apiKey: args.flags["api-key"],
|
|
8804
|
+
publish: args.flags["no-publish"] !== true
|
|
8805
|
+
});
|
|
6103
8806
|
case "dev":
|
|
6104
8807
|
return cmdDev({
|
|
6105
8808
|
port: args.flags.port ? Number(args.flags.port) : void 0,
|
|
@@ -6110,7 +8813,8 @@ async function main() {
|
|
|
6110
8813
|
tenantId,
|
|
6111
8814
|
remoteUrl: args.flags["remote-url"],
|
|
6112
8815
|
adminToken: args.flags["admin-token"],
|
|
6113
|
-
keyId: args.flags["key-id"]
|
|
8816
|
+
keyId: args.flags["key-id"],
|
|
8817
|
+
staticDir: args.flags.static
|
|
6114
8818
|
});
|
|
6115
8819
|
case "report":
|
|
6116
8820
|
if (!args.positional[0]) {
|
|
@@ -6130,18 +8834,83 @@ async function main() {
|
|
|
6130
8834
|
tenantId,
|
|
6131
8835
|
reason: typeof args.flags.reason === "string" ? args.flags.reason : ""
|
|
6132
8836
|
});
|
|
8837
|
+
case "import-mojito":
|
|
8838
|
+
if (!args.positional[0]) {
|
|
8839
|
+
process.stderr.write("Usage: fx import-mojito <dir> [--out <out-dir>]\n");
|
|
8840
|
+
return 1;
|
|
8841
|
+
}
|
|
8842
|
+
return cmdImportMojito(args.positional[0], {
|
|
8843
|
+
outputDir: args.flags.out});
|
|
8844
|
+
case "preview":
|
|
8845
|
+
if (!args.positional[0]) {
|
|
8846
|
+
process.stderr.write(
|
|
8847
|
+
"Usage: fx preview <experimentId> --variant <key> [--ttl 900] [--origin https://...] [--api-url ... --api-key ...]\n"
|
|
8848
|
+
);
|
|
8849
|
+
return 1;
|
|
8850
|
+
}
|
|
8851
|
+
return cmdPreview(args.positional[0], {
|
|
8852
|
+
tenantId,
|
|
8853
|
+
variantKey: typeof args.flags.variant === "string" ? args.flags.variant : "",
|
|
8854
|
+
ttlSeconds: args.flags.ttl ? Number(args.flags.ttl) : void 0,
|
|
8855
|
+
origin: args.flags.origin,
|
|
8856
|
+
apiUrl: args.flags["api-url"],
|
|
8857
|
+
apiKey: args.flags["api-key"],
|
|
8858
|
+
local: args.flags.local === true
|
|
8859
|
+
});
|
|
8860
|
+
case "test":
|
|
8861
|
+
if (args.positional[0] === "publish") {
|
|
8862
|
+
if (!args.positional[1]) {
|
|
8863
|
+
process.stderr.write("Usage: fx test publish <evidence.json> [flags]\n");
|
|
8864
|
+
return 1;
|
|
8865
|
+
}
|
|
8866
|
+
return cmdTestPublish(args.positional[1], {
|
|
8867
|
+
tenantId,
|
|
8868
|
+
apiUrl: args.flags["api-url"],
|
|
8869
|
+
apiKey: args.flags["api-key"],
|
|
8870
|
+
suite: args.flags.suite,
|
|
8871
|
+
externalId: args.flags["external-id"],
|
|
8872
|
+
runUrl: args.flags["run-url"]
|
|
8873
|
+
});
|
|
8874
|
+
}
|
|
8875
|
+
if (args.positional[0] !== "env") {
|
|
8876
|
+
process.stderr.write("Usage: fx test <env|publish> [args] [flags]\n");
|
|
8877
|
+
return 1;
|
|
8878
|
+
}
|
|
8879
|
+
return cmdTestEnv(args.positional[1] ?? "", {
|
|
8880
|
+
name: args.flags.name,
|
|
8881
|
+
catalog: args.flags.catalog,
|
|
8882
|
+
principal: args.flags.principal,
|
|
8883
|
+
grantCatalog: args.flags["skip-catalog-grant"] !== true,
|
|
8884
|
+
seedDir: args.flags.seed,
|
|
8885
|
+
ttl: args.flags.ttl,
|
|
8886
|
+
lakebaseBranch: args.flags["lakebase-branch"] === true,
|
|
8887
|
+
lakebaseProject: args.flags["lakebase-project"],
|
|
8888
|
+
remote: args.flags.remote === true
|
|
8889
|
+
});
|
|
8890
|
+
case "init":
|
|
8891
|
+
if (args.positional[0] !== "databricks-tests") {
|
|
8892
|
+
process.stderr.write("Usage: fx init databricks-tests [dir] [--force]\n");
|
|
8893
|
+
return 1;
|
|
8894
|
+
}
|
|
8895
|
+
return cmdInitDatabricksTests(args.positional[1], { force: args.flags.force === true });
|
|
6133
8896
|
default:
|
|
6134
8897
|
process.stderr.write(`Unknown command: ${args.command}
|
|
6135
8898
|
${HELP}`);
|
|
6136
8899
|
return 1;
|
|
6137
8900
|
}
|
|
6138
8901
|
}
|
|
6139
|
-
|
|
6140
|
-
|
|
6141
|
-
|
|
6142
|
-
|
|
8902
|
+
var isMain = process.argv[1] && path.resolve(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('fx.cjs', document.baseURI).href)))) === path.resolve(fs.realpathSync(process.argv[1]));
|
|
8903
|
+
if (isMain) {
|
|
8904
|
+
main().then((code) => {
|
|
8905
|
+
process.exit(code);
|
|
8906
|
+
}).catch((e) => {
|
|
8907
|
+
process.stderr.write(`fx: ${e.stack ?? e}
|
|
6143
8908
|
`);
|
|
6144
|
-
|
|
6145
|
-
});
|
|
8909
|
+
process.exit(1);
|
|
8910
|
+
});
|
|
8911
|
+
}
|
|
8912
|
+
|
|
8913
|
+
exports.main = main;
|
|
8914
|
+
exports.parse = parse2;
|
|
6146
8915
|
//# sourceMappingURL=fx.cjs.map
|
|
6147
8916
|
//# sourceMappingURL=fx.cjs.map
|