@hermeticacomms/sdk-node 0.0.0-stage → 0.4.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 (73) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +12 -2
  3. package/dist/contracts/analytics.d.ts +405 -0
  4. package/dist/contracts/analytics.js +77 -0
  5. package/dist/contracts/auth.d.ts +363 -0
  6. package/dist/contracts/auth.js +130 -0
  7. package/dist/contracts/billing.d.ts +143 -0
  8. package/dist/contracts/billing.js +32 -0
  9. package/dist/contracts/campaigns.d.ts +915 -0
  10. package/dist/contracts/campaigns.js +276 -0
  11. package/dist/contracts/common.d.ts +57 -0
  12. package/dist/contracts/common.js +35 -0
  13. package/dist/contracts/connectors.d.ts +179 -0
  14. package/dist/contracts/connectors.js +46 -0
  15. package/dist/contracts/consent.d.ts +628 -0
  16. package/dist/contracts/consent.js +194 -0
  17. package/dist/contracts/content-blocks.d.ts +165 -0
  18. package/dist/contracts/content-blocks.js +62 -0
  19. package/dist/contracts/content-library.d.ts +347 -0
  20. package/dist/contracts/content-library.js +52 -0
  21. package/dist/contracts/content.d.ts +955 -0
  22. package/dist/contracts/content.js +194 -0
  23. package/dist/contracts/delivery.d.ts +602 -0
  24. package/dist/contracts/delivery.js +220 -0
  25. package/dist/contracts/events.d.ts +514 -0
  26. package/dist/contracts/events.js +180 -0
  27. package/dist/contracts/experiments.d.ts +378 -0
  28. package/dist/contracts/experiments.js +140 -0
  29. package/dist/contracts/identity.d.ts +761 -0
  30. package/dist/contracts/identity.js +226 -0
  31. package/dist/contracts/index.d.ts +15 -0
  32. package/dist/contracts/index.js +15 -0
  33. package/dist/contracts/integrations.d.ts +445 -0
  34. package/dist/contracts/integrations.js +139 -0
  35. package/dist/contracts/leads.d.ts +733 -0
  36. package/dist/contracts/leads.js +125 -0
  37. package/dist/contracts/metrics.d.ts +465 -0
  38. package/dist/contracts/metrics.js +96 -0
  39. package/dist/contracts/outbound.d.ts +15535 -0
  40. package/dist/contracts/outbound.js +432 -0
  41. package/dist/contracts/pickers.d.ts +12 -0
  42. package/dist/contracts/pickers.js +20 -0
  43. package/dist/contracts/platform-admin.d.ts +244 -0
  44. package/dist/contracts/platform-admin.js +98 -0
  45. package/dist/contracts/postcards.d.ts +79 -0
  46. package/dist/contracts/postcards.js +29 -0
  47. package/dist/contracts/push.d.ts +530 -0
  48. package/dist/contracts/push.js +102 -0
  49. package/dist/contracts/rcs.d.ts +39 -0
  50. package/dist/contracts/rcs.js +19 -0
  51. package/dist/contracts/segments.d.ts +3187 -0
  52. package/dist/contracts/segments.js +421 -0
  53. package/dist/contracts/workflow-nodes.d.ts +2130 -0
  54. package/dist/contracts/workflow-nodes.js +346 -0
  55. package/dist/contracts/workflows.d.ts +46811 -0
  56. package/dist/contracts/workflows.js +350 -0
  57. package/dist/contracts/x10-platform.d.ts +2603 -0
  58. package/dist/contracts/x10-platform.js +129 -0
  59. package/dist/http.d.ts +30 -0
  60. package/dist/http.js +65 -0
  61. package/dist/index.d.ts +11631 -0
  62. package/dist/index.js +63 -0
  63. package/dist/platform.d.ts +163 -0
  64. package/dist/platform.js +40 -0
  65. package/dist/resources.d.ts +1338 -0
  66. package/dist/resources.js +56 -0
  67. package/dist/signature.d.ts +5 -0
  68. package/dist/signature.js +19 -0
  69. package/dist/x10.d.ts +1608 -0
  70. package/dist/x10.js +66 -0
  71. package/dist/z10.d.ts +256 -0
  72. package/dist/z10.js +46 -0
  73. package/package.json +40 -4
