@hogsend/engine 0.46.0 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +6 -0
  2. package/package.json +13 -10
  3. package/src/connectors/presets/index.ts +8 -2
  4. package/src/container.ts +149 -7
  5. package/src/destinations/presets/posthog.ts +7 -0
  6. package/src/destinations/presets/segment.ts +5 -0
  7. package/src/env.ts +38 -0
  8. package/src/flags/reconcile.ts +195 -0
  9. package/src/index.ts +79 -0
  10. package/src/journeys/authoring.ts +32 -0
  11. package/src/journeys/define-journey.ts +45 -40
  12. package/src/journeys/execute-journey-run.ts +73 -32
  13. package/src/journeys/journey-boundary.ts +76 -0
  14. package/src/journeys/journey-context.ts +128 -70
  15. package/src/journeys/journey-task-factory.ts +31 -0
  16. package/src/journeys/journey-task-runtime.ts +31 -0
  17. package/src/journeys/journey-version.test.ts +236 -0
  18. package/src/journeys/journey-version.ts +158 -0
  19. package/src/journeys/record-once.ts +28 -2
  20. package/src/lib/connector-actions.test.ts +36 -0
  21. package/src/lib/connector-actions.ts +42 -4
  22. package/src/lib/contacts.ts +49 -0
  23. package/src/lib/conversions.test.ts +33 -0
  24. package/src/lib/conversions.ts +8 -0
  25. package/src/lib/email.ts +23 -2
  26. package/src/lib/enrollment-policy.ts +51 -0
  27. package/src/lib/feed.ts +55 -3
  28. package/src/lib/flags-registry.ts +48 -0
  29. package/src/lib/flags.ts +498 -0
  30. package/src/lib/fx.ts +374 -0
  31. package/src/lib/global-control-readout.ts +166 -0
  32. package/src/lib/groups.ts +362 -0
  33. package/src/lib/ingestion.ts +38 -0
  34. package/src/lib/journey-lift.ts +142 -0
  35. package/src/lib/operator-settings.ts +71 -0
  36. package/src/lib/outbound.ts +147 -0
  37. package/src/lib/preferences.ts +6 -80
  38. package/src/lib/recipient-preferences.ts +53 -0
  39. package/src/lib/sms.ts +21 -2
  40. package/src/lib/stable-stringify.test.ts +42 -0
  41. package/src/lib/stable-stringify.ts +23 -0
  42. package/src/lib/variant.ts +99 -0
  43. package/src/lib/webhook-signing.ts +16 -1
  44. package/src/lists/registry.ts +6 -2
  45. package/src/lists/subscription.ts +13 -0
  46. package/src/routes/admin/contacts.ts +53 -4
  47. package/src/routes/admin/conversions.ts +137 -0
  48. package/src/routes/admin/flags.ts +369 -0
  49. package/src/routes/admin/groups.ts +866 -0
  50. package/src/routes/admin/impact-schemas.ts +44 -0
  51. package/src/routes/admin/impact-wire.test.ts +181 -0
  52. package/src/routes/admin/impact.ts +486 -0
  53. package/src/routes/admin/index.ts +12 -0
  54. package/src/routes/admin/journey-impact.ts +446 -0
  55. package/src/routes/admin/journeys.ts +70 -100
  56. package/src/routes/admin/readiness.ts +8 -8
  57. package/src/routes/admin/settings.ts +145 -0
  58. package/src/routes/admin/targeting.ts +256 -0
  59. package/src/routes/events/index.ts +11 -0
  60. package/src/routes/flags/index.ts +120 -0
  61. package/src/routes/groups/index.ts +417 -0
  62. package/src/routes/index.ts +23 -1
  63. package/src/testing.ts +25 -0
  64. package/src/webhook-sources/presets/index.ts +5 -1
  65. package/src/webhook-sources/presets/intercom.ts +230 -0
  66. package/src/webhook-sources/presets/segment.ts +56 -4
  67. package/src/worker.ts +3 -0
  68. package/src/workflows/bucket-backfill.ts +1 -14
  69. package/src/workflows/impact-digest.ts +761 -0
  70. package/src/workflows/journey-blueprint-interpreter.ts +18 -1
