@sonordev/contracts 2.20.0 → 2.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.21.0
4
+
5
+ - Add optional, closed `page.experiment` authoring to managed Funnel drafts and definitions, with shared headline/body bounds and variant checks. Keep authored selection separate from the existing native-derived publication manifest. Plain documents stay compatible; older strict parsers reject extended documents, so consumers must adopt together before exposing authoring.
6
+
7
+ - Refuse observed provider metrics paired with unestablished support while retaining unknown per-metric values on complete query snapshots.
8
+
9
+ - Add an optional original read-only provider-reporting grant and a separate closed draft selector. Bind server-resolved scope, agent, principal and paid channels into the existing mandate review/digest while preserving old absent-field bytes. Native identity, original review and current admission remain separate authority checks.
10
+
11
+ - Add closed public observation item, support and page parsers with explicit native identity alignment, mandatory nonfinal provider flags and truthful first-party/unknown metrics. Preserve native-row pagination and the generic metric and optimizer contracts.
12
+
13
+ - Add one explicit SQL pre-read clock policy and evidence branch for conditional reported-cost allocation. Preserve immutable report provenance and independent outcome maturity without cross-clock freshness assumptions. Existing mature, finite and default profiles stay compatible; original native authority, expiry and funding remain separate requirements.
14
+
3
15
  ## 2.20.0
4
16
 
5
17
  - Publish the `resonance`, `resonance-constants` and `signal-experiments` entries with matching CommonJS, ESM and TypeScript surfaces. Add the documentation manifest used by sonor.dev. These validation contracts grant no campaign approval or spending authority.
package/README.md CHANGED
@@ -1162,6 +1162,63 @@ Use `parseFunnelCreateArgs`, `parseFunnelUpdateArgs`, `parseFunnelRevisionArgs`,
1162
1162
  `parseFunnelReadiness`, `parseFunnelOperationReceipt` and the detail/catalog/preview parsers validate bounded response envelopes. Operation receipts bind the exact command target and approved action, and always report zero messages sent by the configuration command. Preview and published-version detail parsers preserve the exact launch or rollback evidence.
1163
1163
 
1164
1164
 
1165
+ ## Authoring Funnel experiments in 2.21.0
1166
+
1167
+ Managed Funnel definitions can optionally save `page.experiment`:
1168
+
1169
+ ```ts
1170
+ import { parseFunnelExperimentAuthoring } from '@sonordev/contracts/funnels'
1171
+
1172
+ const experiment = parseFunnelExperimentAuthoring({
1173
+ experimentId: '11111111-1111-4111-8111-111111111111',
1174
+ experimentRevision: 3,
1175
+ controlVariantKey: 'control',
1176
+ variants: [
1177
+ { variantKey: 'control', content: { headline: 'Workshop news', body: [] } },
1178
+ { variantKey: 'alternative', content: { headline: 'Ideas from the workshop', body: [] } },
1179
+ ],
1180
+ })
1181
+ ```
1182
+
1183
+ This closed author input selects an experiment and supplies keyed headline/body
1184
+ copy. It accepts 2–50 unique variant keys, including the selected control. Keys
1185
+ use the existing 80-character bound; headlines use 160 UTF-16 code units. Bodies
1186
+ use the existing paragraph/bullet limits and 12,000-character aggregate limit per
1187
+ variant. Draft create/update parsers allow blank copy while saving, just like
1188
+ base page copy. `parseFunnelDefinition` and `parseFunnelExperimentAuthoring`
1189
+ require complete copy. The field is supported only on managed pages. Omit it to
1190
+ remove authored experimentation; `null` isn't accepted. Plain Funnel documents
1191
+ and `createFunnelDraft` defaults stay unchanged.
1192
+
1193
+ The authored object accepts only `experimentId`, `experimentRevision`,
1194
+ `controlVariantKey` and `variants`. Each variant accepts only `variantKey` and
1195
+ `content`; content accepts only `headline` and `body`. The base definition keeps
1196
+ one fixed form, offer, brand, route and tracking identity. This input doesn't
1197
+ accept a content digest, goal authority, instance reference or approval flag.
1198
+
1199
+ The native service must resolve the selected real experiment and linked campaign
1200
+ under the current project, site and Full Signal revision, verify the complete
1201
+ native variant set and control, derive the goal from that campaign, and hash each
1202
+ effective full content including the fixed offer. It then produces the existing
1203
+ `PublishedFunnelPage.experimentContent` manifest during normal preview creation.
1204
+ Authored selection is untrusted input; successful parsing grants no readiness,
1205
+ publication, assignment or execution authority. Save, preview, review and publish
1206
+ continue through the existing Funnel lifecycle and approvals. The editor must
1207
+ show every effective variant before review. Lifecycle rebuilds use the saved
1208
+ definition as their content source.
1209
+
1210
+ Matching structural schemas are exported through
1211
+ `FUNNEL_EXPERIMENT_AUTHORING_JSON_SCHEMA`, `FUNNEL_DEFINITION_JSON_SCHEMA`,
1212
+ `FUNNEL_DRAFT_DEFINITION_JSON_SCHEMA` and the existing create/update schemas.
1213
+ Runtime parsers additionally check unique keys, control membership, aggregate
1214
+ body length and managed-page applicability.
1215
+
1216
+ Deploy compatible contracts, parsers, native producer, renderer and editor
1217
+ consumers together before exposing the field. Older strict definition parsers
1218
+ reject `page.experiment` even though the field is optional in 2.21.0. A package
1219
+ upgrade alone doesn't implement native production or authorize publication.
1220
+
1221
+
1165
1222
  ## Adopting 2.20.0
1166
1223
 
1167
1224
  Use the same contracts version in every application that exchanges Resonance
