@sonordev/contracts 2.20.0 → 2.22.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,27 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.22.0
4
+
5
+ - Add one additive set of rules for retargeting several properties from one campaign. A Meta channel can now carry an optional `channelGroup`, `property`, `tier`, `primaryText` and `convertersAcknowledged`. Channels in one group must share their site, account, dataset, Page, categories, countries, objective and optimization, each property keeps its own destination, and tiers of one property can't overlap in time. A grouped campaign's allocations can't exceed its total less its reserve, and a special category in a group requires provider-managed age. A definition that uses none of these fields parses and serializes exactly as before.
6
+ - Add `checkChannelGroups`, `splitBudget`, `suggestPropertyWeights` and `expandPropertyChannels`. The split conserves the total in whole provider quanta, the suggestion keeps every share between a floor and a ceiling, and the expander builds new property channels from the group's first channel with deterministic ids. It never sets a creative, a converter acknowledgement or an approval, and expanding twice is a no-op.
7
+ - Add an optional `minDaysSinceVisit` recency band to an audience reference and to the audience draft, `checkAudienceBand`, and the exported `META_WEBSITE_AUDIENCE_MAX_RETENTION_DAYS` (180), so the editor, the API and the contract share one number. Meta audiences hold at most ten rules, and Google audiences take no band.
8
+ - Add `metaExclusionPolicy` and `META_SAC_CUSTOM_AUDIENCE_EXCLUSION_VERIFIED`, which ships `false`: targeting-level exclusion under a special category stays refused until a reviewed release proves it. Add `META_CALL_TO_ACTIONS`, the one list the editor and compiler validate against.
9
+ - Raise the public observation page bound from 300 to 500 metrics, because one provider row can now expand to five (spend, impressions, clicks, reach and results). The bound of 100 native rows is unchanged.
10
+ - Add the provider metrics `reach` and `results`, the counting unit `provider_unique_reach` (reach only, never summed across channels), and `deriveProviderRatios`, the one place frequency and cost per result are computed. Zero, missing and mixed inputs are unknown with a reason, never zero.
11
+ - Add three optional fields to the Resonance measurement configuration: `metaEligible` on a page resource rule (absent means false), and `browserWitness` and `tagManagerAttested` on a Meta destination. Configurations that omit them parse as before and mean no Meta browser loading.
12
+
13
+ ## 2.21.0
14
+
15
+ - 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.
16
+
17
+ - Refuse observed provider metrics paired with unestablished support while retaining unknown per-metric values on complete query snapshots.
18
+
19
+ - 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.
20
+
21
+ - 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.
22
+
23
+ - 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.
24
+
3
25
  ## 2.20.0
4
26
 
5
27
  - 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
@@ -1554,6 +1611,8 @@ The native sequence starts with a managed draft and its owned sites; channels ca
1554
1611
 
1555
1612
  Measurement configuration CAS is scoped to project/site. Zero expects actual absence; a legacy or malformed row without protected provenance must block. An audit campaign's revision check doesn't partition the site configuration or advance that campaign's review revision. `projectResonanceMeasurementConfiguration(command, context)` accepts an authorized project, protected current projection, reloaded safe page facts and a native transport expiry. It derives one rule per actual page UUID, sorted by page ID. The page resource revision is canonical UTC milliseconds; the rule revision is the existing full native evidence digest. This preserves distinctions between source updates within one millisecond. Native SQL must independently validate the facts and recompute CAS decisions under its locks.
1556
1613
 
1614
+ A page resource rule can carry `metaEligible`. It is set by a person with owner or admin standing, absent means false, and the browser never decides it. A Meta destination can carry `browserWitness`, the server's capability witness for the browser pixel loader (`controlsRevision`, `policyRevision`, `witnessId`, `assertedAt`), and `tagManagerAttested` for a site whose approved configuration states that its tag manager installs no Meta pixel. All three are optional, so earlier configurations still parse, and a configuration without a witness loads no Meta browser code.
1615
+
1557
1616
  Native semantic `configRevision` and `policyRevision` are positive decimal strings. Identical semantics and a new cache expiry preserve them. Page evidence, selected rules or enabled-state changes advance the configuration revision; only consent-policy changes advance the policy revision. Initial provider destinations are `[]`; updates preserve explicitly configured destinations. The helper returns the configuration, friendly page projections and `configurationDigestInput` from the existing `resonanceMeasurementConfigDigestInput`. Hash that exact string once. The save-request digest helper retains original request array order, while derived semantic pages and purposes are sorted.
1558
1617
 
1559
1618
  Measurement `Current` distinguishes actual `unconfigured` revision zero from a saved `configured` projection with current reasons. `Snapshot` contains the original audit campaign, operation, configuration and friendly page evidence. `SaveResponse` adds `replayed`. The native owner must return an exact original same-key result before fresh CAS/source checks, while enforcing current read permission; a changed request conflicts. No parser proves native provenance.
@@ -1599,3 +1658,64 @@ Native owners plan separate original configuration and accepted feed-review read
1599
1658
  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
1659
 
1601
1660
  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.