@@ -1,6 +1,11 @@
1
- import { contacts, emailPreferences } from "@hogsend/db";
1
+ import {
2
+ contacts,
3
+ emailPreferences,
4
+ groupMemberships,
5
+ groups,
6
+ } from "@hogsend/db";
2
7
  import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
3
- import { and, count, desc, eq, isNull, sql } from "drizzle-orm";
8
+ import { and, asc, count, desc, eq, isNull, sql } from "drizzle-orm";
4
9
  import type { AppEnv } from "../../app.js";
5
10
  import {
6
11
  contactSearchFilter,
@@ -49,6 +54,17 @@ const revenueSchema = z.object({
49
54
  lastValuedAt: z.string().nullable(),
50
55
  });
51
56
 
57
+ // The contact's live group memberships (`group_memberships` joined to `groups`),
58
+ // each linking to that group's Studio page. A contact is many-to-many with
59
+ // groups; soft-deleted groups are excluded.
60
+ const contactGroupSchema = z.object({
61
+ groupType: z.string(),
62
+ groupKey: z.string(),
63
+ displayName: z.string().nullable(),
64
+ role: z.string().nullable(),
65
+ joinedAt: z.string(),
66
+ });
67
+
52
68
  const listRoute = createRoute({
53
69
  method: "get",
54
70
  path: "/",
@@ -99,6 +115,7 @@ const getRoute = createRoute({
99
115
  contact: contactSchema,
100
116
  preferences: preferencesSchema,
101
117
  revenue: revenueSchema,
118
+ groups: z.array(contactGroupSchema),
102
119
  }),
103
120
  },
104
121
  },
@@ -301,7 +318,7 @@ export const contactsRouter = new OpenAPIHono<AppEnv>()
301
318
 
302
319
  // email_preferences.user_id uses external_id when present, else the contact
303
320
  // uuid as the deterministic fallback (risk 10 — email-only contacts).
304
- const [prefRows, revenue] = await Promise.all([
321
+ const [prefRows, revenue, groupRows] = await Promise.all([
305
322
  db
306
323
  .select()
307
324
  .from(emailPreferences)
@@ -313,12 +330,44 @@ export const contactsRouter = new OpenAPIHono<AppEnv>()
313
330
  db,
314
331
  key: contact.externalId ?? contact.anonymousId ?? contact.id,
315
332
  }),
333
+ // The contact's live group memberships (mirrors the admin groups router's
334
+ // join idiom): `group_memberships` → `groups`, live groups only, ordered
335
+ // by group type then most-recently-joined.
336
+ db
337
+ .select({
338
+ groupType: groups.groupType,
339
+ groupKey: groups.groupKey,
340
+ displayName: groups.displayName,
341
+ role: groupMemberships.role,
342
+ joinedAt: groupMemberships.joinedAt,
343
+ })
344
+ .from(groupMemberships)
345
+ .innerJoin(groups, eq(groupMemberships.groupId, groups.id))
346
+ .where(
347
+ and(
348
+ eq(groupMemberships.contactId, contact.id),
349
+ isNull(groups.deletedAt),
350
+ ),
351
+ )
352
+ .orderBy(asc(groups.groupType), desc(groupMemberships.joinedAt)),
316
353
  ]);
317
354
 
318
355
  const prefs = prefRows[0] ? serializePrefs(prefRows[0]) : null;
356
+ const groupsList = groupRows.map((r) => ({
357
+ groupType: r.groupType,
358
+ groupKey: r.groupKey,
359
+ displayName: r.displayName,
360
+ role: r.role,
361
+ joinedAt: r.joinedAt.toISOString(),
362
+ }));
319
363
 
320
364
  return c.json(
321
- { contact: serializeContact(contact), preferences: prefs, revenue },
365
+ {
366
+ contact: serializeContact(contact),
367
+ preferences: prefs,
368
+ revenue,
369
+ groups: groupsList,
370
+ },
322
371
  200,
323
372
  );
324
373
  })
@@ -103,6 +103,64 @@ const statsRoute = createRoute({
103
103
  },
104
104
  });
105
105
 