@@ -1599,3 +1656,49 @@ Native owners plan separate original configuration and accepted feed-review read
1599
1656
  The additional closed original Meta intent is `{mode: 'provider_managed'}`. It accepts no bounds, default flag or observed native values and never replaces absent, `omitted` or `bounded` intent. Its review promise is: “Use Meta age settings; record the initial observed configuration before activation.”
1600
1657
 
1601
1658
  Native create and validation requests must omit both age keys. Before activation, the first genuine same-root PAUSED AdSet creator receipt and complete scoped read must seal initial age values **and key presence** once in the existing protected operation. Activation must compare that unchanged observation and every independent non-age, consent, authority and budget gate. Later changes block. This intent makes no claim about exclusive default authorship, unlimited ages, legality or serving. Existing three-mode consumers need explicit preservation, editing and review support before adopting this branch.
1659
+
1660
+
1661
+ ### Reported-cost SQL clock candidate
1662
+
1663
+ The explicit `reported_cpql_conserved_transfer_v1` policy requires `costBasis: 'provider_reported_snapshot_v1'`, `costRevisionRisk: 'accepted_provisional'`, `readClockKind: 'sql_before_provider_read_lower_bound_v1'` and the existing observational allocation thresholds. This is the sole reported-cost policy in this candidate. Earlier unpublished no-clock draft policy/evidence is rejected. Existing mature, finite and default profiles keep their meanings. Adoption requires compatible consumers and this exact policy in the original prepared plan, review and accepted mandate; parsing never grants authority.
1664
+
1665
+ The evidence discriminator is `reported_cpql_sql_clock_v1`. It retains allocation/channel fields, replacing the legacy uncertaintySource with two required closed objects:
1666
+
1667
+ - `channelReportedCost`: basis, protected immutable observationId, sourceEvidenceDigest, reportedSpend, exact queriedFrom/queriedThrough, actual firstReceivedAt/receivedAt, native recordedAt, required readClock, providerFinality unknown and correctionsPossible true.
1668
+ - `outcomeSource`: method `observational_cpql_missing_outcome_bound_v1`, eligibleContacts, fullyResolvedContacts, qualifiedContacts, native sourceRevision, original qualificationRuleRef and universeComplete true.
1669
+
1670
+ The exact readClock is `{kind: 'sql_before_provider_read_lower_bound_v1', notBeforeAt}`. The trusted native producer must await the actual scoped SQL reply before any provider HTTP and bind its unaltered returned lower bound to the same run, target, query and protected immutable source receipt. Caller-supplied, post-read, cached or rebound clocks are invalid. A SQL-generated conservative millisecond lower bound remains a lower bound, never exact HTTP time. The readClock field preserves the actual returned UTC string in evidence/digests, accepting Z or +00:00 with up to six fractional digits; ordinary legacy wire instant formats are unchanged.
1671
+
1672
+ Operational completion, age and decision expiry use SQL chronology: windowEnd <= notBeforeAt <= recordedAt <= observedAt. Raw first/final HTTP receipts remain finite and ordered within their own clock, without numeric comparisons to SQL. Millisecond arithmetic floors any finer native precision conservatively. The native SQL owner must enforce exact retained chronology and current freshness at final claim and every dispatch, together with original mandate/flight limits, actor, kill revision, source and funding guards.
1673
+
1674
+ Keep one exact nonfinal provider spend observation and independent first-party qualified_goals, genuine CRM coverage and channel maturity. Common query windows require completed advertiser-local days with zero milliseconds. Equivalent UTC timestamp representations compare as instants. Query coverage never sets global/channel/provider dataThrough, verifiedSpend or spendPeriodComplete. Passing the actual prepared plan also checks its exact policy/objective, channel/account/site/timezone and frozen qualified cohort.
1675
+
1676
+ `reportedCpqlMissingOutcomeBound` shares the integer outcome sensitivity arithmetic, conditional on reportedSpend. It does not bound cost corrections, establish financial finality, prove causal lift or guarantee cost ordering. Zero cost or no qualified contacts leaves it unavailable. Existing canonical digest functions bind clock kind, immutable cost and independent outcome provenance. Decisions retain observational_allocation/reduce_then_increase, include cost observation IDs and qualification source revisions, and expire by the conservative SQL anchor deadline.
1677
+
1678
+ No new approval surface or engine is introduced. Native budget actions retain their supported original graph and period restrictions. Reported cost releases no donor hold or recipient funding; genuine incremental headroom above reserve remains required. Unknown donor effect stops recipient execution, unsupported funding stays unavailable, and corrections create new immutable history. Parser/schema/source checks cannot authenticate a provider exchange, prove native run binding, grant an action or replace those native checks. This source candidate has no compiled package while the shared build resource is reserved.
1679
+
1680
+
1681
+ ### Public observation pages
1682
+
1683
+ `parseResonanceObservationsPage` reads the existing `{items, nextCursor, observedAt, support}` envelope. Each public item adds four flat native identities to the existing metric: observationId, channelId, versionId and accountBindingId. `parseResonancePublicObservationMetric` extracts those identities and validates the remaining closed metric through the unchanged generic parser. `parseResonanceObservationSupport` validates the closed support union; the page parser then checks cross-object alignment. Matching TypeScript types and JSON schemas are exported from the same Resonance entry. Structural schemas alone do not enforce all semantic relationships.
1684
+
1685
+ Every item has exactly one support entry at the same index, matching all four identities, source, account currency where present, asOf/fetchedAt and dataThrough meaning. A native provider observation may yield spend, impressions and clicks with the same row ID and repeated support; the unique key is observationId plus metric name. Genuine first-party qualified outcomes retain their native row identity and independent qualification sourceRef. Never derive observation identity from that qualification revision or insert contact counts as exposure counts.
1686
+
1687
+ Provider support requires explicit nullable firstReceivedAt, receivedAt, recordedAt and readClock, plus providerFinality unknown, correctionsPossible true and coverageBasis closed_query_snapshot or not_established. Missing required flags fail parsing. First-party support forbids those provider-only fields. A complete closed query remains revisable and does not establish financial finality. Individual clicks or impressions may still be unknown even when row-level query coverage is complete; their value stays null and their metric reason remains separate from the support reason. Legacy/unestablished reporting stays explicit and supplies no operational freshness authority. Raw first/final HTTP timestamps are compared only within their own clock; native readClock bytes retain the final SQL-clock format without restamping.
1688
+
1689
+ Pagination follows native-row UUID order, with at most 100 native rows and 300 expanded metrics per page. A non-null cursor references the last native row, never a metric offset. To display the latest snapshot, group by channel, exact window and metric, then compare support.fetchedAt, which must equal item.asOf as an instant. Do not sum repeated snapshots, turn unknown into zero or infer finality from coverage. The parser preserves reporting data; native API scope, protected producer lineage, original authority, current freshness and funding remain separate requirements.
1690
+
1691
+
1692
+ ### Original read-only provider reporting grant
1693
+
1694
+ The existing mandate draft request accepts optional `providerReporting: {agentContactId, channelIds}`. This closed selector contains only the selected invited agent and explicit channels. It rejects purpose, organization, project, principal and approval fields. Absence stays omitted; null and the superseded Selection-suffix field are invalid. The server must derive the actual organization, project and current invited-agent acts-for principal, never a default agent or the reviewer identity.
1695
+
1696
+ The resolved original mandate has optional `providerReporting: {purpose: 'provider_reporting_refresh', orgId, projectId, agentContactId, principalContactId, channelIds}`. All six fields are required when present. Channels are a unique nonempty UUID list, maximum 100; agent and human principal remain distinct. The grant project must equal the parent mandate project. The original mandate, review payload and canonical digest include the exact resolved binding. No field is backfilled into old mandates and their absent-field digest bytes stay unchanged.
1697
+
1698
+ `ResonanceProviderReportingSelection` and `ResonanceProviderReportingGrant` have separate parser/schema exports. Existing mandate request/scope/approval parsers remain the entry points. Passing the actual prepared plan as the optional second argument to `parseResonanceMandateScope` also checks original plan/review/goal/flight identity and the selected paid channels within mandate sites/accounts and expiry. A public prepared plan has no organization field: exact parent organization equality and real current identities must be established by the protected native owner, not inferred from a project string or parser result.
1699
+
1700
+ This purpose permits read-only report collection and persistence only. It adds no operation, budget mutation, optimization approval, send or child authority. Observation queries must stay within the actual original flight/policy bounds and current native authority. Adding or changing an agent/principal/scope/channel binding requires actual person review through the existing mandate surface; budget-only dominance cannot admit it. The service executor, invited agent and human authorizer remain distinct native actors.
1701
+
1702
+ The existing review surface should display actual named agent, principal and selected scope from the native API projection. Parsing UUIDs is not proof of membership, an invitation, a token, a live acts-for relation or an accepted job claim. Native owners must verify the exact accepted parent grant, organization/project, current job/own claim, actor/principal, kill revision, policy/window, expiry and protected read/write admission before HTTP and persistence. Old mandates without this grant have no scheduled reporting authority. No new approval surface, grant store or bearer retrieval is introduced.
1703
+
1704
+ Observed provider values require complete closed-query support. This is one-way: individual metrics may remain unknown when native query coverage is complete; legacy unknown/null reporting remains readable. It grants no finality, freshness or native authority.
package/dist/funnels.d.ts CHANGED
@@ -93,6 +93,8 @@ export interface FunnelDefinition {
93
93
  body: FunnelBodyBlock[];
94
94
  formId: string;
95
95
  offerAssetId?: string | null;
96
+ /** Authored selection and copy only; native owners verify linkage and derive the published manifest. */
97
+ experiment?: FunnelExperimentAuthoring;
96
98
  };