1661
+
1662
+
1663
+ ### Reported-cost SQL clock candidate
1664
+
1665
+ 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.
1666
+
1667
+ The evidence discriminator is `reported_cpql_sql_clock_v1`. It retains allocation/channel fields, replacing the legacy uncertaintySource with two required closed objects:
1668
+
1669
+ - `channelReportedCost`: basis, protected immutable observationId, sourceEvidenceDigest, reportedSpend, exact queriedFrom/queriedThrough, actual firstReceivedAt/receivedAt, native recordedAt, required readClock, providerFinality unknown and correctionsPossible true.
1670
+ - `outcomeSource`: method `observational_cpql_missing_outcome_bound_v1`, eligibleContacts, fullyResolvedContacts, qualifiedContacts, native sourceRevision, original qualificationRuleRef and universeComplete true.
1671
+
1672
+ 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.
1673
+
1674
+ 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.
1675
+
1676
+ 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.
1677
+
1678
+ `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.
1679
+
1680
+ 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.
1681
+
1682
+
1683
+ ### Public observation pages
1684
+
1685
+ `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.
1686
+
1687
+ 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.
1688
+
1689
+ 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.
1690
+
1691
+ Pagination follows native-row UUID order, with at most 100 native rows and 500 expanded metrics per page (spend, impressions, clicks, reach and results). 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.
1692
+
1693
+
1694
+ ### Original read-only provider reporting grant
1695
+
1696
+ 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.
1697
+
1698
+ 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.
1699
+
1700
+ `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.
1701
+
1702
+ 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.
1703
+
1704
+ 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.
1705
+
1706
+ 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.
1707
+
1708
+ ### Retargeting several properties from one campaign
1709
+
1710
+ A campaign can retarget visitors of several pages, one property each, without sharing audiences or creative between them. Each property is one Meta channel with its own audience, destination, creative and allocation, and the channels carry a shared `channelGroup` (`{ key, label }`). A channel names its `property` (`{ key, label }`) and may name a `tier` (`{ label }`) when one property has several recency tiers. Every one of these fields is optional, so a definition that uses none of them parses and serializes exactly as before.
1711
+
1712
+ `checkChannelGroups` is the one rule for a group. Its channels must share site, account, dataset, Page, special categories, countries, objective and optimization; channels for one property share one destination and channels for different properties don't; no two channels share a property and tier; tiers of one property can't overlap in time; and a group holds at most `RESONANCE_MAX_CHANNELS_PER_GROUP` (20) channels. A channel in a group with a special category must use provider-managed age. When a definition uses groups, the paid allocations can't add up to more than the campaign total less its reserve.
1713
+
1714
+ `splitBudget(total, weights, quantumMicros)` divides a total across whole weights in whole provider quanta, largest remainder first, ties to the lower index, so the shares add up to the total exactly. `suggestPropertyWeights(visitors, { floorBasisPoints, ceilingBasisPoints })` proposes weights in basis points from each property's unique visitors, 10 percent floor and 40 percent ceiling by default. It's a suggestion: equal weights are the default and a person approves any other split. `expandPropertyChannels(definition, groupKey, additions, { quantumMicros, weights })` returns the new channels for properties not yet in the group, built from the group's first channel, with ids derived from the project, campaign slug, group and property so expanding twice changes nothing. It also returns the group's new allocations and the reasons a person still has to act, such as `property_creative_required:<key>`. It never sets a creative, a converter acknowledgement (`convertersAcknowledged`) or an approval. The measurement rule, audience version and destination for a property are native objects you create first and pass in.
1715
+
1716
+ An audience reference can carry `minDaysSinceVisit` (1 to 179), a recency band that keeps only people whose latest visit is at least that many days old. `checkAudienceBand(ref, provider)` requires the band to be shorter than the retention window, caps a Meta window at `META_WEBSITE_AUDIENCE_MAX_RETENTION_DAYS` (180) and a Meta audience at ten rules, and refuses a band on Google. The recency, window and rule checks run on a definition only for a Meta channel that uses a group or a band.
1717
+
1718
+ `metaExclusionPolicy(channel, { targetingLevel, inRule })` answers whether an exclusion is allowed. Under a special category a targeting-level custom-audience exclusion is refused with `meta_exclusion_targeting_blocked_special_category` while `META_SAC_CUSTOM_AUDIENCE_EXCLUSION_VERIFIED` is `false`, and an in-rule exclusion or band is allowed only when Meta's own eligibility readback for that audience says so. `META_CALL_TO_ACTIONS` lists the call-to-action values a Meta ad accepts, and `primaryText` (up to 2200 characters) is the ad's main text, separate from the first card's description.
1719
+
1720
+ Provider metrics gain `reach` (unique people, counting unit `provider_unique_reach`) and `results`. Reach is never added across channels or windows. `deriveProviderRatios(items)` is the one place the ratios are computed, from provider-sourced, observed items that share one observation, channel and window. Frequency is impressions over reach, and cost per result is spend over results rounded half to even at one micro. Zero reach, zero results, a missing input or mixed inputs give an unknown result with a reason, never zero and never a guess.
1721
+
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 };