@@ -0,0 +1,421 @@
1
+ import { z } from 'zod';
2
+ import { AppSlug, Channel, Id, PageQuery, Timestamp } from './common.js';
3
+ import { ProfileDto } from './identity.js';
4
+ export const MAX_SEGMENT_DEPTH = 5;
5
+ export const MAX_SEGMENT_CONDITIONS = 100;
6
+ export const PROPERTY_PATH_RE = /^[a-zA-Z0-9_]{1,64}(\.[a-zA-Z0-9_]{1,64}){0,4}$/;
7
+ const PropertyPath = z.string().regex(PROPERTY_PATH_RE, 'Invalid property path');
8
+ /** Standard profile fields (camelCase like the profile DTO) and their value type. */
9
+ export const STANDARD_FIELDS = {
10
+ email: 'string', phone: 'string', firstName: 'string', lastName: 'string', timezone: 'string', locale: 'string',
11
+ country: 'string', city: 'string', region: 'string', source: 'string', lifecycleStage: 'string', ownerUserId: 'string',
12
+ kind: 'string', createdAt: 'date',
13
+ /** 'unverified' (imported or acquired, no human open/click or confirmation yet), 'verified', or empty. */
14
+ verification: 'string',
15
+ /** When the profile last changed (date_modified) and when it first got an email, phone or external id (date_identified). */
16
+ updatedAt: 'date', identifiedAt: 'date',
17
+ };
18
+ export const ProfileField = z.union([
19
+ z.enum(Object.keys(STANDARD_FIELDS)),
20
+ z.string().startsWith('attributes.').refine((s) => PROPERTY_PATH_RE.test(s.slice('attributes.'.length)), 'Invalid attribute path'),
21
+ ]);
22
+ // ---- operators per value type -------------------------------------------------------------------------------------
23
+ const str = z.string().max(512);
24
+ const DateValue = z.union([z.iso.date(), z.iso.datetime({ offset: true })]);
25
+ const days = z.number().int().min(0).max(3650);
26
+ /** Calendar date tokens, in the workspace zone: weeks start on Monday. */
27
+ export const CALENDAR_PERIODS = ['today', 'yesterday', 'tomorrow', 'this_week', 'last_week', 'next_week', 'this_month', 'last_month', 'next_month', 'this_year', 'last_year', 'next_year'];
28
+ const REPEAT_COUNT = /\{(\d+)(?:,(\d*))?\}/y;
29
+ /** A repeated group that holds a repeat, or a count above 255 (Postgres's own limit). Skips escapes and character classes. */
30
+ function repeatProblem(p) {
31
+ const open = [];
32
+ let closedHasRepeat = false; // the atom just before this position is a group with a repeat inside
33
+ for (let i = 0; i < p.length; i++) {
34
+ const c = p[i];
35
+ let repeat = c === '*' || c === '+' || c === '?';
36
+ if (c === '{') {
37
+ REPEAT_COUNT.lastIndex = i;
38
+ const m = REPEAT_COUNT.exec(p);
39
+ if (m) {
40
+ if (Number(m[1]) > 255 || Number(m[2] || 0) > 255)
41
+ return 'Repeat counts above 255 are not allowed';
42
+ repeat = true;
43
+ i += m[0].length - 1;
44
+ }
45
+ }
46
+ if (repeat) {
47
+ if (closedHasRepeat)
48
+ return 'A repeat inside a repeated group is not allowed';
49
+ if (open.length)
50
+ open[open.length - 1] = true;
51
+ closedHasRepeat = false;
52
+ }
53
+ else if (c === ')') {
54
+ closedHasRepeat = open.pop() ?? false;
55
+ if (closedHasRepeat && open.length)
56
+ open[open.length - 1] = true;
57
+ }
58
+ else {
59
+ closedHasRepeat = false;
60
+ if (c === '(') {
61
+ open.push(false);
62
+ if (p[i + 1] === '?')
63
+ i++;
64
+ }
65
+ else if (c === '\\')
66
+ i++;
67
+ else if (c === '[') {
68
+ i += p[i + 1] === '^' ? 2 : 1;
69
+ if (p[i] === ']')
70
+ i++;
71
+ while (i < p.length && p[i] !== ']')
72
+ i += p[i] === '\\' ? 2 : 1;
73
+ }
74
+ }
75
+ }
76
+ return null;
77
+ }
78
+ /**
79
+ * A pattern is run by Postgres on every profile, so it must be small, valid, and free of the shapes that can blow up its matcher.
80
+ * These checks only remove the obvious ones (ambiguous alternation can still be slow): statement_timeout around every segment query is the real bound.
81
+ */
82
+ export function regexProblem(p) {
83
+ if (p.length > 200)
84
+ return 'Pattern is longer than 200 characters';
85
+ if (/\\[1-9]|\(\?[=!<]/.test(p))
86
+ return 'Back-references and look-around are not allowed';
87
+ try {
88
+ RegExp(p);
89
+ }
90
+ catch {
91
+ return 'Pattern is not a valid regular expression';
92
+ }
93
+ return repeatProblem(p);
94
+ }
95
+ const StringPredicate = z.discriminatedUnion('op', [
96
+ z.object({ valueType: z.literal('string'), op: z.enum(['matches_regex', 'not_matches_regex']), value: z.string().min(1) }).refine((p) => !regexProblem(p.value), { message: 'Not a valid, safe pattern (max 200 characters, no back-references, look-around, repeats inside repeated groups or counts above 255)', path: ['value'] }),
97
+ z.object({ valueType: z.literal('string'), op: z.enum(['eq', 'neq', 'contains', 'not_contains', 'starts_with', 'not_starts_with', 'ends_with', 'not_ends_with']), value: str }),
98
+ z.object({ valueType: z.literal('string'), op: z.enum(['in', 'not_in']), values: z.array(str).min(1).max(500) }),
99
+ z.object({ valueType: z.literal('string'), op: z.enum(['exists', 'not_exists']) }),
100
+ ]);
101
+ const NumberPredicate = z.discriminatedUnion('op', [
102
+ z.object({ valueType: z.literal('number'), op: z.enum(['eq', 'neq', 'gt', 'gte', 'lt', 'lte']), value: z.number() }),
103
+ z.object({ valueType: z.literal('number'), op: z.enum(['between', 'not_between']), from: z.number(), to: z.number() }),
104
+ ]);
105
+ const DatePredicate = z.discriminatedUnion('op', [
106
+ z.object({ valueType: z.literal('date'), op: z.enum(['before', 'after']), value: DateValue }),
107
+ z.object({ valueType: z.literal('date'), op: z.enum(['between', 'not_between']), from: DateValue, to: DateValue }),
108
+ z.object({ valueType: z.literal('date'), op: z.enum(['within_last', 'not_within_last', 'within_next', 'is_anniversary_within', 'anniversary_in_last']), days }),
109
+ /** Month and day only, ignoring the year (birthdays, anniversaries): this calendar month, or a named month 1-12. */
110
+ z.object({ valueType: z.literal('date'), op: z.literal('anniversary_this_month') }),
111
+ z.object({ valueType: z.literal('date'), op: z.literal('anniversary_in_month'), month: z.number().int().min(1).max(12) }),
112
+ /** Falls in a calendar period: today, this/last/next week, month or year. */
113
+ z.object({ valueType: z.literal('date'), op: z.literal('in_period'), period: z.enum(CALENDAR_PERIODS) }),
114
+ ]);
115
+ /** "Is set" / "is not set" for every non-text type (text has its own exists/not_exists above). */
116
+ const SetPredicate = z.object({ valueType: z.enum(['number', 'date', 'boolean', 'list']), op: z.enum(['exists', 'not_exists']) });
117
+ const BooleanPredicate = z.object({ valueType: z.literal('boolean'), op: z.enum(['is_true', 'is_false']) });
118
+ const ListPredicate = z.object({ valueType: z.literal('list'), op: z.enum(['contains_any', 'contains_all', 'not_contains_any', 'not_contains_all']), values: z.array(str).min(1).max(100) });
119
+ const ListTextPredicate = z.object({ valueType: z.literal('list'), op: z.enum(['contains_text', 'not_contains_text']), value: str });
120
+ const ListEmptyPredicate = z.object({ valueType: z.literal('list'), op: z.enum(['is_empty', 'is_not_empty']) });
121
+ /** Number of items in a list-valued property. */
122
+ const ListLengthPredicate = z.object({ valueType: z.literal('list'), op: z.enum(['length_eq', 'length_gt', 'length_gte', 'length_lt', 'length_lte']), value: z.number().int().min(0) });
123
+ export const Predicate = z.union([SetPredicate, StringPredicate, NumberPredicate, DatePredicate, BooleanPredicate, ListPredicate, ListTextPredicate, ListEmptyPredicate, ListLengthPredicate]);
124
+ // ---- conditions ---------------------------------------------------------------------------------------------------
125
+ /** Top-level attribute key as stored (history is keyed by it). */
126
+ const AttrKey = z.string().min(1).max(128);
127
+ const neg = { negate: z.boolean().optional() };
128
+ /** Event property path; `[]` after a segment steps into every item of an array (e.g. `Items[].Categories[]`). */
129
+ export const EVENT_PATH_RE = /^[a-zA-Z0-9_]{1,64}(\[\])?(\.[a-zA-Z0-9_]{1,64}(\[\])?){0,4}$/;
130
+ const EventPropertyPath = z.string().regex(EVENT_PATH_RE, 'Invalid property path');
131
+ /** Predictive values the nightly job stores under `attributes.predictive` (see analytics predict), with their type. */
132
+ export const PREDICTIVE_METRICS = {
133
+ churn_risk: 'number', predicted_clv: 'number', historic_clv: 'number', total_clv: 'number', avg_order_value: 'number',
134
+ avg_order_interval_days: 'number', order_count: 'number', predicted_orders: 'number', expected_next_order_at: 'date', p_alive: 'number',
135
+ /** Inferred from the first name (analytics `profile_gender_predictions`, not an attribute): likely_female | likely_male | uncertain. */
136
+ predicted_gender: 'string',
137
+ };
138
+ export const SEGMENT_SUPPRESSION_REASONS = ['unsubscribe', 'hard_bounce', 'complaint', 'stop_keyword', 'manual', 'invalid', 'dnc'];
139
+ /** Countries where distance from a postal code can be judged: US, UK, Canada, Australia, New Zealand and most EU countries (not CY, EE, GR, MT). */
140
+ export const PROXIMITY_COUNTRIES = ['US', 'GB', 'CA', 'AU', 'NZ', 'AT', 'BE', 'BG', 'HR', 'CZ', 'DK', 'FI', 'FR', 'DE', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE'];
141
+ export const ProximityCountry = z.string().trim().length(2).toUpperCase().transform((c) => (c === 'UK' ? 'GB' : c)).refine((c) => PROXIMITY_COUNTRIES.includes(c), 'Distance searches work for the US, UK, Canada, Australia, New Zealand and most EU countries');
142
+ const Cmp = z.enum(['eq', 'neq', 'gt', 'gte', 'lt', 'lte']);
143
+ /** Fixed company columns and their type. */
144
+ export const COMPANY_FIELDS = { name: 'string', domain: 'string', industry: 'string', sizeBand: 'string', country: 'string', stage: 'string', createdAt: 'date' };
145
+ const CompanyField = z.union([
146
+ z.enum(Object.keys(COMPANY_FIELDS)),
147
+ z.string().startsWith('fields.').refine((s) => PROPERTY_PATH_RE.test(s.slice('fields.'.length)), 'Invalid company field'),
148
+ ]);
149
+ export const EventWindow = z.discriminatedUnion('kind', [
150
+ z.object({ kind: z.literal('ever') }),
151
+ z.object({ kind: z.literal('last_days'), days: z.number().int().min(1).max(3650) }),
152
+ z.object({ kind: z.literal('between'), from: DateValue, to: DateValue }),
153
+ /** From a date until now ("since"), or up to a date ("before"). */
154
+ z.object({ kind: z.literal('since'), from: DateValue }),
155
+ z.object({ kind: z.literal('before'), to: DateValue }),
156
+ /** Upcoming days (future-dated events, e.g. a booking). */
157
+ /** At least N days ago (everything older than that). */
158
+ z.object({ kind: z.literal('older_than_days'), days: z.number().int().min(1).max(3650) }),
159
+ z.object({ kind: z.literal('next_days'), days: z.number().int().min(1).max(3650) }),
160
+ /** The current, previous or next calendar day/week/month/quarter/year (workspace zone). */
161
+ z.object({ kind: z.literal('calendar'), unit: z.enum(['day', 'week', 'month', 'quarter', 'year']), which: z.enum(['this', 'last', 'next']) }),
162
+ ]);
163
+ /** Extra tests on the consent record behind a status: how it was given (form, api, double_opt_in, import...), when, and double opt-in. */
164
+ const consentExtras = {
165
+ method: z.string().trim().min(1).max(64).optional(),
166
+ window: EventWindow.optional(),
167
+ doubleOptIn: z.boolean().optional(),
168
+ };
169
+ export const EventMeasure = z.discriminatedUnion('kind', [
170
+ z.object({ kind: z.literal('count'), op: Cmp, value: z.number().int().min(0) }),
171
+ z.object({ kind: z.enum(['first', 'last']), when: DatePredicate }),
172
+ /** Total of the event's recorded value (revenue) across matching events, in major currency units. */
173
+ z.object({ kind: z.literal('value_sum'), predicate: NumberPredicate }),
174
+ /** Number of distinct values of a property across matching events (e.g. distinct product ids). */
175
+ z.object({ kind: z.literal('distinct_count'), property: PropertyPath, op: Cmp, value: z.number().int().min(0) }),
176
+ /** LastPerformed: take the most recent matching event, then require its properties to satisfy every `has` test. */
177
+ z.object({ kind: z.literal('last_has'), has: z.array(z.object({ path: PropertyPath, predicate: Predicate })).min(1).max(10) }),
178
+ /** KeyedPerformed: one instance per distinct `key` value (its latest event); count the instances whose latest event satisfies every `has` test (none = all). */
179
+ z.object({
180
+ kind: z.literal('keyed_count'), key: PropertyPath, op: Cmp, value: z.number().int().min(0),
181
+ has: z.array(z.object({ path: PropertyPath, predicate: Predicate })).max(10).optional(),
182
+ }),
183
+ z.object({ kind: z.literal('aggregate'), fn: z.enum(['sum', 'avg', 'min', 'max']), property: PropertyPath, predicate: NumberPredicate }),
184
+ ]);
185
+ export const SegmentCondition = z.discriminatedUnion('type', [
186
+ z.object({ type: z.literal('profile_property'), field: ProfileField, predicate: Predicate, ...neg }),
187
+ z.object({ type: z.literal('identifier_exists'), identifierType: z.enum(['email', 'phone', 'external_id', 'anonymous_id', 'crm_id']), verified: z.boolean().optional(),
188
+ /** Exact identifier values (emails lower-cased; phones in E.164): matches a profile holding any of them. */
189
+ values: z.array(z.string().trim().min(1).max(256)).min(1).max(500).optional(), ...neg }),
190
+ z.object({ type: z.literal('tag'), name: z.string().min(1).max(64), ...neg }),
191
+ /** `window` limits to people added to the list in that period. */
192
+ /** `meta` tests the data stored on the membership itself (Mailchimp list-member meta) with a text predicate. */
193
+ z.object({ type: z.literal('list_membership'), listId: Id, window: EventWindow.optional(), meta: z.object({ key: PropertyPath, predicate: Predicate }).optional(), ...neg }),
194
+ z.object({
195
+ type: z.literal('event'),
196
+ name: z.string().min(1).max(128),
197
+ /** Only events sent with this `app` (several products in one workspace). */
198
+ app: AppSlug.optional(),
199
+ properties: z.array(z.object({ path: EventPropertyPath, predicate: Predicate })).max(10).optional(),
200
+ window: EventWindow.default({ kind: 'ever' }),
201
+ measure: EventMeasure.default({ kind: 'count', op: 'gte', value: 1 }),
202
+ ...neg,
203
+ }),
204
+ z.object({
205
+ type: z.literal('consent_status'),
206
+ channel: Channel,
207
+ purpose: z.string().min(1).max(64).optional(),
208
+ topic: z.string().min(1).max(64).optional(),
209
+ status: z.enum(['granted', 'revoked', 'pending_confirmation', 'none']),
210
+ ...consentExtras,
211
+ ...neg,
212
+ }),
213
+ /** `reason` narrows to one cause: hard bounce, invalid address, manual, unsubscribe... */
214
+ z.object({ type: z.literal('suppressed'), channel: Channel, reason: z.enum(SEGMENT_SUPPRESSION_REASONS).optional(), ...neg }),
215
+ /** Country is in the European Union (UK excluded) or the United States, from the profile's two-letter country. */
216
+ z.object({ type: z.literal('in_region'), region: z.enum(['eu', 'us']), ...neg }),
217
+ /** Opted out of tracking (contact preference). Negate for "can be tracked". */
218
+ z.object({ type: z.literal('tracking_opted_out'), ...neg }),
219
+ /** Spend tier from total lifetime value; the tier boundaries are the workspace's segment settings. */
220
+ z.object({ type: z.literal('spend_tier'), tier: z.enum(['low', 'medium', 'high', 'top']), ...neg }),
221
+ /** Can be sent marketing now: unexpired marketing consent granted and not suppressed on the channel. Negate for "cannot". `topic` (key) asks about that topic's subscription; without it a channel-wide revoke excludes. */
222
+ z.object({ type: z.literal('can_receive_marketing'), channel: Channel, topic: z.string().min(1).max(64).optional(), ...consentExtras, ...neg }),
223
+ /** A predicted value (CLV, churn risk, next order date...) tested with a number or date operator. */
224
+ z.object({ type: z.literal('predictive'), metric: z.enum(Object.keys(PREDICTIVE_METRICS)), predicate: z.union([NumberPredicate, DatePredicate, SetPredicate, StringPredicate]), ...neg }),
225
+ /** Within a distance of a point or postal code, from the profile's `latitude`/`longitude` attributes. */
226
+ z.object({
227
+ type: z.literal('location_radius'),
228
+ center: z.union([
229
+ z.object({ kind: z.literal('point'), lat: z.number().min(-90).max(90), lng: z.number().min(-180).max(180) }),
230
+ z.object({ kind: z.literal('postal'), postalCode: z.string().trim().min(2).max(16), country: ProximityCountry }),
231
+ ]),
232
+ radius: z.number().positive().max(20_000),
233
+ unit: z.enum(['km', 'mi']),
234
+ ...neg,
235
+ }),
236
+ z.object({
237
+ type: z.literal('object_link'),
238
+ objectType: z.string().regex(/^[a-z][a-z0-9_]{0,62}$/),
239
+ properties: z.array(z.object({ path: PropertyPath, predicate: Predicate })).max(10).optional(),
240
+ ...neg,
241
+ }),
242
+ z.object({ type: z.literal('segment_membership'), segmentId: Id, ...neg }),
243
+ z.object({ type: z.literal('location'), field: z.enum(['country', 'region', 'city']), op: z.enum(['eq', 'in']), values: z.array(str).min(1).max(200), ...neg }),
244
+ z.object({
245
+ type: z.literal('message_engagement'),
246
+ /** `sent` = handed to the provider; `dropped` = blocked before sending (consent, suppression, limits). */
247
+ engagement: z.enum(['sent', 'received', 'opened', 'clicked', 'replied', 'bounced', 'complained', 'dropped']),
248
+ /** Only messages on this channel (SMS clicks, push receipts...). */
249
+ channel: Channel.optional(),
250
+ /** Only messages rendered from a template carrying this tag. */
251
+ templateTag: z.string().trim().min(1).max(64).optional(),
252
+ /** Only messages rendered from this template (any version). */
253
+ templateId: Id.optional(),
254
+ /** Omitted = any source (campaign, journey, sequence, transactional). */
255
+ sourceKind: z.string().min(1).max(32).optional(),
256
+ sourceId: Id.optional(),
257
+ /** Clicked link (only for `clicked`): the URL contains or equals the text. */
258
+ url: z.object({ op: z.enum(['contains', 'equals']), value: z.string().min(1).max(500) }).optional(),
259
+ /** The message subject contains this text. */
260
+ subjectContains: z.string().min(1).max(200).optional(),
261
+ /** Only campaigns whose name contains or equals the text. */
262
+ campaignName: z.object({ op: z.enum(['contains', 'equals']), value: z.string().min(1).max(200) }).optional(),
263
+ window: EventWindow.default({ kind: 'ever' }),
264
+ /** At least this many engagement events (default 1). */
265
+ minCount: z.number().int().min(1).max(10_000).optional(),
266
+ ...neg,
267
+ }),
268
+ /** The attribute currently holds `value` and has held it for at least `atLeastDays` (from attribute change history). */
269
+ /** `comparator: 'under'` flips it: holds the value now, but for less than `atLeastDays` days. */
270
+ z.object({ type: z.literal('attribute_has_been'), key: AttrKey, value: z.union([z.string().max(512), z.number(), z.boolean()]), atLeastDays: days, comparator: z.enum(['at_least', 'under']).optional(), ...neg }),
271
+ /** The attribute changed (optionally from/to a value) within the window. */
272
+ z.object({
273
+ type: z.literal('attribute_changed'),
274
+ key: AttrKey,
275
+ to: z.union([z.string().max(512), z.number(), z.boolean()]).optional(),
276
+ from: z.union([z.string().max(512), z.number(), z.boolean()]).optional(),
277
+ window: EventWindow.default({ kind: 'ever' }),
278
+ ...neg,
279
+ }),
280
+ /** Last activity = latest event or engagement of the profile. */
281
+ z.object({ type: z.literal('last_active'), when: DatePredicate, ...neg }),
282
+ z.object({ type: z.literal('workflow_membership'), workflowId: Id, activeOnly: z.boolean().optional(), ...neg }),
283
+ /** Stable pseudo-random slice of all profiles (same profile always lands in the same bucket for a given salt). */
284
+ z.object({ type: z.literal('random_percent'), percent: z.number().int().min(0).max(100), salt: z.string().max(64).default(''), ...neg }),
285
+ /** The profile's company: a fixed company field, or `fields.<key>` for a company custom field. */
286
+ z.object({ type: z.literal('company_property'), field: CompanyField, predicate: Predicate, ...neg }),
287
+ /** Member of a list or campaign in a connected CRM (inbound membership sync). Omit `connectionId` for any connection. */
288
+ z.object({ type: z.literal('crm_list_membership'), connectionId: Id.optional(), crmListId: z.string().trim().min(1).max(256), ...neg }),
289
+ /** Object segments only: a property of the object itself. */
290
+ z.object({ type: z.literal('object_property'), path: PropertyPath, predicate: Predicate, ...neg }),
291
+ /** Object segments only: how many people are linked to the object, optionally only people in a segment. */
292
+ z.object({ type: z.literal('object_linked_profiles'), op: Cmp, value: z.number().int().min(0), segmentId: Id.optional(), ...neg }),
293
+ ]);
294
+ /** Conditions that test an object instead of a person; only object segments use them, and object segments use only them. */
295
+ export const OBJECT_CONDITIONS = ['object_property', 'object_linked_profiles'];
296
+ // Recursive schemas carry an `id`: each becomes one OpenAPI component instead of a dangling `$ref`.
297
+ const SegmentNodeSchema = z.lazy(() => z.union([SegmentGroupSchema, SegmentCondition])).meta({ id: 'SegmentNode' });
298
+ const SegmentGroupSchema = z.lazy(() => z.object({ type: z.literal('group'), op: z.enum(['and', 'or']), negate: z.boolean().optional(), children: z.array(SegmentNodeSchema).max(MAX_SEGMENT_CONDITIONS) }));
299
+ export const walkConditions = (n, fn) => n.type === 'group' ? n.children.forEach((c) => walkConditions(c, fn)) : fn(n);
300
+ const depthOf = (n) => (n.type === 'group' ? 1 + Math.max(0, ...n.children.map(depthOf)) : 0);
301
+ /** Root is always a group; an empty `and` group matches every profile. */
302
+ export const SegmentDefinition = SegmentGroupSchema.superRefine((def, ctx) => {
303
+ let count = 0;
304
+ walkConditions(def, () => count++);
305
+ if (count > MAX_SEGMENT_CONDITIONS)
306
+ ctx.addIssue({ code: 'custom', message: `At most ${MAX_SEGMENT_CONDITIONS} conditions` });
307
+ if (depthOf(def) > MAX_SEGMENT_DEPTH)
308
+ ctx.addIssue({ code: 'custom', message: `Groups nest at most ${MAX_SEGMENT_DEPTH} deep` });
309
+ });
310
+ // ---- DTOs ---------------------------------------------------------------------------------------------------------
311
+ export const SegmentDto = z.object({
312
+ id: Id,
313
+ name: z.string(),
314
+ description: z.string().nullable(),
315
+ folder: z.string().nullable(),
316
+ definition: SegmentDefinition,
317
+ status: z.enum(['active', 'archived']),
318
+ evalStatus: z.enum(['pending', 'ready', 'failed']),
319
+ lastEvaluatedAt: Timestamp.nullable(),
320
+ memberCount: z.number().int(),
321
+ dependencyKeys: z.array(z.string()),
322
+ version: z.number().int(),
323
+ /** `profile`, or the custom object type key the segment selects (an object segment). */
324
+ subject: z.string(),
325
+ starred: z.boolean(),
326
+ app: z.string().nullable().optional(),
327
+ tags: z.array(z.string()).optional(),
328
+ createdAt: Timestamp,
329
+ updatedAt: Timestamp,
330
+ });
331
+ export const SegmentPage = z.object({ items: z.array(SegmentDto), nextCursor: z.uuid().nullable() });
332
+ /** `profile` (default) or a custom object type key (segments the objects themselves). */
333
+ export const SegmentSubject = z.string().regex(/^(profile|[a-z][a-z0-9_]{0,62})$/, 'profile or an object type key');
334
+ export const CreateSegmentBody = z.object({
335
+ name: z.string().trim().min(1).max(200), description: z.string().max(2000).nullish(), folder: z.string().trim().min(1).max(80).nullish(), definition: SegmentDefinition,
336
+ tags: z.array(z.string().trim().min(1).max(64)).max(50).optional(), subject: SegmentSubject.optional(), starred: z.boolean().optional(),
337
+ /** Product that owns the segment (null = shared), a label and filter only. */
338
+ app: AppSlug.nullish(),
339
+ });
340
+ export const UpdateSegmentBody = z.object({
341
+ name: z.string().min(1).max(200).optional(),
342
+ description: z.string().max(2000).nullish(),
343
+ folder: z.string().trim().min(1).max(80).nullish(),
344
+ definition: SegmentDefinition.optional(),
345
+ status: z.enum(['active', 'archived']).optional(),
346
+ starred: z.boolean().optional(),
347
+ app: AppSlug.nullish(),
348
+ tags: z.array(z.string().trim().min(1).max(64)).max(50).optional(),
349
+ });
350
+ export const SegmentPreviewBody = z.object({ definition: SegmentDefinition, subject: SegmentSubject.optional() });
351
+ export const SegmentPreviewResult = z.object({
352
+ count: z.number().int(),
353
+ sample: z.array(ProfileDto),
354
+ explanation: z.array(z.string()),
355
+ evaluatedAt: Timestamp,
356
+ });
357
+ export const SegmentVersionDto = z.object({ id: Id, segmentId: Id, n: z.number().int(), definition: SegmentDefinition, createdBy: z.string(), createdAt: Timestamp });
358
+ export const SegmentVersionList = z.object({ items: z.array(SegmentVersionDto) });
359
+ export const SnapshotDto = z.object({ id: Id, segmentId: Id.nullable(), takenAt: Timestamp, count: z.number().int() });
360
+ const Csv = (max) => z.string().max(max * 40).transform((s) => s.split(',').map((x) => x.trim()).filter(Boolean)).pipe(z.array(z.uuid()).max(max));
361
+ const Bool = z.enum(['true', 'false']).transform((v) => v === 'true');
362
+ export const SEGMENT_SORTS = ['name', '-name', 'created_at', '-created_at', 'updated_at', '-updated_at', 'member_count', '-member_count'];
363
+ /** Members of a segment: filter by email, phone and joined-at; `sort` by joined-at (default: by profile id). */
364
+ export const MembersQuery = PageQuery.extend({
365
+ email: z.string().trim().min(1).max(320).optional(), phone: z.string().trim().min(1).max(32).optional(),
366
+ joinedFrom: Timestamp.optional(), joinedTo: Timestamp.optional(), sort: z.enum(['joined_at', '-joined_at']).optional(),
367
+ });
368
+ /** Segment list: name search (case-insensitive substring), ids, created/updated ranges, active or archived, starred, sort. */
369
+ export const SegmentListQuery = PageQuery.extend({
370
+ q: z.string().max(200).optional(), ids: Csv(100).optional(),
371
+ createdFrom: Timestamp.optional(), createdTo: Timestamp.optional(), updatedFrom: Timestamp.optional(), updatedTo: Timestamp.optional(),
372
+ active: Bool.optional(), starred: Bool.optional(), app: AppSlug.optional(), sort: z.enum(SEGMENT_SORTS).optional(),
373
+ });
374
+ export const EvaluateResult = z.object({ queued: z.literal(true) });
375
+ export const SegmentDiffQuery = z.object({ from: z.iso.datetime({ offset: true }).or(z.iso.date()), to: z.iso.datetime({ offset: true }).or(z.iso.date()) });
376
+ const DiffSide = z.object({
377
+ count: z.number().int(),
378
+ sample: z.array(z.object({ profileId: Id, email: z.string().nullable(), firstName: z.string().nullable(), lastName: z.string().nullable(), at: Timestamp })),
379
+ });
380
+ export const SegmentDiff = z.object({ segmentId: Id, from: Timestamp, to: Timestamp, joined: DiffSide, left: DiffSide });
381
+ // ---- explain match ------------------------------------------------------------------------------------------------
382
+ export const SegmentExplainMatchBody = z.object({ definition: SegmentDefinition, profileId: Id });
383
+ const SegmentMatchNodeSchema = z.lazy(() => z.object({ kind: z.enum(['group', 'condition']), label: z.string(), matched: z.boolean(), op: z.enum(['and', 'or']).optional(), negated: z.boolean().optional(), children: z.array(SegmentMatchNodeSchema).optional() })).meta({ id: 'SegmentMatchNode' });
384
+ export const SegmentExplainMatch = z.object({ segmentId: Id.nullable(), profileId: Id, matched: z.boolean(), member: z.boolean().nullable(), tree: SegmentMatchNodeSchema, evaluatedAt: Timestamp });
385
+ // ---- builder helpers: suggestions, export -------------------------------------------------------------------------
386
+ export const SegmentSuggestQuery = z.object({
387
+ source: z.enum(['event', 'profile', 'consent', 'list_meta']),
388
+ /** Event name for source=event; list id for source=list_meta. */
389
+ name: z.string().max(128).optional(),
390
+ /** Property path (`Items[].Name`), or a profile field / `attributes.x`; for list_meta a membership key, or `*` for the keys in use. */
391
+ path: z.string().min(1).max(300),
392
+ /** source=consent only: limit to one channel. */
393
+ channel: Channel.optional(),
394
+ });
395
+ export const SegmentSuggestResult = z.object({ values: z.array(z.object({ value: z.string(), count: z.number().int() })) });
396
+ export const SegmentExportResult = z.object({ filename: z.string(), csv: z.string(), count: z.number().int(), truncated: z.boolean() });
397
+ // ---- settings: spend tiers, geocoding ------------------------------------------------------------------------------
398
+ export const SegmentSpendTiers = z.object({ mid: z.number().min(0), high: z.number().min(0), top: z.number().min(0) })
399
+ .refine((t) => t.mid < t.high && t.high < t.top, 'Each tier boundary must be higher than the one before');
400
+ /** Evaluation tuning; defaults (60 min, 60 s, 20) are the behaviour before these became settings. */
401
+ export const SegmentEvalSettings = z.object({
402
+ sweepMinutes: z.number().int().min(15).max(1440),
403
+ evalTimeoutSeconds: z.number().int().min(5).max(300),
404
+ previewSampleSize: z.number().int().min(5).max(100),
405
+ });
406
+ export const SegmentSettingsDto = z.object({ spendTiers: SegmentSpendTiers, geocoder: z.enum(['none', 'opencage']), geocoderKeySet: z.boolean() }).extend(SegmentEvalSettings.shape);
407
+ export const UpdateSegmentSettingsBody = SegmentEvalSettings.partial().extend({
408
+ spendTiers: SegmentSpendTiers.optional(),
409
+ geocoder: z.enum(['none', 'opencage']).optional(),
410
+ /** Write-only; an empty string removes the stored key. */
411
+ geocoderKey: z.string().max(200).optional(),
412
+ });
413
+ const PlaceKey = z.object({ country: ProximityCountry, postalCode: z.string().trim().min(2).max(16) });
414
+ export const SegmentPlaceCheckBody = PlaceKey;
415
+ export const SegmentPlaceBody = PlaceKey.extend({ lat: z.number().min(-90).max(90), lng: z.number().min(-180).max(180) });
416
+ export const SegmentPlaceStatus = z.object({
417
+ placed: z.boolean(), lat: z.number().nullable(), lng: z.number().nullable(), source: z.string().nullable(),
418
+ /** Profiles whose position is known (own coordinates, or a placed postal code). */
419
+ profilesPositioned: z.number().int(), profilesTotal: z.number().int(), geocoder: z.enum(['none', 'opencage']),
420
+ });
421
+ export const SegmentGeocodeResult = z.object({ placed: z.number().int(), failed: z.number().int(), remaining: z.number().int() });