106
+ const timingSchema = z.object({
107
+ definitionId: z.string(),
108
+ /** What each subject is anchored on: a journey enrollment or an event. */
109
+ anchor: z.object({
110
+ type: z.enum(["journey", "event"]),
111
+ id: z.string(),
112
+ }),
113
+ days: z.number(),
114
+ /** Subjects anchored in the window (denominator). */
115
+ anchored: z.number(),
116
+ /** Subjects that fired the conversion at/after their anchor (numerator). */
117
+ converted: z.number(),
118
+ /** converted / anchored (0 when nobody was anchored). */
119
+ rate: z.number(),
120
+ /** How many converted within N days of the anchor (cumulative buckets). */
121
+ convertedWithin: z.object({
122
+ d1: z.number(),
123
+ d7: z.number(),
124
+ d14: z.number(),
125
+ d30: z.number(),
126
+ }),
127
+ /** Median days from anchor to first conversion among converters. */
128
+ medianDays: z.number().nullable(),
129
+ /** 90th-percentile days from anchor to first conversion among converters. */
130
+ p90Days: z.number().nullable(),
131
+ /**
132
+ * Always true — anchoring on an enrollment/event self-selects engaged
133
+ * contacts, so "how long after" is association, not causation. Holdouts
134
+ * are the causal instrument (mirrors the funnels report).
135
+ */
136
+ correlational: z.literal(true),
137
+ });
138
+
139
+ const timingRoute = createRoute({
140
+ method: "get",
141
+ path: "/timing",
142
+ tags: ["Admin"],
143
+ summary: "Time-to-conversion distribution after an anchor (correlational)",
144
+ request: {
145
+ query: z.object({
146
+ /** The conversion definition to measure the latency of. */
147
+ definitionId: z.string(),
148
+ /** Anchor each subject on a journey enrollment or an event. */
149
+ anchorType: z.enum(["journey", "event"]),
150
+ /** The journey id (anchorType=journey) or event name (anchorType=event). */
151
+ anchorId: z.string(),
152
+ days: z.coerce.number().min(1).max(365).default(90),
153
+ }),
154
+ },
155
+ responses: {
156
+ 200: {
157
+ content: { "application/json": { schema: timingSchema } },
158
+ description:
159
+ "Conversion rate + latency percentiles + within-N-day buckets, anchored on an enrollment or event",
160
+ },
161
+ },
162
+ });
163
+
106
164
  export const adminConversionsRouter = new OpenAPIHono<AppEnv>()
107
165
  .openapi(listRoute, async (c) => {
108
166
  const { db } = c.get("container");
@@ -244,4 +302,83 @@ export const adminConversionsRouter = new OpenAPIHono<AppEnv>()
244
302
  },
245
303
  200,
246
304
  );