97
99
  permission: {
98
100
  mode: 'requested_only' | 'marketing_opt_in';
@@ -156,6 +158,20 @@ export interface PublishedFunnelPage {
156
158
  * older strict page parsers reject this field. No assignment/publication grant. */
157
159
  experimentContent?: FunnelExperimentContentManifest;
158
160
  }
161
+ /** Optional saved author input. IDs/revisions select an experiment; they grant no authority.
162
+ * Form, offer, brand, goal and page identity remain fixed on the definition. */
163
+ export interface FunnelExperimentAuthoring {
164
+ experimentId: string;
165
+ experimentRevision: number;
166
+ controlVariantKey: string;
167
+ variants: Array<{
168
+ variantKey: string;
169
+ content: {
170
+ headline: string;
171
+ body: FunnelBodyBlock[];
172
+ };
173
+ }>;
174
+ }
159
175
  export interface FunnelExperimentContentManifest {
160
176
  schemaVersion: 1;
161
177
  kind: 'funnel_experiment_content_v1';
@@ -297,6 +313,24 @@ export declare const FUNNEL_DEFINITION_JSON_SCHEMA: {
297
313
  readonly oneOf?: readonly Shape[];
298
314
  readonly $schema: 'http://json-schema.org/draft-07/schema#';
299
315
  };
316
+ export declare const FUNNEL_EXPERIMENT_AUTHORING_JSON_SCHEMA: {
317
+ readonly type?: 'object' | 'array' | 'string' | 'integer' | 'boolean' | 'null';
318
+ readonly properties?: Record<string, Shape>;
319
+ readonly required?: readonly string[];
320
+ readonly additionalProperties?: false;
321
+ readonly items?: Shape;
322
+ readonly minItems?: number;
323
+ readonly maxItems?: number;
324
+ readonly minLength?: number;
325
+ readonly maxLength?: number;
326
+ readonly pattern?: string;
327
+ readonly minimum?: number;
328
+ readonly maximum?: number;
329
+ readonly enum?: readonly unknown[];
330
+ readonly const?: unknown;
331
+ readonly oneOf?: readonly Shape[];
332
+ readonly $schema: 'http://json-schema.org/draft-07/schema#';
333
+ };
300
334
  export declare const FUNNEL_EXPERIMENT_CONTENT_JSON_SCHEMA: {
301
335
  readonly type?: 'object' | 'array' | 'string' | 'integer' | 'boolean' | 'null';
302
336
  readonly properties?: Record<string, Shape>;
@@ -345,6 +379,9 @@ export declare function isSafeFunnelPublicUrl(value: string): boolean;
345
379
  export declare function managedFunnelPath(value: string): string;
346
380
  export declare function parseFunnelDefinition(value: unknown): FunnelDefinition;
347
381
  export declare function parsePublishedFunnelPage(value: unknown): PublishedFunnelPage;
382
+ /** Complete copy shape only; native project/site/campaign ownership, current
383
+ * experiment revision/keys/control and goal/hash derivation are still required. */
384
+ export declare function parseFunnelExperimentAuthoring(value: unknown): FunnelExperimentAuthoring;
348
385
  /** Shape/content checks only. Native owners verify the complete original Signal
349
386
  * variant set and hash each effective FULL content with existing funnelHash. */
350
387
  export declare function parseFunnelExperimentContent(value: unknown): FunnelExperimentContentManifest;
package/dist/funnels.js CHANGED
@@ -101,6 +101,12 @@ var override = object({
101
101
  var bodyBlock = { oneOf: [object({ type: literal("paragraph"), text: string(2e3) }), object({ type: literal("bullets"), items: array(string(500), 8, 1) })] };
102
102
  var body = array(bodyBlock, 12);
103
103
  var publishedContentFields = { headline: string(160), body };
104
+ var authoredExperimentShape = object({
105
+ experimentId: uuid,
106
+ experimentRevision: integer(1),
107
+ controlVariantKey: string(80),
108
+ variants: array(object({ variantKey: string(80), content: object(publishedContentFields) }), 50, 2)
109
+ });
104
110
  var experimentContentShape = object({
105
111
  schemaVersion: literal(1),
106
112
  kind: literal("funnel_experiment_content_v1"),
@@ -124,7 +130,7 @@ var definitionShape = object({
124
130
  site,
125
131
  entry: object({ formId: uuid, mode: literal("future_accepted_form_only") }),
126
132
  goal: object({ type: enumeration("newsletter_confirmed", "guide_requested", "inquiry_received", "booking_confirmed"), bookingTypeId: nullable(uuid) }, ["type"]),
127
- page: object({ mode: enumeration("existing", "managed"), path, slug: nullable(slug), headline: string(160, 0), body, formId: uuid, offerAssetId: nullable(uuid) }, ["mode", "path", "headline", "body", "formId"]),
133
+ page: object({ mode: enumeration("existing", "managed"), path, slug: nullable(slug), headline: string(160, 0), body, formId: uuid, offerAssetId: nullable(uuid), experiment: authoredExperimentShape }, ["mode", "path", "headline", "body", "formId"]),
128
134
  permission: object({ mode: enumeration("requested_only", "marketing_opt_in"), optInFieldSlug: nullable(fieldSlug) }, ["mode"]),
129
135
  brandOverride: override,
130
136
  steps: array(step, 8),
@@ -147,7 +153,11 @@ draftProps.steps.items.oneOf = draftProps.steps.items.oneOf.map((item) => {
147
153
  if (fields.tag) fields.tag = string(80, 0);
148
154
  return item;
149
155
  });
150
- draftProps.page.properties.body = array({ oneOf: [object({ type: literal("paragraph"), text: string(2e3, 0) }), object({ type: literal("bullets"), items: array(string(500, 0), 8, 1) })] }, 12);
156
+ var draftBody = array({ oneOf: [object({ type: literal("paragraph"), text: string(2e3, 0) }), object({ type: literal("bullets"), items: array(string(500, 0), 8, 1) })] }, 12);
157
+ draftProps.page.properties.body = draftBody;
158
+ var draftExperimentContent = draftProps.page.properties.experiment.properties.variants.items.properties.content.properties;
159
+ draftExperimentContent.headline = string(160, 0);
160
+ draftExperimentContent.body = draftBody;
151
161
  var FUNNEL_DRAFT_DEFINITION_JSON_SCHEMA = { $schema: "http://json-schema.org/draft-07/schema#", ...draftDefinitionShape };
152
162
  function parseFunnelDraftDefinition(value) {
153
163
  var _a, _b, _c, _d, _e;
@@ -161,6 +171,7 @@ function parseFunnelDraftDefinition(value) {
161
171
  (_e = result.exits).confirmedBooking ?? (_e.confirmedBooking = { enabled: false, bookingTypeId: null });
162
172
  for (const item of result.steps) if (item.type === "send_email") item.guideAssetId ?? (item.guideAssetId = null);
163
173
  checkBody(result.page.body, "draft.page.body");
174
+ checkAuthoredExperiment(result.page, "draft.page");
164
175
  if (result.brandOverride) checkFonts(result.brandOverride, "draft.brandOverride");
165
176
  if (result.page.mode === "existing" && result.page.slug !== null) fail("draft.page.slug", "only managed pages have slugs");
166
177
  return result;
@@ -195,6 +206,7 @@ var publishedShape = object({
195
206
  tracking: object({ campaignSlug: slug }),
196
207
  experimentContent: experimentContentShape
197
208
  }, ["schemaVersion", "id", "versionId", "revision", "site", "path", "content", "brand", "conversion", "tracking"]);
209
+ var FUNNEL_EXPERIMENT_AUTHORING_JSON_SCHEMA = { $schema: "http://json-schema.org/draft-07/schema#", ...authoredExperimentShape };
198
210
  var FUNNEL_EXPERIMENT_CONTENT_JSON_SCHEMA = { $schema: "http://json-schema.org/draft-07/schema#", ...experimentContentShape };
199
211
  var PUBLISHED_FUNNEL_PAGE_JSON_SCHEMA = { $schema: "http://json-schema.org/draft-07/schema#", ...publishedShape };
200
212
  var FUNNEL_LAUNCH_JSON_SCHEMA = object({ expectedRevision: integer(1), previewId: uuid, idempotencyKey: string(200), confirm: literal(true) });
@@ -286,6 +298,7 @@ function parseFunnelDefinition(value) {
286
298
  if (result.steps.some((item) => item.type === "send_email" && item.purpose === "marketing") && result.permission.mode !== "marketing_opt_in") fail("definition.permission", "marketing requires explicit opt-in");
287
299
  if (new Set(result.steps.map((item) => item.id)).size !== result.steps.length) fail("definition.steps", "step identities must be unique");
288
300
  checkBody(result.page.body, "definition.page.body");
301
+ checkAuthoredExperiment(result.page, "definition.page");
289
302
  if (result.brandOverride) checkFonts(result.brandOverride, "definition.brandOverride");
290
303
  return result;
291
304
  }
@@ -301,13 +314,27 @@ function parsePublishedFunnelPage(value) {
301
314
  if (result.experimentContent) result.experimentContent = parseFunnelExperimentContent(result.experimentContent);
302
315
  return result;
303
316
  }
317
+ function checkExperimentVariants(value, at) {
318
+ const keys = value.variants.map((variant) => variant.variantKey);
319
+ if (new Set(keys).size !== keys.length) fail(`${at}.variants`, "variant keys must be unique");
320
+ if (!keys.includes(value.controlVariantKey)) fail(`${at}.controlVariantKey`, "must identify an existing variant");
321
+ value.variants.forEach((variant, i) => checkBody(variant.content.body, `${at}.variants[${i}].content.body`));
322
+ }
323
+ function checkAuthoredExperiment(page, at) {
324
+ if (!page.experiment) return;
325
+ if (page.mode !== "managed") fail(`${at}.experiment`, "only managed pages support authored experiment content");
326
+ checkExperimentVariants(page.experiment, `${at}.experiment`);
327
+ }
328
+ function parseFunnelExperimentAuthoring(value) {
329
+ check(value, authoredExperimentShape, "experiment");
330
+ const result = JSON.parse(JSON.stringify(value));
331
+ checkExperimentVariants(result, "experiment");
332
+ return result;
333
+ }
304
334
  function parseFunnelExperimentContent(value) {
305
335
  check(value, experimentContentShape, "experimentContent");
306
336
  const result = JSON.parse(JSON.stringify(value));
307
- const keys = result.variants.map((v) => v.variantKey);
308
- if (new Set(keys).size !== keys.length) fail("experimentContent.variants", "variant keys must be unique");
309
- if (!keys.includes(result.controlVariantKey)) fail("experimentContent.controlVariantKey", "must identify an existing reviewed variant");
310
- result.variants.forEach((variant, i) => checkBody(variant.content.body, `experimentContent.variants[${i}].content.body`));
337
+ checkExperimentVariants(result, "experimentContent");
311
338
  return result;
312
339
  }
313
340
  function resolveFunnelExperimentContent(value, variantKey) {
@@ -595,6 +622,7 @@ exports.FUNNEL_DETAIL_JSON_SCHEMA = FUNNEL_DETAIL_JSON_SCHEMA;
595
622
  exports.FUNNEL_DRAFT_DEFINITION_JSON_SCHEMA = FUNNEL_DRAFT_DEFINITION_JSON_SCHEMA;
596
623
  exports.FUNNEL_DRAFT_JSON_SCHEMAS = FUNNEL_DRAFT_JSON_SCHEMAS;
597
624
  exports.FUNNEL_ENROLLMENT_JSON_SCHEMA = FUNNEL_ENROLLMENT_JSON_SCHEMA;
625
+ exports.FUNNEL_EXPERIMENT_AUTHORING_JSON_SCHEMA = FUNNEL_EXPERIMENT_AUTHORING_JSON_SCHEMA;
598
626
  exports.FUNNEL_EXPERIMENT_CONTENT_JSON_SCHEMA = FUNNEL_EXPERIMENT_CONTENT_JSON_SCHEMA;
599
627
  exports.FUNNEL_LAUNCH_EVIDENCE_JSON_SCHEMA = FUNNEL_LAUNCH_EVIDENCE_JSON_SCHEMA;
600
628
  exports.FUNNEL_LAUNCH_JSON_SCHEMA = FUNNEL_LAUNCH_JSON_SCHEMA;
@@ -629,6 +657,7 @@ exports.parseFunnelDetail = parseFunnelDetail;
629
657
  exports.parseFunnelDraftArgs = parseFunnelDraftArgs;
630
658
  exports.parseFunnelDraftDefinition = parseFunnelDraftDefinition;
631
659
  exports.parseFunnelEnrollmentSummary = parseFunnelEnrollmentSummary;
660
+ exports.parseFunnelExperimentAuthoring = parseFunnelExperimentAuthoring;
632
661
  exports.parseFunnelExperimentContent = parseFunnelExperimentContent;
633
662
  exports.parseFunnelLaunchArgs = parseFunnelLaunchArgs;
634
663
  exports.parseFunnelLaunchEvidence = parseFunnelLaunchEvidence;
package/dist/funnels.mjs CHANGED
@@ -99,6 +99,12 @@ var override = object({
99
99
  var bodyBlock = { oneOf: [object({ type: literal("paragraph"), text: string(2e3) }), object({ type: literal("bullets"), items: array(string(500), 8, 1) })] };
100
100
  var body = array(bodyBlock, 12);
101
101
  var publishedContentFields = { headline: string(160), body };
102
+ var authoredExperimentShape = object({
103
+ experimentId: uuid,
104
+ experimentRevision: integer(1),
105
+ controlVariantKey: string(80),
106
+ variants: array(object({ variantKey: string(80), content: object(publishedContentFields) }), 50, 2)
107
+ });
102
108
  var experimentContentShape = object({
103
109
  schemaVersion: literal(1),
104
110
  kind: literal("funnel_experiment_content_v1"),
@@ -122,7 +128,7 @@ var definitionShape = object({
122
128
  site,
123
129
  entry: object({ formId: uuid, mode: literal("future_accepted_form_only") }),
124
130
  goal: object({ type: enumeration("newsletter_confirmed", "guide_requested", "inquiry_received", "booking_confirmed"), bookingTypeId: nullable(uuid) }, ["type"]),
125
- page: object({ mode: enumeration("existing", "managed"), path, slug: nullable(slug), headline: string(160, 0), body, formId: uuid, offerAssetId: nullable(uuid) }, ["mode", "path", "headline", "body", "formId"]),
131
+ page: object({ mode: enumeration("existing", "managed"), path, slug: nullable(slug), headline: string(160, 0), body, formId: uuid, offerAssetId: nullable(uuid), experiment: authoredExperimentShape }, ["mode", "path", "headline", "body", "formId"]),
126
132
  permission: object({ mode: enumeration("requested_only", "marketing_opt_in"), optInFieldSlug: nullable(fieldSlug) }, ["mode"]),
127
133
  brandOverride: override,
128
134
  steps: array(step, 8),
@@ -145,7 +151,11 @@ draftProps.steps.items.oneOf = draftProps.steps.items.oneOf.map((item) => {
145
151
  if (fields.tag) fields.tag = string(80, 0);
146
152
  return item;
147
153
  });
148
- draftProps.page.properties.body = array({ oneOf: [object({ type: literal("paragraph"), text: string(2e3, 0) }), object({ type: literal("bullets"), items: array(string(500, 0), 8, 1) })] }, 12);
154
+ var draftBody = array({ oneOf: [object({ type: literal("paragraph"), text: string(2e3, 0) }), object({ type: literal("bullets"), items: array(string(500, 0), 8, 1) })] }, 12);
155
+ draftProps.page.properties.body = draftBody;
156
+ var draftExperimentContent = draftProps.page.properties.experiment.properties.variants.items.properties.content.properties;
157
+ draftExperimentContent.headline = string(160, 0);
158
+ draftExperimentContent.body = draftBody;
149
159
  var FUNNEL_DRAFT_DEFINITION_JSON_SCHEMA = { $schema: "http://json-schema.org/draft-07/schema#", ...draftDefinitionShape };
150
160
  function parseFunnelDraftDefinition(value) {
151
161
  var _a, _b, _c, _d, _e;
@@ -159,6 +169,7 @@ function parseFunnelDraftDefinition(value) {
159
169
  (_e = result.exits).confirmedBooking ?? (_e.confirmedBooking = { enabled: false, bookingTypeId: null });
160
170
  for (const item of result.steps) if (item.type === "send_email") item.guideAssetId ?? (item.guideAssetId = null);
161
171
  checkBody(result.page.body, "draft.page.body");
172
+ checkAuthoredExperiment(result.page, "draft.page");
162
173
  if (result.brandOverride) checkFonts(result.brandOverride, "draft.brandOverride");
163
174
  if (result.page.mode === "existing" && result.page.slug !== null) fail("draft.page.slug", "only managed pages have slugs");
164
175
  return result;
@@ -193,6 +204,7 @@ var publishedShape = object({
193
204
  tracking: object({ campaignSlug: slug }),
194
205
  experimentContent: experimentContentShape
195
206
  }, ["schemaVersion", "id", "versionId", "revision", "site", "path", "content", "brand", "conversion", "tracking"]);
207
+ var FUNNEL_EXPERIMENT_AUTHORING_JSON_SCHEMA = { $schema: "http://json-schema.org/draft-07/schema#", ...authoredExperimentShape };
196
208
  var FUNNEL_EXPERIMENT_CONTENT_JSON_SCHEMA = { $schema: "http://json-schema.org/draft-07/schema#", ...experimentContentShape };
197
209
  var PUBLISHED_FUNNEL_PAGE_JSON_SCHEMA = { $schema: "http://json-schema.org/draft-07/schema#", ...publishedShape };
198
210
  var FUNNEL_LAUNCH_JSON_SCHEMA = object({ expectedRevision: integer(1), previewId: uuid, idempotencyKey: string(200), confirm: literal(true) });
@@ -284,6 +296,7 @@ function parseFunnelDefinition(value) {
284
296
  if (result.steps.some((item) => item.type === "send_email" && item.purpose === "marketing") && result.permission.mode !== "marketing_opt_in") fail("definition.permission", "marketing requires explicit opt-in");
285
297
  if (new Set(result.steps.map((item) => item.id)).size !== result.steps.length) fail("definition.steps", "step identities must be unique");
286
298
  checkBody(result.page.body, "definition.page.body");
299
+ checkAuthoredExperiment(result.page, "definition.page");
287
300
  if (result.brandOverride) checkFonts(result.brandOverride, "definition.brandOverride");
288
301
  return result;
289
302
  }
@@ -299,13 +312,27 @@ function parsePublishedFunnelPage(value) {
299
312
  if (result.experimentContent) result.experimentContent = parseFunnelExperimentContent(result.experimentContent);
300
313
  return result;
301
314
  }
315
+ function checkExperimentVariants(value, at) {
316
+ const keys = value.variants.map((variant) => variant.variantKey);
317
+ if (new Set(keys).size !== keys.length) fail(`${at}.variants`, "variant keys must be unique");
318
+ if (!keys.includes(value.controlVariantKey)) fail(`${at}.controlVariantKey`, "must identify an existing variant");
319
+ value.variants.forEach((variant, i) => checkBody(variant.content.body, `${at}.variants[${i}].content.body`));
320
+ }
321
+ function checkAuthoredExperiment(page, at) {
322
+ if (!page.experiment) return;
323
+ if (page.mode !== "managed") fail(`${at}.experiment`, "only managed pages support authored experiment content");
324
+ checkExperimentVariants(page.experiment, `${at}.experiment`);
325
+ }
326
+ function parseFunnelExperimentAuthoring(value) {
327
+ check(value, authoredExperimentShape, "experiment");
328
+ const result = JSON.parse(JSON.stringify(value));
329
+ checkExperimentVariants(result, "experiment");
330
+ return result;
331
+ }
302
332
  function parseFunnelExperimentContent(value) {
303
333
  check(value, experimentContentShape, "experimentContent");
304
334
  const result = JSON.parse(JSON.stringify(value));
305
- const keys = result.variants.map((v) => v.variantKey);
306
- if (new Set(keys).size !== keys.length) fail("experimentContent.variants", "variant keys must be unique");
307
- if (!keys.includes(result.controlVariantKey)) fail("experimentContent.controlVariantKey", "must identify an existing reviewed variant");
308
- result.variants.forEach((variant, i) => checkBody(variant.content.body, `experimentContent.variants[${i}].content.body`));
335
+ checkExperimentVariants(result, "experimentContent");
309
336
  return result;
310
337
  }
311
338
  function resolveFunnelExperimentContent(value, variantKey) {
@@ -585,4 +612,4 @@ function parseFunnelPublishedVersionDetail(value) {
585
612
  }
586
613
  for (const schema of [FUNNEL_LAUNCH_EVIDENCE_JSON_SCHEMA, FUNNEL_ROLLBACK_EVIDENCE_JSON_SCHEMA, FUNNEL_VERSION_JSON_SCHEMA, FUNNEL_VERSION_DETAIL_JSON_SCHEMA]) freezeSchema(schema);
587
614
 
588
- export { FUNNEL_BRAND_SNAPSHOT_JSON_SCHEMA, FUNNEL_CATALOG_JSON_SCHEMA, FUNNEL_CREATE_JSON_SCHEMA, FUNNEL_DEFINITION_JSON_SCHEMA, FUNNEL_DETAIL_JSON_SCHEMA, FUNNEL_DRAFT_DEFINITION_JSON_SCHEMA, FUNNEL_DRAFT_JSON_SCHEMAS, FUNNEL_ENROLLMENT_JSON_SCHEMA, FUNNEL_EXPERIMENT_CONTENT_JSON_SCHEMA, FUNNEL_LAUNCH_EVIDENCE_JSON_SCHEMA, FUNNEL_LAUNCH_JSON_SCHEMA, FUNNEL_LIFECYCLE_JSON_SCHEMA, FUNNEL_OPERATION_RECEIPT_JSON_SCHEMA, FUNNEL_PREVIEW_JSON_SCHEMA, FUNNEL_READINESS_JSON_SCHEMA, FUNNEL_RETRY_JSON_SCHEMA, FUNNEL_REVISION_JSON_SCHEMA, FUNNEL_ROLLBACK_EVIDENCE_JSON_SCHEMA, FUNNEL_ROLLBACK_JSON_SCHEMA, FUNNEL_SCHEMA_VERSION, FUNNEL_SUMMARY_JSON_SCHEMA, FUNNEL_TEMPLATES, FUNNEL_TIMELINE_JSON_SCHEMA, FUNNEL_UPDATE_JSON_SCHEMA, FUNNEL_VERSION_DETAIL_JSON_SCHEMA, FUNNEL_VERSION_JSON_SCHEMA, FunnelValidationError, MANAGED_FUNNEL_PATH_PREFIX, PUBLISHED_FUNNEL_PAGE_JSON_SCHEMA, applyFunnelBrandOverride, createFunnelDraft, isSafeFunnelPublicUrl, managedFunnelPath, normalizeCampaignSlug, parseFunnelBrandSnapshot, parseFunnelCatalog, parseFunnelCreateArgs, parseFunnelDefinition, parseFunnelDetail, parseFunnelDraftArgs, parseFunnelDraftDefinition, parseFunnelEnrollmentSummary, parseFunnelExperimentContent, parseFunnelLaunchArgs, parseFunnelLaunchEvidence, parseFunnelLifecycleArgs, parseFunnelOperationReceipt, parseFunnelPreview, parseFunnelPublishedVersion, parseFunnelPublishedVersionDetail, parseFunnelReadiness, parseFunnelRetryArgs, parseFunnelRevisionArgs, parseFunnelRollbackEvidence, parseFunnelSummary, parseFunnelTimeline, parseFunnelUpdateArgs, parsePublishedFunnelPage, resolveFunnelExperimentContent };
615
+ export { FUNNEL_BRAND_SNAPSHOT_JSON_SCHEMA, FUNNEL_CATALOG_JSON_SCHEMA, FUNNEL_CREATE_JSON_SCHEMA, FUNNEL_DEFINITION_JSON_SCHEMA, FUNNEL_DETAIL_JSON_SCHEMA, FUNNEL_DRAFT_DEFINITION_JSON_SCHEMA, FUNNEL_DRAFT_JSON_SCHEMAS, FUNNEL_ENROLLMENT_JSON_SCHEMA, FUNNEL_EXPERIMENT_AUTHORING_JSON_SCHEMA, FUNNEL_EXPERIMENT_CONTENT_JSON_SCHEMA, FUNNEL_LAUNCH_EVIDENCE_JSON_SCHEMA, FUNNEL_LAUNCH_JSON_SCHEMA, FUNNEL_LIFECYCLE_JSON_SCHEMA, FUNNEL_OPERATION_RECEIPT_JSON_SCHEMA, FUNNEL_PREVIEW_JSON_SCHEMA, FUNNEL_READINESS_JSON_SCHEMA, FUNNEL_RETRY_JSON_SCHEMA, FUNNEL_REVISION_JSON_SCHEMA, FUNNEL_ROLLBACK_EVIDENCE_JSON_SCHEMA, FUNNEL_ROLLBACK_JSON_SCHEMA, FUNNEL_SCHEMA_VERSION, FUNNEL_SUMMARY_JSON_SCHEMA, FUNNEL_TEMPLATES, FUNNEL_TIMELINE_JSON_SCHEMA, FUNNEL_UPDATE_JSON_SCHEMA, FUNNEL_VERSION_DETAIL_JSON_SCHEMA, FUNNEL_VERSION_JSON_SCHEMA, FunnelValidationError, MANAGED_FUNNEL_PATH_PREFIX, PUBLISHED_FUNNEL_PAGE_JSON_SCHEMA, applyFunnelBrandOverride, createFunnelDraft, isSafeFunnelPublicUrl, managedFunnelPath, normalizeCampaignSlug, parseFunnelBrandSnapshot, parseFunnelCatalog, parseFunnelCreateArgs, parseFunnelDefinition, parseFunnelDetail, parseFunnelDraftArgs, parseFunnelDraftDefinition, parseFunnelEnrollmentSummary, parseFunnelExperimentAuthoring, parseFunnelExperimentContent, parseFunnelLaunchArgs, parseFunnelLaunchEvidence, parseFunnelLifecycleArgs, parseFunnelOperationReceipt, parseFunnelPreview, parseFunnelPublishedVersion, parseFunnelPublishedVersionDetail, parseFunnelReadiness, parseFunnelRetryArgs, parseFunnelRevisionArgs, parseFunnelRollbackEvidence, parseFunnelSummary, parseFunnelTimeline, parseFunnelUpdateArgs, parsePublishedFunnelPage, resolveFunnelExperimentContent };
package/dist/outreach.js CHANGED
@@ -1,6 +1,50 @@
1
1
  'use strict';
2
2
 
3
- // src/contracts/business-claims.ts
3
+ // src/contracts/voice.ts
4
+ var TABLE = [
5
+ ["do not", "don't"],
6
+ ["does not", "doesn't"],
7
+ ["did not", "didn't"],
8
+ ["is not", "isn't"],
9
+ ["are not", "aren't"],
10
+ ["was not", "wasn't"],
11
+ ["were not", "weren't"],
12
+ ["cannot", "can't"],
13
+ ["can not", "can't"],
14
+ ["will not", "won't"],
15
+ ["would not", "wouldn't"],
16
+ ["should not", "shouldn't"],
17
+ ["could not", "couldn't"],
18
+ ["has not", "hasn't"],
19
+ ["have not", "haven't"],
20
+ ["had not", "hadn't"],
21
+ ["must not", "mustn't"],
22
+ ["need not", "needn't"],
23
+ ["it is", "it's"],
24
+ ["that is", "that's"],
25
+ ["there is", "there's"],
26
+ ["here is", "here's"],
27
+ ["who is", "who's"],
28
+ ["what is", "what's"],
29
+ ["you are", "you're"],
30
+ ["we are", "we're"],
31
+ ["they are", "they're"],
32
+ ["I am", "I'm"],
33
+ ["you will", "you'll"],
34
+ ["we will", "we'll"],
35
+ ["they will", "they'll"],
36
+ ["it will", "it'll"],
37
+ ["we would", "we'd"],
38
+ ["you would", "you'd"],
39
+ ["they would", "they'd"],
40
+ ["let us", "let's"]
41
+ ];
42
+ TABLE.map(([full, contracted]) => ({
43
+ full,
44
+ contracted,
45
+ negation: / not$|^cannot$/.test(full),
46
+ pattern: new RegExp(`\\b${full.replace(/ /g, "[ \\t]+")}\\b`, "gi")
47
+ }));
4
48
  function fnv1a(text) {
5
49
  let hash = 2166136261;
6
50
  for (let i = 0; i < text.length; i++) {
package/dist/outreach.mjs CHANGED
@@ -1,4 +1,48 @@
1
- // src/contracts/business-claims.ts
1
+ // src/contracts/voice.ts
2
+ var TABLE = [
3
+ ["do not", "don't"],
4
+ ["does not", "doesn't"],
5
+ ["did not", "didn't"],
6
+ ["is not", "isn't"],
7
+ ["are not", "aren't"],
8
+ ["was not", "wasn't"],
9
+ ["were not", "weren't"],
10
+ ["cannot", "can't"],
11
+ ["can not", "can't"],
12
+ ["will not", "won't"],
13
+ ["would not", "wouldn't"],
14
+ ["should not", "shouldn't"],
15
+ ["could not", "couldn't"],
16
+ ["has not", "hasn't"],
17
+ ["have not", "haven't"],
18
+ ["had not", "hadn't"],
19
+ ["must not", "mustn't"],
20
+ ["need not", "needn't"],
21
+ ["it is", "it's"],
22
+ ["that is", "that's"],
23
+ ["there is", "there's"],
24
+ ["here is", "here's"],
25
+ ["who is", "who's"],
26
+ ["what is", "what's"],
27
+ ["you are", "you're"],
28
+ ["we are", "we're"],
29
+ ["they are", "they're"],
30
+ ["I am", "I'm"],
31
+ ["you will", "you'll"],
32
+ ["we will", "we'll"],
33
+ ["they will", "they'll"],
34
+ ["it will", "it'll"],
35
+ ["we would", "we'd"],
36
+ ["you would", "you'd"],
37
+ ["they would", "they'd"],
38
+ ["let us", "let's"]
39
+ ];
40
+ TABLE.map(([full, contracted]) => ({
41
+ full,
42
+ contracted,
43
+ negation: / not$|^cannot$/.test(full),
44
+ pattern: new RegExp(`\\b${full.replace(/ /g, "[ \\t]+")}\\b`, "gi")
45
+ }));
2
46
  function fnv1a(text) {
3
47
  let hash = 2166136261;
4
48
  for (let i = 0; i < text.length; i++) {