305
+ })
306
+ .openapi(timingRoute, async (c) => {
307
+ const { db } = c.get("container");
308
+ const { definitionId, anchorType, anchorId, days } = c.req.valid("query");
309
+ const since = new Date(
310
+ Date.now() - days * 24 * 60 * 60 * 1000,
311
+ ).toISOString();
312
+
313
+ // Per subject: the anchor instant + its subject key. A journey subject is
314
+ // one enrollment row (created_at); an event subject is a contact's FIRST
315
+ // occurrence of the named event in the window.
316
+ const subjects =
317
+ anchorType === "journey"
318
+ ? sql`
319
+ select js.created_at as anchor_at, js.user_id as subject_key
320
+ from journey_states js
321
+ where js.journey_id = ${anchorId}
322
+ and js.created_at >= ${since}::timestamptz`
323
+ : sql`
324
+ select min(ue.occurred_at) as anchor_at, ue.user_id as subject_key
325
+ from user_events ue
326
+ where ue.event = ${anchorId}
327
+ and ue.occurred_at >= ${since}::timestamptz
328
+ group by ue.user_id`;
329
+
330
+ // For each subject, the first conversion of this definition at/after the
331
+ // anchor (correlated scalar). Latency = first_conv - anchor_at.
332
+ const latencyDays = sql`extract(epoch from (s.first_conv - s.anchor_at)) / 86400`;
333
+ const rows = await db.execute(sql`
334
+ select
335
+ (count(*))::int as anchored,
336
+ (count(s.first_conv))::int as converted,
337
+ (count(*) filter (where s.first_conv <= s.anchor_at + interval '1 day'))::int as w1,
338
+ (count(*) filter (where s.first_conv <= s.anchor_at + interval '7 days'))::int as w7,
339
+ (count(*) filter (where s.first_conv <= s.anchor_at + interval '14 days'))::int as w14,
340
+ (count(*) filter (where s.first_conv <= s.anchor_at + interval '30 days'))::int as w30,
341
+ percentile_cont(0.5) within group (order by ${latencyDays})
342
+ filter (where s.first_conv is not null) as median_days,
343
+ percentile_cont(0.9) within group (order by ${latencyDays})
344
+ filter (where s.first_conv is not null) as p90_days
345
+ from (
346
+ select
347
+ subj.anchor_at,
348
+ (
349
+ select min(c.occurred_at)
350
+ from conversions c
351
+ where c.user_key = subj.subject_key
352
+ and c.definition_id = ${definitionId}
353
+ and c.occurred_at >= subj.anchor_at
354
+ ) as first_conv
355
+ from (${subjects}) subj
356
+ ) s`);
357
+
358
+ const [row = {}] = rows as unknown as Record<string, unknown>[];
359
+ const num = (v: unknown) => Number(v ?? 0);
360
+ const nullableNum = (v: unknown) => (v == null ? null : Number(v));
361
+ const anchored = num(row.anchored);
362
+ const converted = num(row.converted);
363
+
364
+ return c.json(
365
+ {
366
+ definitionId,
367
+ anchor: { type: anchorType, id: anchorId },
368
+ days,
369
+ anchored,
370
+ converted,
371
+ rate: anchored > 0 ? converted / anchored : 0,
372
+ convertedWithin: {
373
+ d1: num(row.w1),
374
+ d7: num(row.w7),
375
+ d14: num(row.w14),
376
+ d30: num(row.w30),
377
+ },
378
+ medianDays: nullableNum(row.median_days),
379
+ p90Days: nullableNum(row.p90_days),
380
+ correlational: true as const,
381
+ },
382
+ 200,
383
+ );
247
384
  });
@@ -0,0 +1,369 @@
1
+ import {
2
+ type ConditionSet,
3
+ type FlagCreateInput,
4
+ type FlagTargeting,
5
+ type FlagUpdateInput,
6
+ type FlagVariant,
7
+ flagConditionSetSchema,
8
+ flagCreateSchema,
9
+ flagTargetingSchema,
10
+ flagUpdateSchema,
11
+ } from "@hogsend/core";
12
+ import { flags } from "@hogsend/db";
13
+ import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
14
+ import { and, desc, eq, isNull } from "drizzle-orm";
15
+ import type { AppEnv } from "../../app.js";
16
+ import { errorSchema } from "../../lib/schemas.js";
17
+
18
+ /**
19
+ * Admin CRUD over the sovereign `flags` table (the Studio authoring surface).
20
+ * Inherits the admin router's `requireAdmin` guard, so it never re-auths here.
21
+ * Archive is a soft-delete (`archivedAt`) that frees the flag's key for reuse
22
+ * via the partial-unique live-row index.
23
+ */
24
+
25
+ const flagVariantSchema = z.object({
26
+ key: z.string(),
27
+ value: z.unknown(),
28
+ weight: z.number(),
29
+ });
30
+
31
+ const flagSchema = z.object({
32
+ id: z.string(),
33
+ key: z.string(),
34
+ name: z.string(),
35
+ description: z.string().nullable(),
36
+ enabled: z.boolean(),
37
+ type: z.string(),
38
+ variants: z.array(flagVariantSchema),
39
+ defaultValue: z.unknown(),
40
+ targeting: flagTargetingSchema,
41
+ rollout: z.number(),
42
+ conditionSets: z.array(flagConditionSetSchema),
43
+ origin: z.string(),
44
+ archivedAt: z.string().nullable(),
45
+ createdAt: z.string(),
46
+ updatedAt: z.string(),
47
+ });
48
+
49
+ /**
50
+ * Normalize a write body's targeting to the coherent pair the columns store:
51
+ * the ordered `conditionSets` (authoritative) AND the legacy `targeting`+
52
+ * `rollout` (synthesized from `conditionSets[0]` for readers that still read
53
+ * them). `conditionSets` wins when present; otherwise a single set is built
54
+ * from the legacy fields (an omitted `rollout` defaults to 100).
55
+ */
56
+ function normalizeWrite(body: FlagCreateInput | FlagUpdateInput): {
57
+ conditionSets: ConditionSet[];
58
+ targeting: FlagTargeting;
59
+ rollout: number;
60
+ } {
61
+ const first = body.conditionSets?.[0];
62
+ if (body.conditionSets && first) {
63
+ return {
64
+ conditionSets: body.conditionSets,
65
+ targeting: first.targeting as FlagTargeting,
66
+ rollout: first.rollout,
67
+ };
68
+ }
69
+ const targeting = (body.targeting ?? []) as FlagTargeting;
70
+ const rollout = body.rollout ?? 100;
71
+ return { conditionSets: [{ targeting, rollout }], targeting, rollout };
72
+ }
73
+
74
+ function serializeFlag(row: typeof flags.$inferSelect) {
75
+ // Back-compat synthesis: a flag that predates condition sets (NULL column)
76
+ // reads as a single set built from the legacy targeting+rollout columns.
77
+ const conditionSets: ConditionSet[] = (row.conditionSets as
78
+ | ConditionSet[]
79
+ | null) ?? [
80
+ { targeting: row.targeting as FlagTargeting, rollout: row.rollout },
81
+ ];
82
+ return {
83
+ id: row.id,
84
+ key: row.key,
85
+ name: row.name,
86
+ description: row.description ?? null,
87
+ enabled: row.enabled,
88
+ type: row.type,
89
+ variants: row.variants as FlagVariant[],
90
+ defaultValue: row.defaultValue,
91
+ targeting: row.targeting as FlagTargeting,
92
+ rollout: row.rollout,
93
+ conditionSets,
94
+ origin: row.origin,
95
+ archivedAt: row.archivedAt?.toISOString() ?? null,
96
+ createdAt: row.createdAt.toISOString(),
97
+ updatedAt: row.updatedAt.toISOString(),
98
+ };
99
+ }
100
+
101
+ const listRoute = createRoute({
102
+ method: "get",
103
+ path: "/",
104
+ tags: ["Admin — Flags"],
105
+ summary: "List flags",
106
+ request: {
107
+ query: z.object({
108
+ includeArchived: z.coerce.boolean().optional(),
109
+ }),
110
+ },
111
+ responses: {
112
+ 200: {
113
+ content: {
114
+ "application/json": {
115
+ schema: z.object({ flags: z.array(flagSchema) }),
116
+ },
117
+ },
118
+ description: "Flags",
119
+ },
120
+ },
121
+ });
122
+
123
+ const createFlagRoute = createRoute({
124
+ method: "post",
125
+ path: "/",
126
+ tags: ["Admin — Flags"],
127
+ summary: "Create a flag",
128
+ request: {
129
+ body: { content: { "application/json": { schema: flagCreateSchema } } },
130
+ },
131
+ responses: {
132
+ 201: {
133
+ content: {
134
+ "application/json": { schema: z.object({ flag: flagSchema }) },
135
+ },
136
+ description: "Flag created",
137
+ },
138
+ 409: {
139
+ content: { "application/json": { schema: errorSchema } },
140
+ description: "A live flag with that key already exists",
141
+ },
142
+ },
143
+ });
144
+
145
+ const updateFlagRoute = createRoute({
146
+ method: "patch",
147
+ path: "/{id}",
148
+ tags: ["Admin — Flags"],
149
+ summary: "Update a flag (toggle enabled, edit targeting/rollout/variants)",
150
+ request: {
151
+ params: z.object({ id: z.string().uuid() }),
152
+ body: { content: { "application/json": { schema: flagUpdateSchema } } },
153
+ },
154
+ responses: {
155
+ 200: {
156
+ content: {
157
+ "application/json": { schema: z.object({ flag: flagSchema }) },
158
+ },
159
+ description: "Flag updated",
160
+ },
161
+ 404: {
162
+ content: { "application/json": { schema: errorSchema } },
163
+ description: "Flag not found",
164
+ },
165
+ 409: {
166
+ content: { "application/json": { schema: errorSchema } },
167
+ description: "A live flag with that key already exists",
168
+ },
169
+ },
170
+ });
171
+
172
+ const archiveFlagRoute = createRoute({
173
+ method: "delete",
174
+ path: "/{id}",
175
+ tags: ["Admin — Flags"],
176
+ summary: "Archive a flag (soft-delete; frees the key)",
177
+ request: {
178
+ params: z.object({ id: z.string().uuid() }),
179
+ },
180
+ responses: {
181
+ 200: {
182
+ content: {
183
+ "application/json": {
184
+ schema: z.object({ archived: z.boolean() }),
185
+ },
186
+ },
187
+ description: "Flag archived",
188
+ },
189
+ 404: {
190
+ content: { "application/json": { schema: errorSchema } },
191
+ description: "Flag not found",
192
+ },
193
+ },
194
+ });
195
+
196
+ export const adminFlagsRouter = new OpenAPIHono<AppEnv>()
197
+ .openapi(listRoute, async (c) => {
198
+ const { db } = c.get("container");
199
+ const { includeArchived } = c.req.valid("query");
200
+ const rows = await db
201
+ .select()
202
+ .from(flags)
203
+ .where(includeArchived ? undefined : isNull(flags.archivedAt))
204
+ .orderBy(desc(flags.createdAt));
205
+ return c.json({ flags: rows.map(serializeFlag) }, 200);
206
+ })
207
+ .openapi(createFlagRoute, async (c) => {
208
+ const { db } = c.get("container");
209
+ const body = c.req.valid("json");
210
+
211
+ // Enforce the live-key uniqueness explicitly for a friendly 409 (the
212
+ // partial-unique index is the ultimate backstop).
213
+ const existing = await db
214
+ .select({ id: flags.id })
215
+ .from(flags)
216
+ .where(and(eq(flags.key, body.key), isNull(flags.archivedAt)))
217
+ .limit(1);
218
+ if (existing[0]) {
219
+ return c.json({ error: "A live flag with that key already exists" }, 409);
220
+ }
221
+
222
+ // A boolean flag's default is `false` when unspecified (the spec's served
223
+ // value when disabled / targeting fails / outside the rollout).
224
+ const defaultValue =
225
+ body.defaultValue !== undefined
226
+ ? body.defaultValue
227
+ : body.type === "boolean"
228
+ ? false
229
+ : null;
230
+
231
+ const write = normalizeWrite(body);
232
+ const [created] = await db
233
+ .insert(flags)
234
+ .values({
235
+ key: body.key,
236
+ name: body.name,
237
+ description: body.description,
238
+ enabled: body.enabled,
239
+ type: body.type,
240
+ variants: body.variants ?? [],
241
+ defaultValue,
242
+ targeting: write.targeting,
243
+ rollout: write.rollout,
244
+ conditionSets: write.conditionSets,
245
+ })
246
+ .returning();
247
+ if (!created) throw new Error("Failed to create flag");
248
+ return c.json({ flag: serializeFlag(created) }, 201);
249
+ })
250
+ .openapi(updateFlagRoute, async (c) => {
251
+ const { db } = c.get("container");
252
+ const { id } = c.req.valid("param");
253
+ const body = c.req.valid("json");
254
+
255
+ const rows = await db.select().from(flags).where(eq(flags.id, id)).limit(1);
256
+ if (!rows[0]) return c.json({ error: "Flag not found" }, 404);
257
+
258
+ // A key rename must stay unique among LIVE flags (the partial-unique index
259
+ // is the backstop; this is the friendly 409). Skip when the key is
260
+ // unchanged so re-saving the same flag never self-collides.
261
+ if (body.key !== undefined && body.key !== rows[0].key) {
262
+ const clash = await db
263
+ .select({ id: flags.id })
264
+ .from(flags)
265
+ .where(and(eq(flags.key, body.key), isNull(flags.archivedAt)))
266
+ .limit(1);
267
+ if (clash[0]) {
268
+ return c.json(
269
+ { error: "A live flag with that key already exists" },
270
+ 409,
271
+ );
272
+ }
273
+ }
274
+
275
+ // Targeting write: recompute the coherent (conditionSets + legacy) triple
276
+ // when the caller touches ANY of conditionSets/targeting/rollout. An
277
+ // explicit `conditionSets` is authoritative. A legacy-field-only edit (bare
278
+ // targeting/rollout) merges into the EXISTING first set and PRESERVES
279
+ // sets[1..], so a rollout bump on a multi-set flag never silently destroys
280
+ // its other sets. The legacy `targeting`/`rollout` columns mirror set[0].
281
+ const touchesTargeting =
282
+ body.conditionSets !== undefined ||
283
+ body.targeting !== undefined ||
284
+ body.rollout !== undefined;
285
+ let targetingWrite:
286
+ | {
287
+ conditionSets: ConditionSet[];
288
+ targeting: FlagTargeting;
289
+ rollout: number;
290
+ }
291
+ | undefined;
292
+ if (touchesTargeting) {
293
+ const first = body.conditionSets?.[0];
294
+ if (body.conditionSets && first) {
295
+ targetingWrite = {
296
+ conditionSets: body.conditionSets,
297
+ targeting: first.targeting as FlagTargeting,
298
+ rollout: first.rollout,
299
+ };
300
+ } else {
301
+ // Existing sets to merge into (back-compat: a NULL column synthesizes a
302
+ // single set from the legacy targeting+rollout columns).
303
+ const existing = rows[0].conditionSets as ConditionSet[] | null;
304
+ const base =
305
+ existing && existing.length > 0
306
+ ? existing
307
+ : [
308
+ {
309
+ targeting: rows[0].targeting as FlagTargeting,
310
+ rollout: rows[0].rollout,
311
+ },
312
+ ];
313
+ const targeting = (body.targeting ??
314
+ base[0]?.targeting ??
315
+ rows[0].targeting) as FlagTargeting;
316
+ const rollout = body.rollout ?? base[0]?.rollout ?? rows[0].rollout;
317
+ targetingWrite = {
318
+ conditionSets: [{ targeting, rollout }, ...base.slice(1)],
319
+ targeting,
320
+ rollout,
321
+ };
322
+ }
323
+ }
324
+
325
+ const [updated] = await db
326
+ .update(flags)
327
+ .set({
328
+ ...(body.key !== undefined ? { key: body.key } : {}),
329
+ ...(body.name !== undefined ? { name: body.name } : {}),
330
+ ...(body.description !== undefined
331
+ ? { description: body.description }
332
+ : {}),
333
+ ...(body.enabled !== undefined ? { enabled: body.enabled } : {}),
334
+ ...(body.type !== undefined ? { type: body.type } : {}),
335
+ ...(body.variants !== undefined ? { variants: body.variants } : {}),
336
+ ...(body.defaultValue !== undefined
337
+ ? { defaultValue: body.defaultValue }
338
+ : {}),
339
+ ...(targetingWrite
340
+ ? {
341
+ targeting: targetingWrite.targeting,
342
+ rollout: targetingWrite.rollout,
343
+ conditionSets: targetingWrite.conditionSets,
344
+ }
345
+ : {}),
346
+ updatedAt: new Date(),
347
+ })
348
+ .where(eq(flags.id, id))
349
+ .returning();
350
+ if (!updated) throw new Error("Failed to update flag");
351
+ return c.json({ flag: serializeFlag(updated) }, 200);
352
+ })
353
+ .openapi(archiveFlagRoute, async (c) => {
354
+ const { db } = c.get("container");
355
+ const { id } = c.req.valid("param");
356
+
357
+ const rows = await db
358
+ .select()
359
+ .from(flags)
360
+ .where(and(eq(flags.id, id), isNull(flags.archivedAt)))
361
+ .limit(1);
362
+ if (!rows[0]) return c.json({ error: "Flag not found" }, 404);
363
+
364
+ await db
365
+ .update(flags)
366
+ .set({ archivedAt: new Date(), updatedAt: new Date() })
367
+ .where(eq(flags.id, id));
368
+ return c.json({ archived: true }, 200);
369
+ });