@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.
@@ -387,14 +387,14 @@ var destination = union2(
387
387
  object2({ kind: literal2("funnel"), id: uuid, ...scope, path, funnelRef: resource, formSlug: text2(80, /^[a-z0-9]+(?:-[a-z0-9]+)*$/), installationRevision: revision }),
388
388
  object2({ kind: literal2("existing_page"), id: uuid, ...scope, path, pageRevision: revision, evidenceDigest: digest })
389
389
  );
390
- var audience = object2({ ...scope, id: uuid, revision, policyRevision: revision, retentionDays: integer2(1, 540), exclusionRuleIds: list2(uuid, 50), consentPurpose: literal2("ad_personalization") });
390
+ var audience = object2({ ...scope, id: uuid, revision, policyRevision: revision, retentionDays: integer2(1, 540), exclusionRuleIds: list2(uuid, 50), minDaysSinceVisit: optional2(integer2(1, 179)), consentPurpose: literal2("ad_personalization") });
391
391
  var experiment = object2({ ...scope, id: uuid, revision: integer2(1), digest });
392
392
  var budget = refine2(object2({ total: money, dailyAllocationCeiling: nullable2(money), reserveMargin: money, startAt: instant, endAt: instant, timeZone, maxChange: money, maxChangeBasisPoints: integer2(0, 1e4), cooldownSeconds: integer2(0, 31536e3) }), (v, p) => {
393
393
  if (Date.parse(v.endAt) <= Date.parse(v.startAt)) fail2(p, "end must follow start");
394
394
  for (const m of [v.reserveMargin, v.maxChange, ...v.dailyAllocationCeiling ? [v.dailyAllocationCeiling] : []]) if (m.currency !== v.total.currency) fail2(p, "currency mismatch");
395
395
  if (BigInt(v.reserveMargin.amountMicros) > BigInt(v.total.amountMicros)) fail2(p, "reserve exceeds total");
396
396
  });
397
- var matureOptimizationPolicy = object2({
397
+ var allocationPolicyFields = {
398
398
  schemaVersion: literal2(1),
399
399
  sourceRef: nullable2(resource),
400
400
  decisionKind: literal2("observational_allocation"),
@@ -411,7 +411,10 @@ var matureOptimizationPolicy = object2({
411
411
  uncertaintyMethod: literal2("observational_cpql_missing_outcome_bound_v1"),
412
412
  attributionModel: choice2("first_party_source", "first_touch", "last_touch", "provider_reported", RESONANCE_ATTRIBUTION_MODEL),
413
413
  requiredChecks: list2(choice2("tracking", "dedupe", "qualification", "uncertainty", "assignment", "power"), 6, 1)
414
- });
414
+ };
415
+ var matureOptimizationPolicy = object2(allocationPolicyFields);
416
+ var reportedPolicyFields = { ...allocationPolicyFields, algorithm: literal2("reported_cpql_conserved_transfer_v1"), costBasis: literal2("provider_reported_snapshot_v1"), costRevisionRisk: literal2("accepted_provisional") };
417
+ var reportedOptimizationPolicy = object2({ ...reportedPolicyFields, readClockKind: literal2("sql_before_provider_read_lower_bound_v1") });
415
418
  function uniqueList(item, max, min = 0) {
416
419
  const base = list2(item, max, min);
417
420
  return field2({ ...base.schema, uniqueItems: true }, (v, p) => {
@@ -446,10 +449,10 @@ var finiteMetaCandidatePolicy = object2({
446
449
  stopRules: uniqueList(finiteStopRule, 8, 8),
447
450
  expiresAt: instant
448
451
  });
449
- var optimizationPolicy = union2(matureOptimizationPolicy, finiteMetaCandidatePolicy);
452
+ var optimizationPolicy = union2(matureOptimizationPolicy, finiteMetaCandidatePolicy, reportedOptimizationPolicy);
450
453
  function parseResonanceOptimizationPolicy(v) {
451
454
  const r = optimizationPolicy.read(v, "optimizationPolicy");
452
- if (r.algorithm === "mature_cpql_conserved_transfer_v1") {
455
+ if (r.algorithm !== "finite_meta_candidates_v1") {
453
456
  unique(r.requiredChecks, "optimizationPolicy.requiredChecks");
454
457
  return r;
455
458
  }
@@ -471,7 +474,39 @@ var search = object2({ ...channelBase, localCampaignKey: text2(80), kind: litera
471
474
  var metaAgeConstraint = union2(refine2(object2({ mode: literal2("bounded"), min: integer2(1, 120), max: integer2(1, 120) }), (v, p) => {
472
475
  if (v.min > v.max) fail2(p, "minimum age exceeds maximum");
473
476
  }), object2({ mode: literal2("omitted") }), object2({ mode: literal2("provider_managed") }));
474
- var meta = object2({ ...channelBase, localCampaignKey: text2(80), kind: literal2("meta_retargeting"), provider: literal2("meta_ads"), accountBindingId: uuid, capabilityRevision: revision, allocation: money, budgetMode: choice2("lifetime", "daily"), audienceRuleRefs: list2(audience, 50, 1), objective: choice2("OUTCOME_LEADS", "OUTCOME_SALES", "OUTCOME_TRAFFIC"), pageRef: object2({ connectionId: uuid, externalId: text2(160), revision }), instagramRef: nullable2(object2({ connectionId: uuid, externalId: text2(160), revision })), datasetRef: object2({ id: text2(160), revision }), conversionGoalRef: resource, optimization: choice2("landing_page_views", "lead", "purchase"), billing: literal2("impressions"), bid: union2(object2({ strategy: literal2("lowest_cost") }), object2({ strategy: literal2("cost_cap"), cap: money })), localAdSetKey: text2(80), localAdKey: text2(80), budgetOwner: choice2("campaign", "adset"), specialCategories: list2(choice2("housing", "employment", "financial_products_services"), 3), countryCodes: list2(text2(2, /^[A-Z]{2}$/), 30, 1), placement: literal2("automatic"), ageConstraint: optional2(metaAgeConstraint) });
477
+ var propertyKey = object2({ key: text2(40, /^[a-z0-9]+(?:-[a-z0-9]+)*$/), label: text2(80) });
478
+ var meta = object2({
479
+ ...channelBase,
480
+ localCampaignKey: text2(80),
481
+ kind: literal2("meta_retargeting"),
482
+ provider: literal2("meta_ads"),
483
+ accountBindingId: uuid,
484
+ capabilityRevision: revision,
485
+ allocation: money,
486
+ budgetMode: choice2("lifetime", "daily"),
487
+ audienceRuleRefs: list2(audience, 50, 1),
488
+ objective: choice2("OUTCOME_LEADS", "OUTCOME_SALES", "OUTCOME_TRAFFIC"),
489
+ pageRef: object2({ connectionId: uuid, externalId: text2(160), revision }),
490
+ instagramRef: nullable2(object2({ connectionId: uuid, externalId: text2(160), revision })),
491
+ datasetRef: object2({ id: text2(160), revision }),
492
+ conversionGoalRef: resource,
493
+ optimization: choice2("landing_page_views", "lead", "purchase"),
494
+ billing: literal2("impressions"),
495
+ bid: union2(object2({ strategy: literal2("lowest_cost") }), object2({ strategy: literal2("cost_cap"), cap: money })),
496
+ localAdSetKey: text2(80),
497
+ localAdKey: text2(80),
498
+ budgetOwner: choice2("campaign", "adset"),
499
+ specialCategories: list2(choice2("housing", "employment", "financial_products_services"), 3),
500
+ countryCodes: list2(text2(2, /^[A-Z]{2}$/), 30, 1),
501
+ placement: literal2("automatic"),
502
+ ageConstraint: optional2(metaAgeConstraint),
503
+ // Property retargeting (one channel per property under one group). Every field is optional and omitted from the canonical form when absent, so no existing reviewed digest changes.
504
+ channelGroup: optional2(propertyKey),
505
+ property: optional2(propertyKey),
506
+ tier: optional2(object2({ label: text2(40) })),
507
+ primaryText: optional2(text2(2200)),
508
+ convertersAcknowledged: optional2(literal2(true))
509
+ });
475
510
  var owned = object2({ ...channelBase, kind: choice2("funnel", "broadcast", "outreach"), resourceRef: resource });
476
511
  var channel = union2(search, meta, owned);
477
512
  var definitionFields = { schemaVersion: literal2(1), projectId: uuid, name: text2(160), slug: refine2(text2(80), (v, p) => {
@@ -517,6 +552,9 @@ function checkDefinition(v) {
517
552
  if ("bidding" in c && "target" in c.bidding && c.bidding.target.currency !== v.budget.total.currency) fail2("campaign.channels.bidding", "currency mismatch");
518
553
  if ("allocation" in c && c.allocation.currency !== v.budget.total.currency) fail2("campaign.channels.allocation", "currency mismatch");
519
554
  }
555
+ checkChannelGroups(v.channels);
556
+ checkGroupedAllocations(v);
557
+ for (const c of v.channels) if (c.kind === "meta_retargeting") checkMetaAudienceBands(c, "campaign.channels.audienceRuleRefs");
520
558
  const policy = v.optimization.policy;
521
559
  if (policy.algorithm === "finite_meta_candidates_v1") {
522
560
  const guard = policy.measurementGuard, goal = v.objective;
@@ -573,14 +611,37 @@ var websiteVisitFeed = object2({ profile: literal2(RESONANCE_WEBSITE_VISIT_PROFI
573
611
  matchingProfileRef
574
612
  }), 100, 1) });
575
613
  var RESONANCE_WEBSITE_VISIT_FEED_JSON_SCHEMA = websiteVisitFeed.schema;
576
- var mandateScope = object2({ projectId: uuid, campaignId: uuid, preparedPlanId: uuid, reviewDigest: digest, accountBindingIds: list2(uuid, 100), sites: list2(site, 50, 1), budget, creativeRefs: list2(creative, 100, 1), audienceRuleRefs: list2(audience, 100), goal: objective, allowedOperations: mandateAllowedOperations, allowedTransformationRef: nullable2(resource), expiresAt: instant, websiteVisitFeed: optional2(websiteVisitFeed) });
577
- function parseResonanceMandateScope(v) {
614
+ var providerReportingChannelIds = refine2(uniqueList(uuid, 100, 1), (ids, p) => unique(ids.map((id) => id.toLowerCase()), p));
615
+ var providerReportingSelection = object2({ agentContactId: uuid, channelIds: providerReportingChannelIds });
616
+ var providerReportingGrant = refine2(object2({ purpose: literal2("provider_reporting_refresh"), orgId: uuid, projectId: uuid, agentContactId: uuid, principalContactId: uuid, channelIds: providerReportingChannelIds }), (v, p) => {
617
+ if (v.agentContactId.toLowerCase() === v.principalContactId.toLowerCase()) fail2(p + ".principalContactId", "agent and human principal must remain distinct");
618
+ });
619
+ var parseResonanceProviderReportingSelection = (v) => providerReportingSelection.read(v, "providerReportingSelection");
620
+ var parseResonanceProviderReportingGrant = (v) => providerReportingGrant.read(v, "providerReportingGrant");
621
+ var RESONANCE_PROVIDER_REPORTING_SELECTION_JSON_SCHEMA = providerReportingSelection.schema;
622
+ var RESONANCE_PROVIDER_REPORTING_GRANT_JSON_SCHEMA = providerReportingGrant.schema;
623
+ var mandateScope = object2({ projectId: uuid, campaignId: uuid, preparedPlanId: uuid, reviewDigest: digest, accountBindingIds: list2(uuid, 100), sites: list2(site, 50, 1), budget, creativeRefs: list2(creative, 100, 1), audienceRuleRefs: list2(audience, 100), goal: objective, allowedOperations: mandateAllowedOperations, allowedTransformationRef: nullable2(resource), expiresAt: instant, websiteVisitFeed: optional2(websiteVisitFeed), providerReporting: optional2(providerReportingGrant) });
624
+ function parseResonanceMandateScope(v, preparedPlan) {
578
625
  const r = mandateScope.read(v, "mandateScope");
579
626
  scoped(r, r.projectId, r.sites, "mandateScope");
580
627
  if (r.websiteVisitFeed) {
581
628
  unique(r.websiteVisitFeed.channels.map((c) => c.channelId), "mandateScope.websiteVisitFeed.channels");
582
629
  for (const c of r.websiteVisitFeed.channels) unique(c.resourceRuleRefs.map((rule) => rule.id), "mandateScope.websiteVisitFeed.resourceRuleRefs");
583
630
  }
631
+ if (r.providerReporting) {
632
+ const grant = r.providerReporting, p = "mandateScope.providerReporting";
633
+ if (grant.projectId !== r.projectId) fail2(p + ".projectId", "must match the original mandate project");
634
+ if (Date.parse(r.expiresAt) <= Date.parse(r.budget.startAt) || Date.parse(r.expiresAt) > Date.parse(r.budget.endAt)) fail2(p, "reporting remains inside the original mandate flight and expiry");
635
+ if (preparedPlan !== void 0) {
636
+ const plan = parseResonancePreparedPlan(preparedPlan);
637
+ if (r.projectId !== plan.projectId || r.campaignId !== plan.campaignId || r.preparedPlanId !== plan.id || r.reviewDigest !== plan.reviewDigest || canonical(r.goal) !== canonical(plan.definition.objective) || canonical(r.budget) !== canonical(plan.definition.budget)) fail2(p, "requires the exact original plan, review, goal and flight");
638
+ if (r.sites.some((site2) => !plan.definition.sites.includes(site2)) || r.accountBindingIds.some((id) => !plan.accounts.some((account) => account.id === id))) fail2(p, "mandate sites and accounts must stay inside the original plan");
639
+ for (const id of grant.channelIds) {
640
+ const channel2 = plan.definition.channels.find((c) => c.id === id);
641
+ if (!channel2 || !("provider" in channel2) || !r.sites.includes(channel2.site) || !r.accountBindingIds.includes(channel2.accountBindingId)) fail2(p + ".channelIds", "requires an explicit original paid channel inside mandate sites and accounts");
642
+ }
643
+ }
644
+ }
584
645
  return r;
585
646
  }
586
647
  var websiteVisitTimes = object2({ occurredAt: instant, receivedAt: instant });
@@ -855,12 +916,13 @@ function parseResonanceCampaignView(v) {
855
916
  var metricValue = union2(object2({ kind: literal2("count"), count: decimal }), object2({ kind: literal2("money"), money }), object2({ kind: literal2("ratio"), numerator: decimal, denominator: refine2(decimal, (v, p) => {
856
917
  if (v === "0") fail2(p, "zero denominator");
857
918
  }) }));
858
- var metricBase = { ...scope, campaignId: uuid, name: choice2("impressions", "clicks", "spend", "accepted_goals", "qualified_goals", "revenue", "conversion_rate"), source: choice2("first_party", "provider", "experiment"), sourceRef: revision, goalRevision: nullable2(revision), countingUnit: choice2("unique_source", "unique_qualified_contact", "net_order", "provider_aggregate"), windowStart: instant, windowEnd: instant, timeZone, attributionModel: nullable2(text2(100)), asOf: instant, dataThrough: nullable2(instant), maturityDelaySeconds: integer2(0), coverageBasisPoints: nullable2(integer2(0, 1e4)), eligibleExposures: nullable2(decimal), matureOutcomes: nullable2(decimal), native: nullable2(object2({ unit: text2(80), amount: decimal, currency: nullable2(currency), unitExponent: integer2(0, 9), providerVersion: text2(30) })) };
919
+ var metricBase = { ...scope, campaignId: uuid, name: choice2("impressions", "clicks", "spend", "accepted_goals", "qualified_goals", "revenue", "conversion_rate", "reach", "results"), source: choice2("first_party", "provider", "experiment"), sourceRef: revision, goalRevision: nullable2(revision), countingUnit: choice2("unique_source", "unique_qualified_contact", "net_order", "provider_aggregate", "provider_unique_reach"), windowStart: instant, windowEnd: instant, timeZone, attributionModel: nullable2(text2(100)), asOf: instant, dataThrough: nullable2(instant), maturityDelaySeconds: integer2(0), coverageBasisPoints: nullable2(integer2(0, 1e4)), eligibleExposures: nullable2(decimal), matureOutcomes: nullable2(decimal), native: nullable2(object2({ unit: text2(80), amount: decimal, currency: nullable2(currency), unitExponent: integer2(0, 9), providerVersion: text2(30) })) };
859
920
  var metric = union2(object2({ ...metricBase, state: literal2("observed"), value: metricValue }), object2({ ...metricBase, state: choice2("unknown", "insufficient", "delayed", "unavailable"), value: literal2(null), reasonCode: text2(80) }));
860
921
  function parseResonanceMetricObservation(v) {
861
922
  const r = metric.read(v, "metric");
862
923
  if (["accepted_goals", "qualified_goals", "revenue", "conversion_rate"].includes(r.name) && r.goalRevision === null) fail2("metric.goalRevision", "goal measurement requires explicit revision");
863
924
  if (Date.parse(r.windowEnd) <= Date.parse(r.windowStart)) fail2("metric.window", "invalid window");
925
+ if (r.name === "reach" !== (r.countingUnit === "provider_unique_reach")) fail2("metric.countingUnit", "reach, and only reach, counts unique provider reach");
864
926
  if (r.state === "observed") {
865
927
  const expected = r.name === "spend" || r.name === "revenue" ? "money" : r.name === "conversion_rate" ? "ratio" : "count";
866
928
  if (r.value.kind !== expected) fail2("metric.value", "metric unit mismatch");
@@ -988,15 +1050,18 @@ var allocationHorizon = union2(
988
1050
  );
989
1051
  var uncertaintySource = object2({ method: literal2(RESONANCE_CPQL_UNCERTAINTY_METHOD), eligibleContacts: decimal, fullyResolvedContacts: decimal, qualifiedContacts: decimal, verifiedSpend: money, sourceRevision: revision, qualificationRuleRef: resource, universeComplete: literal2(true), spendPeriodComplete: literal2(true) });
990
1052
  function cpqlMissingOutcomeBound(input) {
1053
+ return conditionalCpqlOutcomeBound(input, input.verifiedSpend);
1054
+ }
1055
+ function conditionalCpqlOutcomeBound(input, spend) {
991
1056
  const n = BigInt(decimal.read(input.eligibleContacts, "bound.eligibleContacts"));
992
1057
  const c = BigInt(decimal.read(input.fullyResolvedContacts, "bound.fullyResolvedContacts"));
993
1058
  const k = BigInt(decimal.read(input.qualifiedContacts, "bound.qualifiedContacts"));
994
1059
  if (c > n || k > c) fail2("bound", "inconsistent unique-contact source universe");
995
- if (n === 0n || k === 0n || parseMoney(input.verifiedSpend).amountMicros === "0") return null;
1060
+ if (n === 0n || k === 0n || parseMoney(spend).amountMicros === "0") return null;
996
1061
  const u = n - c, denominator = 2n * k + u;
997
1062
  return Number((10000n * u + denominator - 1n) / denominator);
998
1063
  }
999
- var matureOptimizationEvidence = object2({
1064
+ var allocationEvidenceFields = {
1000
1065
  id: uuid,
1001
1066
  revision,
1002
1067
  evidenceDigest: digest,
@@ -1017,13 +1082,42 @@ var matureOptimizationEvidence = object2({
1017
1082
  trackingState: choice2("healthy", "blocked", "unknown"),
1018
1083
  coverageBasisPoints: nullable2(integer2(0, 1e4)),
1019
1084
  assignmentCheck: choice2("pass", "failed", "unknown", "not_applicable"),
1020
- powerCheck: choice2("pass", "failed", "unknown", "not_applicable"),
1021
- channels: list2(object2({ channelId: uuid, site, accountBindingId: uuid, trackingState: choice2("healthy", "blocked", "unknown"), coverageBasisPoints: nullable2(integer2(0, 1e4)), coverageFamily: choice2("crm_attribution", "provider_import", "experiment_exposure"), coverageDefinitionRef: resource, coveredNumerator: nullable2(decimal), eligibleDenominator: nullable2(decimal), uncertaintyBasisPoints: nullable2(integer2(0, 1e4)), uncertaintySource: nullable2(uncertaintySource), dedupeCheck: choice2("pass", "failed", "unknown", "not_applicable"), qualificationCheck: choice2("pass", "failed", "unknown", "not_applicable"), reasonCodes: list2(text2(80), 50), capabilityRevision: revision, budgetMode: choice2("campaign_total", "average_daily", "lifetime", "daily"), allocationHorizon: nullable2(allocationHorizon), matureThrough: nullable2(instant), dataThrough: nullable2(instant), goalRevision: revision, countingUnit: choice2("unique_source", "unique_qualified_contact", "net_order"), attributionModel: text2(100), attributionWindowDays: integer2(1, 365), policyRevision: revision, currentAllocation: money, remoteSnapshotDigest: digest, observations: list2(metric, 100), providerUnitExponent: refine2(integer2(0, 6), (v, p) => {
1022
- if (![0, 2, 3, 6].includes(v)) fail2(p, "unsupported provider exponent");
1023
- }), providerMaxUnits: decimal }), 100, 1)
1085
+ powerCheck: choice2("pass", "failed", "unknown", "not_applicable")
1086
+ };
1087
+ var allocationChannelFields = { channelId: uuid, site, accountBindingId: uuid, trackingState: choice2("healthy", "blocked", "unknown"), coverageBasisPoints: nullable2(integer2(0, 1e4)), coverageFamily: choice2("crm_attribution", "provider_import", "experiment_exposure"), coverageDefinitionRef: resource, coveredNumerator: nullable2(decimal), eligibleDenominator: nullable2(decimal), uncertaintyBasisPoints: nullable2(integer2(0, 1e4)), uncertaintySource: nullable2(uncertaintySource), dedupeCheck: choice2("pass", "failed", "unknown", "not_applicable"), qualificationCheck: choice2("pass", "failed", "unknown", "not_applicable"), reasonCodes: list2(text2(80), 50), capabilityRevision: revision, budgetMode: choice2("campaign_total", "average_daily", "lifetime", "daily"), allocationHorizon: nullable2(allocationHorizon), matureThrough: nullable2(instant), dataThrough: nullable2(instant), goalRevision: revision, countingUnit: choice2("unique_source", "unique_qualified_contact", "net_order"), attributionModel: text2(100), attributionWindowDays: integer2(1, 365), policyRevision: revision, currentAllocation: money, remoteSnapshotDigest: digest, observations: list2(metric, 100), providerUnitExponent: refine2(integer2(0, 6), (v, p) => {
1088
+ if (![0, 2, 3, 6].includes(v)) fail2(p, "unsupported provider exponent");
1089
+ }), providerMaxUnits: decimal };
1090
+ var { uncertaintySource: _legacyUncertaintyField, ...reportedChannelFields } = allocationChannelFields;
1091
+ var matureOptimizationEvidence = object2({ ...allocationEvidenceFields, resolvedPolicy: matureOptimizationPolicy, channels: list2(object2({ ...allocationChannelFields, uncertaintySource: nullable2(uncertaintySource) }), 100, 1) });
1092
+ var reportedCostFields = { basis: literal2("provider_reported_snapshot_v1"), observationId: uuid, sourceEvidenceDigest: digest, reportedSpend: money, queriedFrom: instant, queriedThrough: instant, firstReceivedAt: instant, receivedAt: instant, recordedAt: instant, providerFinality: literal2("unknown"), correctionsPossible: literal2(true) };
1093
+ var reportedOutcomeSource = object2({ method: literal2(RESONANCE_CPQL_UNCERTAINTY_METHOD), eligibleContacts: decimal, fullyResolvedContacts: decimal, qualifiedContacts: decimal, sourceRevision: revision, qualificationRuleRef: resource, universeComplete: literal2(true) });
1094
+ var nativeSqlReadInstant = refine2(text2(32, /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,6}))?(?:Z|\+00:00)$/), (v, p) => {
1095
+ const match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,6}))?(?:Z|\+00:00)$/.exec(v);
1096
+ const projected = match[1] + "." + (match[2] ?? "").padEnd(3, "0").slice(0, 3) + "Z";
1097
+ if (!Number.isFinite(Date.parse(projected)) || new Date(projected).toISOString() !== projected) fail2(p, "invalid native SQL UTC instant");
1024
1098
  });
1099
+ var providerReadClock = object2({ kind: literal2("sql_before_provider_read_lower_bound_v1"), notBeforeAt: nativeSqlReadInstant });
1100
+ var channelReportedCost = object2({ ...reportedCostFields, readClock: providerReadClock });
1101
+ var reportedOptimizationEvidence = object2({
1102
+ ...allocationEvidenceFields,
1103
+ evidenceKind: literal2("reported_cpql_sql_clock_v1"),
1104
+ resolvedPolicy: reportedOptimizationPolicy,
1105
+ channels: list2(object2({ ...reportedChannelFields, channelReportedCost, outcomeSource: reportedOutcomeSource }), 100, 1)
1106
+ });
1107
+ function reportedCpqlMissingOutcomeBound(input) {
1108
+ return conditionalCpqlOutcomeBound(input, input.reportedSpend);
1109
+ }
1025
1110
  function parseMatureOptimizationEvidence(v) {
1026
1111
  const r = matureOptimizationEvidence.read(v, "optimizationEvidence");
1112
+ for (const c of r.channels) {
1113
+ if (c.uncertaintySource === null) {
1114
+ if (c.uncertaintyBasisPoints !== null) fail2("optimizationEvidence.channels.uncertainty", "no bound without source witness");
1115
+ } else if (c.uncertaintySource.verifiedSpend.currency !== c.currentAllocation.currency || c.uncertaintyBasisPoints !== cpqlMissingOutcomeBound(c.uncertaintySource)) fail2("optimizationEvidence.channels.uncertainty", "source bound mismatch");
1116
+ }
1117
+ checkAllocationEvidence(r);
1118
+ return r;
1119
+ }
1120
+ function checkAllocationEvidence(r) {
1027
1121
  if (r.objective.measurementRevision !== r.goalRevision) fail2("optimizationEvidence.goalRevision", "goal snapshot mismatch");
1028
1122
  if (Date.parse(r.windowEnd) <= Date.parse(r.windowStart) || r.dataThrough !== null && Date.parse(r.dataThrough) > Date.parse(r.observedAt)) fail2("optimizationEvidence.window", "invalid observed window");
1029
1123
  const sites = r.channels.map((c) => c.site);
@@ -1031,9 +1125,6 @@ function parseMatureOptimizationEvidence(v) {
1031
1125
  unique(r.channels.map((c) => c.channelId), "optimizationEvidence.channels");
1032
1126
  const currency2 = r.channels[0].currentAllocation.currency;
1033
1127
  for (const c of r.channels) {
1034
- if (c.uncertaintySource === null) {
1035
- if (c.uncertaintyBasisPoints !== null) fail2("optimizationEvidence.channels.uncertainty", "no bound without source witness");
1036
- } else if (c.uncertaintySource.verifiedSpend.currency !== c.currentAllocation.currency || c.uncertaintyBasisPoints !== cpqlMissingOutcomeBound(c.uncertaintySource)) fail2("optimizationEvidence.channels.uncertainty", "source bound mismatch");
1037
1128
  if (c.allocationHorizon !== null && (["campaign_total", "lifetime"].includes(c.budgetMode) ? c.allocationHorizon.kind !== "finite_period" : c.allocationHorizon.kind !== "daily_average")) fail2("optimizationEvidence.channels.allocationHorizon", "unapproved budget period normalization");
1038
1129
  if (c.coveredNumerator === null || c.eligibleDenominator === null || c.eligibleDenominator === "0") {
1039
1130
  if (c.coverageBasisPoints !== null) fail2("optimizationEvidence.channels.coverage", "unknown denominator means unknown coverage");
@@ -1050,8 +1141,50 @@ function parseMatureOptimizationEvidence(v) {
1050
1141
  if (observation.campaignId !== r.campaignId || observation.site !== c.site) fail2("optimizationEvidence.channels.observations", "scope mismatch");
1051
1142
  }
1052
1143
  }
1144
+ }
1145
+ function parseReportedOptimizationEvidence(v) {
1146
+ const r = reportedOptimizationEvidence.read(v, "optimizationEvidence");
1147
+ checkReportedAllocationEvidence(r);
1053
1148
  return r;
1054
1149
  }
1150
+ function checkReportedAllocationEvidence(r) {
1151
+ const p = "optimizationEvidence";
1152
+ parseResonanceOptimizationPolicy(r.resolvedPolicy);
1153
+ if (r.objective.source.kind !== "qualified_lead" || r.objective.countingUnit !== "unique_qualified_contact" || !r.objective.qualificationRuleRef || r.objective.qualificationRuleRef.module !== "crm") fail2(p + ".objective", "requires the original independent qualified-contact source");
1154
+ if (r.dataThrough !== null) fail2(p + ".dataThrough", "query coverage cannot become mature provider dataThrough");
1155
+ unique(r.channels.map((c) => c.channelReportedCost.observationId), p + ".channels.channelReportedCost.observationId");
1156
+ const observedAt = Date.parse(r.observedAt), windowStart = Date.parse(r.windowStart), windowEnd = Date.parse(r.windowEnd);
1157
+ if (windowEnd <= windowStart || windowEnd > observedAt) fail2(p + ".window", "requires a completed observed interval");
1158
+ let commonZone;
1159
+ for (const c of r.channels) {
1160
+ const cost = c.channelReportedCost, outcome = c.outcomeSource;
1161
+ if (c.dataThrough !== null) fail2(p + ".channels.dataThrough", "query coverage cannot become mature provider dataThrough");
1162
+ if (Date.parse(cost.queriedFrom) !== windowStart || Date.parse(cost.queriedThrough) !== windowEnd) fail2(p + ".channels.channelReportedCost", "requires the exact common query interval");
1163
+ const firstReceived = Date.parse(cost.firstReceivedAt), received = Date.parse(cost.receivedAt), recorded = Date.parse(cost.recordedAt);
1164
+ const anchor = Date.parse(cost.readClock.notBeforeAt);
1165
+ if (received < firstReceived) fail2(p + ".channels.channelReportedCost", "HTTP receipts must retain internal ordering");
1166
+ if (anchor < windowEnd || anchor > recorded || recorded > observedAt || observedAt - anchor > r.resolvedPolicy.maxEvidenceAgeSeconds * 1e3) fail2(p + ".channels.channelReportedCost.readClock", "requires the original fresh SQL-before-HTTP lower bound and SQL receipt order");
1167
+ if (cost.reportedSpend.currency !== c.currentAllocation.currency || canonical(outcome.qualificationRuleRef) !== canonical(r.objective.qualificationRuleRef)) fail2(p + ".channels.outcomeSource", "requires original qualification reference and currency");
1168
+ if (c.uncertaintyBasisPoints !== reportedCpqlMissingOutcomeBound({ ...outcome, reportedSpend: cost.reportedSpend })) fail2(p + ".channels.uncertainty", "conditional source bound mismatch");
1169
+ const spends = c.observations.filter((o) => o.name === "spend");
1170
+ if (spends.length !== 1) fail2(p + ".channels.observations", "requires one exact provider spend snapshot, never overlapping sums");
1171
+ const spend = spends[0];
1172
+ if (spend.state !== "observed" || spend.source !== "provider" || spend.countingUnit !== "provider_aggregate" || spend.attributionModel !== "provider_reported" || spend.value.kind !== "money" || canonical(spend.value.money) !== canonical(cost.reportedSpend) || Date.parse(spend.windowStart) !== windowStart || Date.parse(spend.windowEnd) !== windowEnd || spend.dataThrough !== null || Date.parse(spend.asOf) !== recorded) fail2(p + ".channels.observations", "reported spend must match the exact nonfinal provider snapshot");
1173
+ const outcomes = c.observations.filter((o) => o.name === "qualified_goals");
1174
+ if (outcomes.length !== 1) fail2(p + ".channels.observations", "requires one independent qualified-contact source");
1175
+ const qualified = outcomes[0];
1176
+ if (qualified.state !== "observed" || qualified.source !== "first_party" || qualified.sourceRef !== outcome.sourceRevision || qualified.goalRevision !== r.goalRevision || qualified.countingUnit !== "unique_qualified_contact" || qualified.attributionModel !== r.resolvedPolicy.attributionModel || qualified.value.kind !== "count" || qualified.value.count !== outcome.qualifiedContacts || qualified.eligibleExposures !== outcome.eligibleContacts || qualified.matureOutcomes !== outcome.qualifiedContacts || qualified.dataThrough === null || Date.parse(qualified.dataThrough) < windowEnd || Date.parse(qualified.dataThrough) > observedAt || c.matureThrough === null || Date.parse(c.matureThrough) < windowEnd || Date.parse(c.matureThrough) > observedAt) fail2(p + ".channels.outcomeSource", "requires independent mature qualified-contact evidence");
1177
+ const formatter = new Intl.DateTimeFormat("en-GB", { timeZone: spend.timeZone, hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" });
1178
+ if ([r.windowStart, r.windowEnd].some((t) => new Date(t).getUTCMilliseconds() !== 0 || formatter.format(new Date(t)) !== "00:00:00") || commonZone !== void 0 && commonZone !== spend.timeZone) fail2(p + ".channels.observations", "requires common advertiser-local completed days without rounding");
1179
+ commonZone = spend.timeZone;
1180
+ for (const o of c.observations) {
1181
+ parseResonanceMetricObservation(o);
1182
+ if (o.projectId !== r.projectId || o.campaignId !== r.campaignId || o.site !== c.site || Date.parse(o.windowStart) !== windowStart || Date.parse(o.windowEnd) !== windowEnd || o.timeZone !== spend.timeZone || Date.parse(o.asOf) > observedAt) fail2(p + ".channels.observations", "foreign or mismatched observation interval");
1183
+ if (o.source === "provider" && o.dataThrough !== null) fail2(p + ".channels.observations", "reported provider observation remains nonfinal");
1184
+ }
1185
+ }
1186
+ checkAllocationEvidence(r);
1187
+ }
1055
1188
  var optimizationEvidenceRefFields = { id: uuid, revision, evidenceDigest: digest };
1056
1189
  var optimizationEvidenceRef = object2(optimizationEvidenceRefFields);
1057
1190
  var finiteOwnMeasurement = union2(
@@ -1104,11 +1237,12 @@ var finiteOptimizationEvidence = object2({
1104
1237
  inventoryState: choice2("complete", "incomplete", "unknown"),
1105
1238
  candidates: list2(finiteCandidateObservation, 100, 1)
1106
1239
  });
1107
- var optimizationEvidence = union2(matureOptimizationEvidence, finiteOptimizationEvidence);
1240
+ var optimizationEvidence = union2(matureOptimizationEvidence, finiteOptimizationEvidence, reportedOptimizationEvidence);
1108
1241
  function parseResonanceOptimizationEvidence(v, preparedPlan) {
1109
1242
  const r = optimizationEvidence.read(v, "optimizationEvidence");
1110
1243
  if (preparedPlan !== void 0) checkOptimizationEvidencePlan(r, parseResonancePreparedPlan(preparedPlan));
1111
1244
  if (!("evidenceKind" in r)) return parseMatureOptimizationEvidence(r);
1245
+ if (r.evidenceKind === "reported_cpql_sql_clock_v1") return parseReportedOptimizationEvidence(r);
1112
1246
  const p = "optimizationEvidence", policy = parseResonanceOptimizationPolicy(r.resolvedPolicy);
1113
1247
  if (r.objective.measurementRevision !== r.goalRevision || r.objective.countingUnit !== "unique_qualified_contact" || canonical(policy.measurementGuard.sourceRef) !== canonical(r.objective.source) || canonical(policy.measurementGuard.qualificationRuleRef) !== canonical(r.objective.qualificationRuleRef) || policy.measurementGuard.maturityDelaySeconds !== r.objective.maturityDelaySeconds) fail2(p + ".objective", "finite policy must retain the original qualified objective");
1114
1248
  if (Date.parse(r.windowEnd) <= Date.parse(r.windowStart) || r.dataThrough !== null && Date.parse(r.dataThrough) > Date.parse(r.observedAt)) fail2(p + ".window", "invalid observed window");
@@ -1129,8 +1263,8 @@ function parseResonanceOptimizationEvidence(v, preparedPlan) {
1129
1263
  parseResonanceMetricObservation(o);
1130
1264
  if (o.projectId !== r.projectId || o.campaignId !== r.campaignId || o.site !== c.site) fail2(p + ".candidates.ownMeasurement", "foreign candidate measurement scope");
1131
1265
  if (Date.parse(o.asOf) > Date.parse(r.observedAt) || Date.parse(o.windowStart) < Date.parse(r.windowStart) || Date.parse(o.windowEnd) > Date.parse(r.windowEnd) || o.dataThrough !== null && Date.parse(o.dataThrough) > Date.parse(r.observedAt)) fail2(p + ".candidates.ownMeasurement", "outside the actual candidate evidence window");
1132
- const aggregate = o.source === "provider" && ["spend", "clicks", "impressions"].includes(o.name);
1133
- if (aggregate ? o.countingUnit !== "provider_aggregate" || o.attributionModel !== "provider_reported" || o.goalRevision !== null && o.goalRevision !== r.goalRevision : o.source !== "first_party" || o.goalRevision !== r.goalRevision || o.countingUnit !== r.objective.countingUnit || o.attributionModel !== policy.measurementGuard.attributionModel) fail2(p + ".candidates.ownMeasurement", "preserve actual provider aggregate versus first-party cohort provenance");
1266
+ const aggregate = o.source === "provider" && RESONANCE_PROVIDER_METRIC_NAMES.includes(o.name);
1267
+ if (aggregate ? o.countingUnit !== providerCountingUnit(o.name) || o.attributionModel !== "provider_reported" || o.goalRevision !== null && o.goalRevision !== r.goalRevision : o.source !== "first_party" || o.goalRevision !== r.goalRevision || o.countingUnit !== r.objective.countingUnit || o.attributionModel !== policy.measurementGuard.attributionModel) fail2(p + ".candidates.ownMeasurement", "preserve actual provider aggregate versus first-party cohort provenance");
1134
1268
  }
1135
1269
  }
1136
1270
  return r;
@@ -1139,6 +1273,15 @@ function checkOptimizationEvidencePlan(e, plan) {
1139
1273
  const p = "optimizationEvidence";
1140
1274
  if (e.projectId !== plan.projectId || e.campaignId !== plan.campaignId || e.preparedPlanId !== plan.id || e.reviewDigest !== plan.reviewDigest || canonical(e.objective) !== canonical(plan.definition.objective) || canonical(e.resolvedPolicy) !== canonical(plan.resolvedEvidencePolicy)) fail2(p + ".preparedPlanId", "requires the exact original prepared scope and policy");
1141
1275
  if (!("evidenceKind" in e)) return;
1276
+ if (e.evidenceKind === "reported_cpql_sql_clock_v1") {
1277
+ const cohort = plan.resolvedQualificationRule?.cohort;
1278
+ if (!cohort || Date.parse(e.windowStart) < Date.parse(cohort.startAt) || Date.parse(e.windowEnd) > Date.parse(cohort.endAt)) fail2(p + ".window", "outside the original frozen qualification cohort");
1279
+ for (const c of e.channels) {
1280
+ const original = plan.definition.channels.find((x) => x.id === c.channelId), account = plan.accounts.find((x) => x.id === c.accountBindingId);
1281
+ if (!original || !("provider" in original) || original.site !== c.site || original.accountBindingId !== c.accountBindingId || !account || c.observations.some((o) => o.timeZone !== account.timeZone)) fail2(p + ".channels", "reported evidence must retain original channel/account/site/timezone");
1282
+ }
1283
+ return;
1284
+ }
1142
1285
  for (const observed of e.candidates) {
1143
1286
  const original = plan.definition.channels.find((c) => c.id === observed.channelId), preview2 = plan.channelPreviews.find((c) => c.channelId === observed.channelId);
1144
1287
  if (!original || original.kind !== "meta_retargeting" || !preview2 || observed.site !== original.site || observed.accountBindingId !== original.accountBindingId || canonical(observed.cap) !== canonical(original.allocation) || canonical(observed.manifestRef) !== canonical(preview2.manifestRef)) fail2(p + ".candidates", "candidate projection differs from original channel and manifest");
@@ -1218,11 +1361,18 @@ function checkOptimizationDecisionEvidence(d, e) {
1218
1361
  if (d.projectId !== e.projectId || d.campaignId !== e.campaignId || d.preparedPlanId !== e.preparedPlanId || d.reviewDigest !== e.reviewDigest || d.policyDigest !== e.policyDigest || canonical(d.evidenceRef) !== canonical({ id: e.id, revision: e.revision, evidenceDigest: e.evidenceDigest })) fail2(p + ".evidenceRef", "must bind the exact original evidence and review");
1219
1362
  if (Date.parse(d.createdAt) < Date.parse(e.observedAt)) fail2(p + ".createdAt", "precedes actual evidence");
1220
1363
  if (d.decisionKind !== "preapproved_candidate_operation") {
1221
- if ("evidenceKind" in e) fail2(p + ".decisionKind", "mature decisions cannot borrow finite lifecycle evidence");
1364
+ if ("evidenceKind" in e && e.evidenceKind !== "reported_cpql_sql_clock_v1") fail2(p + ".decisionKind", "mature decisions cannot borrow finite lifecycle evidence");
1365
+ if ("evidenceKind" in e && e.evidenceKind === "reported_cpql_sql_clock_v1" ? d.algorithmRevision !== e.resolvedPolicy.algorithm || d.decisionKind !== "observational_allocation" : d.algorithmRevision === "reported_cpql_conserved_transfer_v1") fail2(p + ".algorithmRevision", "reported-cost decisions require the exact reported evidence policy");
1366
+ if ("evidenceKind" in e && e.evidenceKind === "reported_cpql_sql_clock_v1") {
1367
+ const deadline = Math.min(Date.parse(e.observedAt), ...e.channels.flatMap((c) => [Date.parse(c.channelReportedCost.readClock.notBeforeAt), Date.parse(c.channelReportedCost.recordedAt)])) + e.resolvedPolicy.maxEvidenceAgeSeconds * 1e3;
1368
+ if (Date.parse(d.createdAt) > deadline || Date.parse(d.expiresAt) > deadline) fail2(p + ".expiresAt", "outside original HTTP/database evidence freshness");
1369
+ const refs = e.channels.flatMap((c) => [c.channelReportedCost.observationId, c.outcomeSource.sourceRevision]);
1370
+ if (refs.some((ref) => !d.sourceRefs.includes(ref))) fail2(p + ".sourceRefs", "requires immutable reported-cost and independent outcome sources");
1371
+ }
1222
1372
  if (d.algorithmRevision === "finite_meta_candidates_v1") fail2(p + ".algorithmRevision", "mature decisions cannot use the finite algorithm");
1223
1373
  return;
1224
1374
  }
1225
- if (!("evidenceKind" in e)) fail2(p + ".decisionKind", "finite actions require finite lifecycle evidence");
1375
+ if (!("evidenceKind" in e) || e.evidenceKind !== "finite_candidate_lifecycle_v1") fail2(p + ".decisionKind", "finite actions require finite lifecycle evidence");
1226
1376
  const finite = e, policy = finite.resolvedPolicy;
1227
1377
  if (Date.parse(d.createdAt) - Date.parse(finite.observedAt) > policy.measurementGuard.maxEvidenceAgeSeconds * 1e3 || Date.parse(d.expiresAt) > Date.parse(policy.expiresAt)) fail2(p + ".expiresAt", "outside current policy/evidence freshness");
1228
1378
  for (const a of d.candidateActions) {
@@ -1254,9 +1404,11 @@ function checkOptimizationDecisionEvidence(d, e) {
1254
1404
  }
1255
1405
  var RESONANCE_OPTIMIZATION_EVIDENCE_JSON_SCHEMA = optimizationEvidence.schema;
1256
1406
  var RESONANCE_OPTIMIZATION_DECISION_JSON_SCHEMA = optimizationDecision.schema;
1407
+ var metaBrowserWitness = object2({ controlsRevision: text2(60, /^[A-Z][A-Z0-9_]*$/), policyRevision: revision, witnessId: uuid, assertedAt: instant });
1257
1408
  var publicDestination = union2(
1258
1409
  object2({ provider: literal2("google_ads"), id: uuid, tagId: text2(40, /^AW-[0-9]+$/) }),
1259
- object2({ provider: literal2("meta_ads"), id: uuid, pixelId: text2(40, /^[0-9]+$/) })
1410
+ // browserWitness and tagManagerAttested are optional so configurations from before the Meta loader keep parsing; absent means no Meta browser loading.
1411
+ object2({ provider: literal2("meta_ads"), id: uuid, pixelId: text2(40, /^[0-9]+$/), browserWitness: optional2(metaBrowserWitness), tagManagerAttested: optional2(bool) })
1260
1412
  );
1261
1413
  var interestResource = object2({ ...scope, type: choice2("page", "article", "product", "listing"), id: text2(160, /^[a-zA-Z0-9._:-]+$/), revision });
1262
1414
  var measurementConfig = object2({
@@ -1268,7 +1420,8 @@ var measurementConfig = object2({
1268
1420
  enabled: bool,
1269
1421
  consentPolicy: object2({ mode: literal2("basic"), requiredPurposes: list2(purpose, 4, 1) }),
1270
1422
  destinations: list2(publicDestination, 10),
1271
- resourceRules: list2(object2({ id: uuid, revision, site, resource: interestResource, path, interestKey: text2(100, /^[a-zA-Z0-9._:-]+$/) }), 500)
1423
+ // metaEligible is set by a person with owner or admin standing; absent means false. The browser never decides it.
1424
+ resourceRules: list2(object2({ id: uuid, revision, site, resource: interestResource, path, interestKey: text2(100, /^[a-zA-Z0-9._:-]+$/), metaEligible: optional2(bool) }), 500)
1272
1425
  });
1273
1426
  function parseResonanceMeasurementConfig(v) {
1274
1427
  const r = measurementConfig.read(v, "measurementConfig");
@@ -1380,11 +1533,12 @@ var audienceDraft = object2({
1380
1533
  schemaVersion: literal2(1),
1381
1534
  expectedRevision: optional2(integer2(1)),
1382
1535
  idempotencyKey: operationKey,
1383
- definition: object2({ name: text2(160), site, accountBindingId: uuid, resourceRuleId: uuid, excludedResourceRuleIds: list2(uuid, 50), retentionDays: integer2(1, 540), policyRevision: revision, currentConsentPolicyRevision: revision })
1536
+ definition: object2({ name: text2(160), site, accountBindingId: uuid, resourceRuleId: uuid, excludedResourceRuleIds: list2(uuid, 50), retentionDays: integer2(1, 540), minDaysSinceVisit: optional2(integer2(1, 179)), policyRevision: revision, currentConsentPolicyRevision: revision })
1384
1537
  });
1385
1538
  function parseResonanceAudienceDraftSaveCommand(v) {
1386
1539
  const r = audienceDraft.read(v, "audienceDraftSave");
1387
1540
  unique(r.definition.excludedResourceRuleIds, "audienceDraftSave.definition.excludedResourceRuleIds");
1541
+ if (r.definition.minDaysSinceVisit !== void 0 && r.definition.minDaysSinceVisit >= r.definition.retentionDays) fail2("audienceDraftSave.definition.minDaysSinceVisit", "must be shorter than the retention window");
1388
1542
  return r;
1389
1543
  }
1390
1544
  var RESONANCE_AUDIENCE_DRAFT_SAVE_COMMAND_JSON_SCHEMA = audienceDraft.schema;
@@ -1553,6 +1707,7 @@ function checkMetaMaterial(v, p) {
1553
1707
  unique(v.audiences.map((a) => a.audienceRuleRef.id), p + ".audiences");
1554
1708
  unique(v.channel.audienceRuleRefs.map((a) => a.id), p + ".channel.audienceRuleRefs");
1555
1709
  if (v.audiences.length !== v.channel.audienceRuleRefs.length) fail2(p + ".audiences", "must cover exactly the original logical audiences");
1710
+ checkMetaAudienceBands(v.channel, p + ".channel.audienceRuleRefs");
1556
1711
  for (const a of v.audiences) {
1557
1712
  if (!v.channel.audienceRuleRefs.some((ref) => canonical(ref) === canonical(a.audienceRuleRef))) fail2(p + ".audiences", "original logical audience version mismatch");
1558
1713
  unique(a.excludedResourceRuleRefs.map((ref) => ref.id), p + ".audiences.excludedResourceRuleRefs");
@@ -1614,7 +1769,7 @@ var feedSelection = refine2(object2({ channels: list2(object2({ channelId: uuid,
1614
1769
  unique(v.channels.map((c) => c.channelId), p + ".channels");
1615
1770
  for (const c of v.channels) unique(c.resourceRuleRefs.map((ref) => ref.id), p + ".resourceRuleRefs");
1616
1771
  });
1617
- var mandateDraftRequest = object2({ expectedRevision: integer2(1), allowedOperations: mandateAllowedOperations, expiresAt: instant, websiteVisitFeedSelection: optional2(feedSelection) });
1772
+ var mandateDraftRequest = object2({ expectedRevision: integer2(1), allowedOperations: mandateAllowedOperations, expiresAt: instant, websiteVisitFeedSelection: optional2(feedSelection), providerReporting: optional2(providerReportingSelection) });
1618
1773
  var parseResonanceMandateDraftRequest = (v) => mandateDraftRequest.read(v, "mandateDraftRequest");
1619
1774
  var RESONANCE_MANDATE_DRAFT_REQUEST_JSON_SCHEMA = mandateDraftRequest.schema;
1620
1775
  var feedReview = object2({ schemaVersion: literal2(1), approval: mandateApproval, mandateRef, configurations: list2(metaSnapshot, 100), current: object2({ state: choice2("not_enabled", "eligible", "invalidated", "unavailable"), checkedAt: instant, expiresAt: nullable2(instant), reasonCodes: uniqueList(text2(200), 100) }) });
@@ -1646,5 +1801,283 @@ function parseResonanceWebsiteVisitFeedReview(v, context) {
1646
1801
  return r;
1647
1802
  }
1648
1803
  var RESONANCE_WEBSITE_VISIT_FEED_REVIEW_JSON_SCHEMA = feedReview.schema;
1804
+ var observationIdentity = { observationId: uuid, channelId: uuid, versionId: uuid, accountBindingId: uuid };
1805
+ var publicObservationMetric = union2(
1806
+ object2({ ...metricBase, ...observationIdentity, source: choice2("provider", "first_party"), state: literal2("observed"), value: metricValue }),
1807
+ object2({ ...metricBase, ...observationIdentity, source: choice2("provider", "first_party"), state: choice2("unknown", "insufficient", "delayed", "unavailable"), value: literal2(null), reasonCode: text2(80) })
1808
+ );
1809
+ function parseResonancePublicObservationMetric(v) {
1810
+ const r = publicObservationMetric.read(v, "observationItem");
1811
+ const { observationId: _observation, channelId: _channel, versionId: _version, accountBindingId: _account, ...body } = r;
1812
+ parseResonanceMetricObservation(body);
1813
+ return r;
1814
+ }
1815
+ var observationDenominators = object2({ eligibleContacts: nullable2(decimal), fullyResolvedContacts: nullable2(decimal), qualifiedContacts: nullable2(decimal) });
1816
+ var observationSupportFields = { ...observationIdentity, currency, fetchedAt: instant, dataThrough: nullable2(instant), coverage: choice2("unknown", "partial", "complete"), reasonCode: nullable2(text2(80)), denominators: observationDenominators };
1817
+ var firstPartyObservationSupport = object2({ ...observationSupportFields, source: literal2("first_party") });
1818
+ var providerObservationSupport = object2({
1819
+ ...observationSupportFields,
1820
+ source: literal2("provider"),
1821
+ firstReceivedAt: nullable2(instant),
1822
+ receivedAt: nullable2(instant),
1823
+ recordedAt: nullable2(instant),
1824
+ readClock: nullable2(providerReadClock),
1825
+ providerFinality: literal2("unknown"),
1826
+ correctionsPossible: literal2(true),
1827
+ coverageBasis: choice2("closed_query_snapshot", "not_established")
1828
+ });
1829
+ var observationSupport = union2(firstPartyObservationSupport, providerObservationSupport);
1830
+ function parseResonanceObservationSupport(v) {
1831
+ const r = observationSupport.read(v, "observationSupport"), p = "observationSupport", d = r.denominators;
1832
+ if (d.fullyResolvedContacts !== null && (d.eligibleContacts === null || BigInt(d.fullyResolvedContacts) > BigInt(d.eligibleContacts)) || d.qualifiedContacts !== null && (d.fullyResolvedContacts === null || BigInt(d.qualifiedContacts) > BigInt(d.fullyResolvedContacts))) fail2(p + ".denominators", "inconsistent independent contact universe");
1833
+ if (r.source === "provider") {
1834
+ if (Object.values(d).some((v2) => v2 !== null)) fail2(p + ".denominators", "provider reporting cannot supply qualified-contact denominators");
1835
+ if (r.firstReceivedAt !== null && (r.receivedAt === null || Date.parse(r.firstReceivedAt) > Date.parse(r.receivedAt))) fail2(p + ".firstReceivedAt", "preserve actual internal HTTP receipt order");
1836
+ if (r.recordedAt !== null && Date.parse(r.recordedAt) !== Date.parse(r.fetchedAt)) fail2(p + ".recordedAt", "must retain the native immutable SQL write time");
1837
+ if (r.readClock !== null && (r.firstReceivedAt === null || r.receivedAt === null || r.recordedAt === null || Date.parse(r.readClock.notBeforeAt) > Date.parse(r.recordedAt))) fail2(p + ".readClock", "requires actual earliest/final HTTP metadata and SQL lower-bound chronology");
1838
+ if (r.coverageBasis === "closed_query_snapshot" ? r.coverage !== "complete" || r.reasonCode !== null || r.receivedAt === null || r.recordedAt === null || r.dataThrough !== null : r.coverage === "complete") fail2(p + ".coverage", "distinguish revisable query coverage from unestablished legacy reporting");
1839
+ }
1840
+ return r;
1841
+ }
1842
+ var observationsPage = object2({ items: list2(publicObservationMetric, 500), nextCursor: nullable2(uuid), observedAt: instant, support: list2(observationSupport, 500) });
1843
+ function parseResonanceObservationsPage(v) {
1844
+ const r = observationsPage.read(v, "observationsPage"), p = "observationsPage";
1845
+ if (r.items.length !== r.support.length) fail2(p + ".support", "requires one support entry for each metric item");
1846
+ const pairs = /* @__PURE__ */ new Set(), rows = /* @__PURE__ */ new Map(), observedAt = Date.parse(r.observedAt);
1847
+ let previous;
1848
+ const first = r.items[0];
1849
+ for (let i = 0; i < r.items.length; i++) {
1850
+ const item = parseResonancePublicObservationMetric(r.items[i]), s = parseResonanceObservationSupport(r.support[i]), rowId = item.observationId.toLowerCase();
1851
+ if (Object.keys(observationIdentity).some((k) => item[k] !== s[k])) fail2(p + ".support", "item/support observation, channel, version and account must align in order");
1852
+ if (item.source !== s.source || item.projectId !== first.projectId || item.campaignId !== first.campaignId || item.site !== first.site) fail2(p + ".items", "requires one scoped provider or first-party page");
1853
+ if (Date.parse(item.asOf) !== Date.parse(s.fetchedAt) || Date.parse(s.fetchedAt) > observedAt || item.dataThrough === null !== (s.dataThrough === null) || item.dataThrough !== null && s.dataThrough !== null && Date.parse(item.dataThrough) !== Date.parse(s.dataThrough)) fail2(p + ".support", "preserve native SQL observation chronology and data-through meaning");
1854
+ if (item.state === "observed" && item.value.kind === "money" && item.value.money.currency !== s.currency) fail2(p + ".support.currency", "observed money must retain account currency");
1855
+ if (previous !== void 0 && rowId < previous) fail2(p + ".items", "native-row UUID order cannot be replaced by metric/time sorting");
1856
+ previous = rowId;
1857
+ const key = rowId + ":" + item.name;
1858
+ if (pairs.has(key)) fail2(p + ".items", "duplicate observation/metric pair");
1859
+ pairs.add(key);
1860
+ const supportIdentity = { ...s, fetchedAt: Date.parse(s.fetchedAt), dataThrough: s.dataThrough === null ? null : Date.parse(s.dataThrough), ...s.source === "provider" ? { firstReceivedAt: s.firstReceivedAt === null ? null : Date.parse(s.firstReceivedAt), receivedAt: s.receivedAt === null ? null : Date.parse(s.receivedAt), recordedAt: s.recordedAt === null ? null : Date.parse(s.recordedAt) } : {} };
1861
+ const row = canonical({ projectId: item.projectId, campaignId: item.campaignId, site: item.site, channelId: item.channelId, versionId: item.versionId, accountBindingId: item.accountBindingId, source: item.source, windowStart: Date.parse(item.windowStart), windowEnd: Date.parse(item.windowEnd), timeZone: item.timeZone, fetchedAt: Date.parse(s.fetchedAt), support: supportIdentity });
1862
+ if (rows.has(rowId) && rows.get(rowId) !== row) fail2(p + ".support", "one immutable native observation cannot change identity or support across metrics");
1863
+ rows.set(rowId, row);
1864
+ if (s.source === "provider") {
1865
+ if (item.state === "observed" && (s.coverage !== "complete" || s.coverageBasis !== "closed_query_snapshot" || s.reasonCode !== null)) fail2(p + ".support", "observed provider values require complete genuine closed-query support");
1866
+ if (!RESONANCE_PROVIDER_METRIC_NAMES.includes(item.name) || item.sourceRef !== item.observationId || item.countingUnit !== providerCountingUnit(item.name) || item.attributionModel !== "provider_reported") fail2(p + ".items", "provider metrics retain exact native observation and aggregate semantics");
1867
+ if (s.readClock !== null && Date.parse(s.readClock.notBeforeAt) < Date.parse(item.windowEnd)) fail2(p + ".support.readClock", "SQL pre-read lower bound must follow the completed query window");
1868
+ } else {
1869
+ const d = s.denominators;
1870
+ if (item.name !== "qualified_goals" || item.countingUnit !== "unique_qualified_contact" || item.goalRevision === null || item.attributionModel !== RESONANCE_ATTRIBUTION_MODEL || item.eligibleExposures !== null || item.matureOutcomes !== null) fail2(p + ".items", "preserve genuine first-party qualification without fabricated exposure counts");
1871
+ const coverage = d.eligibleContacts === null || d.eligibleContacts === "0" || d.fullyResolvedContacts === null ? null : Number(BigInt(d.fullyResolvedContacts) * 10000n / BigInt(d.eligibleContacts));
1872
+ if (item.coverageBasisPoints !== coverage) fail2(p + ".support.denominators", "contact resolution coverage must match the independent universe");
1873
+ if (item.state !== "observed" && (s.coverage === "complete" || s.reasonCode !== item.reasonCode)) fail2(p + ".support", "unresolved qualified sources keep incomplete coverage and their native reason");
1874
+ if (item.state === "observed" && (s.coverage !== "complete" || s.reasonCode !== null || d.eligibleContacts === null || d.fullyResolvedContacts !== d.eligibleContacts || d.qualifiedContacts === null || item.value.kind !== "count" || item.value.count !== d.qualifiedContacts)) fail2(p + ".support", "observed qualified count requires its complete independent native universe");
1875
+ }
1876
+ }
1877
+ if (rows.size > 100) fail2(p + ".items", "at most 100 native rows per page");
1878
+ if (r.nextCursor !== null && (!r.items.length || r.nextCursor.toLowerCase() !== previous)) fail2(p + ".nextCursor", "cursor must retain the final native row, not a metric offset");
1879
+ return r;
1880
+ }
1881
+ var RESONANCE_PUBLIC_OBSERVATION_METRIC_JSON_SCHEMA = publicObservationMetric.schema;
1882
+ var RESONANCE_OBSERVATION_SUPPORT_JSON_SCHEMA = observationSupport.schema;
1883
+ var RESONANCE_OBSERVATIONS_PAGE_JSON_SCHEMA = observationsPage.schema;
1884
+ var META_WEBSITE_AUDIENCE_MAX_RETENTION_DAYS = 180;
1885
+ var META_AUDIENCE_RULE_LIMIT = 10;
1886
+ var META_SAC_CUSTOM_AUDIENCE_EXCLUSION_VERIFIED = false;
1887
+ var META_CALL_TO_ACTIONS = ["LEARN_MORE", "SIGN_UP", "SHOP_NOW", "APPLY_NOW", "BOOK_TRAVEL", "CONTACT_US", "GET_QUOTE"];
1888
+ var RESONANCE_MAX_CHANNELS_PER_GROUP = 20;
1889
+ var RESONANCE_PROVIDER_METRIC_NAMES = ["spend", "impressions", "clicks", "reach", "results"];
1890
+ var providerCountingUnit = (name) => name === "reach" ? "provider_unique_reach" : "provider_aggregate";
1891
+ var isMetaChannel = (c) => c.kind === "meta_retargeting";
1892
+ var usesPropertyModel = (c) => c.channelGroup !== void 0 || c.audienceRuleRefs.some((ref) => ref.minDaysSinceVisit !== void 0);
1893
+ function checkAudienceBand(ref, provider = "meta_ads", at = "audienceRuleRef") {
1894
+ const min = ref.minDaysSinceVisit;
1895
+ if (min !== void 0 && min >= ref.retentionDays) fail2(at + ".minDaysSinceVisit", "must be shorter than the retention window");
1896
+ if (provider === "google_ads") {
1897
+ if (min !== void 0) fail2(at + ".minDaysSinceVisit", "Google audiences have no recency band");
1898
+ return;
1899
+ }
1900
+ if (ref.retentionDays > META_WEBSITE_AUDIENCE_MAX_RETENTION_DAYS) fail2(at + ".retentionDays", `exceeds the ${META_WEBSITE_AUDIENCE_MAX_RETENTION_DAYS}-day Meta website audience maximum`);
1901
+ if (1 + ref.exclusionRuleIds.length + (min === void 0 ? 0 : 1) > META_AUDIENCE_RULE_LIMIT) fail2(at + ".exclusionRuleIds", `a Meta audience holds at most ${META_AUDIENCE_RULE_LIMIT} rules including the page and any recency band`);
1902
+ }
1903
+ function checkMetaAudienceBands(channel2, at) {
1904
+ if (!usesPropertyModel(channel2)) return;
1905
+ channel2.audienceRuleRefs.forEach((ref, index) => checkAudienceBand(ref, "meta_ads", `${at}[${index}]`));
1906
+ }
1907
+ var bandsOverlap = (a, b) => (a.minDaysSinceVisit ?? 0) < b.retentionDays && (b.minDaysSinceVisit ?? 0) < a.retentionDays;
1908
+ function checkChannelGroups(channels) {
1909
+ const groups = /* @__PURE__ */ new Map();
1910
+ for (const c of channels) if (isMetaChannel(c) && c.channelGroup) groups.set(c.channelGroup.key, [...groups.get(c.channelGroup.key) ?? [], c]);
1911
+ for (const [key, members] of groups) {
1912
+ const at = `campaign.channelGroup.${key}`;
1913
+ if (members.length > RESONANCE_MAX_CHANNELS_PER_GROUP) fail2(at, `at most ${RESONANCE_MAX_CHANNELS_PER_GROUP} channels per group`);
1914
+ const first = members[0];
1915
+ const shared = (c) => canonical([c.site, c.accountBindingId, c.datasetRef.id, c.pageRef, c.instagramRef, c.specialCategories, c.countryCodes, c.objective, c.optimization]);
1916
+ const identity = /* @__PURE__ */ new Set(), destinationOf = /* @__PURE__ */ new Map(), propertyOfDestination = /* @__PURE__ */ new Map();
1917
+ for (const c of members) {
1918
+ if (shared(c) !== shared(first)) fail2(at, "channels in one group must share site, account, dataset, Page, categories, countries, objective and optimization");
1919
+ if (c.specialCategories.length > 0 && c.ageConstraint?.mode !== "provider_managed") fail2(at + ".ageConstraint", "a special category requires provider-managed age");
1920
+ const pk = (c.property ?? fail2(at + ".property", "a grouped channel names its property")).key, tier = c.tier?.label ?? "", id = `${pk}|${tier}`;
1921
+ if (identity.has(id)) fail2(at + ".property", "two channels share one property and tier");
1922
+ identity.add(id);
1923
+ if (destinationOf.has(pk) && destinationOf.get(pk) !== c.destinationId) fail2(at + ".destinationId", "channels for one property share one destination");
1924
+ destinationOf.set(pk, c.destinationId);
1925
+ const other = propertyOfDestination.get(c.destinationId);
1926
+ if (other !== void 0 && other !== pk) fail2(at + ".destinationId", "channels for different properties have different destinations");
1927
+ propertyOfDestination.set(c.destinationId, pk);
1928
+ }
1929
+ for (let i = 0; i < members.length; i++) for (let j = i + 1; j < members.length; j++) {
1930
+ if (members[i].property?.key !== members[j].property?.key) continue;
1931
+ for (const a of members[i].audienceRuleRefs) for (const b of members[j].audienceRuleRefs) if (bandsOverlap(a, b)) fail2(at + ".audienceRuleRefs", "tiers of one property cannot overlap in time");
1932
+ }
1933
+ }
1934
+ }
1935
+ function checkGroupedAllocations(v) {
1936
+ if (!v.channels.some((c) => isMetaChannel(c) && c.channelGroup)) return;
1937
+ let sum = 0n;
1938
+ for (const c of v.channels) if ("allocation" in c) sum += BigInt(c.allocation.amountMicros);
1939
+ if (sum > BigInt(v.budget.total.amountMicros) - BigInt(v.budget.reserveMargin.amountMicros)) fail2("campaign.channels.allocation", "channel allocations exceed the campaign total less its reserve");
1940
+ }
1941
+ function splitBudget(total, weights, quantumMicros) {
1942
+ const t = parseMoney(total), at = "splitBudget";
1943
+ if (!/^[1-9][0-9]{0,29}$/.test(quantumMicros)) fail2(at + ".quantumMicros", "must be a positive whole number of micros");
1944
+ if (weights.length < 1 || weights.length > 100 || weights.some((w) => !Number.isSafeInteger(w) || w < 1)) fail2(at + ".weights", "one to 100 positive whole weights");
1945
+ const quantum = BigInt(quantumMicros), micros = BigInt(t.amountMicros);
1946
+ if (micros % quantum !== 0n) fail2(at + ".total", "must be a whole number of provider quanta");
1947
+ const units = micros / quantum, sum = weights.reduce((a, w) => a + BigInt(w), 0n);
1948
+ const parts = weights.map((w, index) => ({ index, floor: units * BigInt(w) / sum, rest: units * BigInt(w) % sum }));
1949
+ let left = units - parts.reduce((a, p) => a + p.floor, 0n);
1950
+ const order = [...parts].sort((a, b) => a.rest === b.rest ? a.index - b.index : a.rest > b.rest ? -1 : 1);
1951
+ const extra = /* @__PURE__ */ new Set();
1952
+ for (const p of order) {
1953
+ if (left === 0n) break;
1954
+ extra.add(p.index);
1955
+ left -= 1n;
1956
+ }
1957
+ return parts.map((p) => ({ currency: t.currency, amountMicros: ((p.floor + (extra.has(p.index) ? 1n : 0n)) * quantum).toString() }));
1958
+ }
1959
+ function suggestPropertyWeights(visitors, bounds = {}) {
1960
+ const floor = bounds.floorBasisPoints ?? 1e3, ceiling = bounds.ceilingBasisPoints ?? 4e3, n = visitors.length, at = "suggestPropertyWeights";
1961
+ if (n < 1 || n > 100 || visitors.some((v) => !Number.isSafeInteger(v) || v < 0)) fail2(at + ".visitors", "one to 100 whole, non-negative visitor counts");
1962
+ if (!Number.isInteger(floor) || !Number.isInteger(ceiling) || floor < 0 || ceiling > 1e4 || floor > ceiling || n * floor > 1e4 || n * ceiling < 1e4) fail2(at + ".bounds", "floor and ceiling cannot hold every share");
1963
+ const weight = visitors.map((v) => v + 1);
1964
+ const total = (lambda) => weight.reduce((a, w) => a + Math.min(ceiling, Math.max(floor, lambda * w)), 0);
1965
+ let low = 0, high = ceiling / Math.min(...weight) + 1;
1966
+ for (let i = 0; i < 200; i++) {
1967
+ const mid = (low + high) / 2;
1968
+ if (total(mid) < 1e4) low = mid;
1969
+ else high = mid;
1970
+ }
1971
+ const share = weight.map((w) => Math.min(ceiling, Math.max(floor, high * w)));
1972
+ const whole = share.map(Math.floor), rest = share.map((value, i) => ({ i, rest: value - whole[i] })).sort((a, b) => b.rest - a.rest || a.i - b.i);
1973
+ let left = 1e4 - whole.reduce((a, b) => a + b, 0);
1974
+ for (const r of rest) {
1975
+ if (left <= 0) break;
1976
+ whole[r.i] += 1;
1977
+ left -= 1;
1978
+ }
1979
+ return whole;
1980
+ }
1981
+ function deterministicUuid(seed) {
1982
+ const mask = (1n << 64n) - 1n, prime = 0x100000001b3n, bytes = new TextEncoder().encode(seed);
1983
+ const hash = (basis) => {
1984
+ let h = basis;
1985
+ for (const b of bytes) {
1986
+ h ^= BigInt(b);
1987
+ h = h * prime & mask;
1988
+ }
1989
+ return h.toString(16).padStart(16, "0");
1990
+ };
1991
+ const hex = hash(0xcbf29ce484222325n) + hash(0x84222325cbf29ce4n);
1992
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-${"89ab"[parseInt(hex[16], 16) & 3]}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
1993
+ }
1994
+ var PLACEHOLDER_CREATIVE_ID = "00000000-0000-4000-8000-000000000000";
1995
+ var clip = (value, max) => value.length <= max ? value : value.slice(0, max);
1996
+ function expandPropertyChannels(definition2, groupKey, additions, options) {
1997
+ const at = "expandPropertyChannels";
1998
+ const group = definition2.channels.filter((c) => isMetaChannel(c) && c.channelGroup?.key === groupKey);
1999
+ if (!group.length) fail2(at + ".group", "needs an existing property channel to use as the template");
2000
+ const template = group[0];
2001
+ const present = new Set(group.map((c) => c.property?.key));
2002
+ const keys = additions.map((a) => a.key);
2003
+ unique(keys, at + ".additions");
2004
+ const fresh = additions.filter((a) => !present.has(a.key));
2005
+ if (!fresh.length) return { channels: [], allocations: [], blockingReasons: [] };
2006
+ const weightOf = (key, own) => own ?? options.weights?.[key] ?? 1;
2007
+ const members = [...group.map((c) => ({ key: c.property.key, id: c.id, weight: weightOf(c.property.key) })), ...fresh.map((a) => ({ key: a.key, id: deterministicUuid(`${definition2.projectId}|${definition2.slug}|${groupKey}|${a.key}`), weight: weightOf(a.key, a.weight) }))];
2008
+ const total = group.reduce((a, c) => addMoney(a, c.allocation), { currency: template.allocation.currency, amountMicros: "0" });
2009
+ const split = splitBudget(total, members.map((m) => m.weight), options.quantumMicros);
2010
+ const allocations = members.map((m, i) => ({ channelId: m.id, allocation: split[i] }));
2011
+ const { tier: _tier, primaryText: _primary, convertersAcknowledged: _converters, ...rest } = template;
2012
+ const channels = fresh.map((a) => {
2013
+ const id = members.find((m) => m.key === a.key).id;
2014
+ const proposal = {
2015
+ ...rest,
2016
+ id,
2017
+ localCampaignKey: clip(`${groupKey}-${a.key}`, 80),
2018
+ localAdSetKey: clip(`${a.key}-visitors`, 80),
2019
+ localAdKey: clip(`${a.key}-1`, 80),
2020
+ property: { key: a.key, label: a.label },
2021
+ destinationId: a.destinationId,
2022
+ audienceRuleRefs: a.audienceRuleRefs,
2023
+ creativeIds: [],
2024
+ allocation: allocations.find((x) => x.channelId === id).allocation
2025
+ };
2026
+ meta.read({ ...proposal, creativeIds: [PLACEHOLDER_CREATIVE_ID] }, at + ".channel");
2027
+ return proposal;
2028
+ });
2029
+ const combined = [...definition2.channels, ...channels.map((c) => ({ ...c, creativeIds: [PLACEHOLDER_CREATIVE_ID] }))];
2030
+ unique(combined.map((c) => c.id), at + ".channels");
2031
+ checkChannelGroups(combined);
2032
+ const changed = group.some((c) => canonical(allocations.find((x) => x.channelId === c.id).allocation) !== canonical(c.allocation));
2033
+ return { channels, allocations, blockingReasons: [...fresh.map((a) => `property_creative_required:${a.key}`), ...changed ? ["rebalance_changes_running_allocations"] : []] };
2034
+ }
2035
+ function metaExclusionPolicy(channel2, use) {
2036
+ const special = channel2.specialCategories.length > 0;
2037
+ if (use.targetingLevel && special && !META_SAC_CUSTOM_AUDIENCE_EXCLUSION_VERIFIED) return { allowed: false, reason: "meta_exclusion_targeting_blocked_special_category", requiresEligibilityReadback: false };
2038
+ return { allowed: true, reason: null, requiresEligibilityReadback: special && (use.inRule || use.targetingLevel) };
2039
+ }
2040
+ function deriveProviderRatios(items) {
2041
+ const unknown = (reasonCode) => ({ frequency: { state: "unknown", reasonCode }, costPerResult: { state: "unknown", reasonCode }, reasonCodes: [reasonCode] });
2042
+ if (!items.length) return unknown("no_inputs");
2043
+ const first = items[0];
2044
+ if (items.some((i) => i.source !== "provider" || i.state !== "observed" || i.observationId === void 0 || i.observationId !== first.observationId || i.channelId !== first.channelId || i.windowStart !== first.windowStart || i.windowEnd !== first.windowEnd)) return unknown("mixed_inputs");
2045
+ const named = (name) => items.filter((i) => i.name === name);
2046
+ if (RESONANCE_PROVIDER_METRIC_NAMES.some((name) => named(name).length > 1)) return unknown("duplicate_metric");
2047
+ const count = (name) => {
2048
+ const i = named(name)[0];
2049
+ return i && i.state === "observed" && i.value?.kind === "count" ? BigInt(i.value.count) : null;
2050
+ };
2051
+ const spend = () => {
2052
+ const i = named("spend")[0];
2053
+ return i && i.state === "observed" && i.value?.kind === "money" ? i.value.money : null;
2054
+ };
2055
+ const reasons = [];
2056
+ let frequency;
2057
+ const impressions = count("impressions"), reach = count("reach");
2058
+ if (impressions === null || reach === null) {
2059
+ frequency = { state: "unknown", reasonCode: impressions === null ? "missing_impressions" : "missing_reach" };
2060
+ reasons.push(frequency.reasonCode);
2061
+ } else if (reach === 0n) {
2062
+ frequency = { state: "unknown", reasonCode: "no_reach" };
2063
+ reasons.push("no_reach");
2064
+ } else frequency = { state: "observed", value: { kind: "ratio", numerator: impressions.toString(), denominator: reach.toString() } };
2065
+ let costPerResult;
2066
+ const money2 = spend(), results = count("results");
2067
+ if (money2 === null || results === null) {
2068
+ costPerResult = { state: "unknown", reasonCode: money2 === null ? "missing_spend" : "missing_results" };
2069
+ reasons.push(costPerResult.reasonCode);
2070
+ } else if (results === 0n) {
2071
+ costPerResult = { state: "unknown", reasonCode: "no_results" };
2072
+ reasons.push("no_results");
2073
+ } else {
2074
+ const micros = BigInt(money2.amountMicros);
2075
+ let quotient = micros / results;
2076
+ const twice = 2n * (micros % results);
2077
+ if (twice > results || twice === results && quotient % 2n === 1n) quotient += 1n;
2078
+ costPerResult = { state: "observed", money: { currency: money2.currency, amountMicros: quotient.toString() } };
2079
+ }
2080
+ return { frequency, costPerResult, reasonCodes: reasons };
2081
+ }
1649
2082
 
1650
- export { MAX_MONEY_MICROS, MONEY_EXPONENT, MONEY_JSON_SCHEMA, RESONANCE_ACCEPT_COMMAND_JSON_SCHEMA, RESONANCE_ACCOUNT_CAPABILITY_JSON_SCHEMA, RESONANCE_ATTRIBUTION_MODEL, RESONANCE_AUDIENCE_DRAFT_SAVE_COMMAND_JSON_SCHEMA, RESONANCE_AUDIENCE_RULE_REF_JSON_SCHEMA, RESONANCE_BINDING_COMMAND_JSON_SCHEMA, RESONANCE_CAMPAIGN_DEFINITION_JSON_SCHEMA, RESONANCE_CAMPAIGN_DRAFT_JSON_SCHEMA, RESONANCE_CAMPAIGN_VIEW_JSON_SCHEMA, RESONANCE_CLICK_IDENTIFIERS_JSON_SCHEMA, RESONANCE_COMMAND_JSON_SCHEMA, RESONANCE_COMMAND_PREPARE_REQUEST_JSON_SCHEMA, RESONANCE_COMMAND_PREPARE_RESPONSE_JSON_SCHEMA, RESONANCE_CONSENT_JSON_SCHEMA, RESONANCE_CONSENT_RESPONSE_JSON_SCHEMA, RESONANCE_CONSENT_UPDATE_JSON_SCHEMA, RESONANCE_CONVERSION_JSON_SCHEMA, RESONANCE_CPQL_UNCERTAINTY_METHOD, RESONANCE_CURRENCIES, RESONANCE_EXPERIMENT_COMPLETE_COMMAND_JSON_SCHEMA, RESONANCE_EXPERIMENT_CREATE_COMMAND_JSON_SCHEMA, RESONANCE_EXPERIMENT_LIFECYCLE_COMMAND_JSON_SCHEMA, RESONANCE_EXPERIMENT_LINK_COMMAND_JSON_SCHEMA, RESONANCE_EXPERIMENT_REF_JSON_SCHEMA, RESONANCE_EXPERIMENT_UPDATE_COMMAND_JSON_SCHEMA, RESONANCE_GOOGLE_CONFIGURATION_REVIEW_JSON_SCHEMA, RESONANCE_GOOGLE_CONFIGURATION_SAVE_COMMAND_JSON_SCHEMA, RESONANCE_GOOGLE_CONFIGURATION_SAVE_RESPONSE_JSON_SCHEMA, RESONANCE_GOOGLE_CONFIGURATION_SNAPSHOT_JSON_SCHEMA, RESONANCE_GOOGLE_CONFIGURATION_VIEW_JSON_SCHEMA, RESONANCE_GOOGLE_SETUP_SPEC_JSON_SCHEMA, RESONANCE_GOOGLE_SIGNAL_SEMANTICS, RESONANCE_GOOGLE_SOURCE_CATEGORIES, RESONANCE_MANDATE_ACTION_KIND, RESONANCE_MANDATE_APPROVAL_JSON_SCHEMA, RESONANCE_MANDATE_DRAFT_REQUEST_JSON_SCHEMA, RESONANCE_MANDATE_REF_JSON_SCHEMA, RESONANCE_MANDATE_SCOPE_JSON_SCHEMA, RESONANCE_MANDATE_TARGET_JSON_SCHEMA, RESONANCE_MEASUREMENT_CONFIGURATION_CURRENT_JSON_SCHEMA, RESONANCE_MEASUREMENT_CONFIGURATION_SAVE_COMMAND_JSON_SCHEMA, RESONANCE_MEASUREMENT_CONFIGURATION_SAVE_RESPONSE_JSON_SCHEMA, RESONANCE_MEASUREMENT_CONFIGURATION_SNAPSHOT_JSON_SCHEMA, RESONANCE_MEASUREMENT_CONFIG_JSON_SCHEMA, RESONANCE_MEASUREMENT_OCCURRENCE_JSON_SCHEMA, RESONANCE_META_CONFIGURATION_SAVE_COMMAND_JSON_SCHEMA, RESONANCE_META_CONFIGURATION_SAVE_RESPONSE_JSON_SCHEMA, RESONANCE_META_CONFIGURATION_SNAPSHOT_JSON_SCHEMA, RESONANCE_META_CONFIGURATION_VIEW_JSON_SCHEMA, RESONANCE_METRIC_JSON_SCHEMA, RESONANCE_OCCURRENCE_RESPONSE_JSON_SCHEMA, RESONANCE_OPTIMIZATION_DECISION_JSON_SCHEMA, RESONANCE_OPTIMIZATION_EVIDENCE_JSON_SCHEMA, RESONANCE_OPTIMIZATION_POLICY_JSON_SCHEMA, RESONANCE_PREPARED_PLAN_JSON_SCHEMA, RESONANCE_QUALIFICATION_RULE_JSON_SCHEMA, RESONANCE_RECEIPT_JSON_SCHEMA, RESONANCE_RESOLVED_QUALIFICATION_RULE_JSON_SCHEMA, RESONANCE_RESOURCE_REF_JSON_SCHEMA, RESONANCE_SAVE_COMMAND_JSON_SCHEMA, RESONANCE_SCHEMA_VERSION, RESONANCE_SOURCE_MARKER_JSON_SCHEMA, RESONANCE_SOURCE_MARKER_PARAMETER, RESONANCE_SUBJECT_HEADER, RESONANCE_SUBJECT_RENEW_COMMAND_JSON_SCHEMA, RESONANCE_WEBSITE_VISIT_FEED_JSON_SCHEMA, RESONANCE_WEBSITE_VISIT_FEED_REVIEW_JSON_SCHEMA, RESONANCE_WEBSITE_VISIT_PROFILE, ResonanceValidationError, addMoney, compareMoney, cpqlMissingOutcomeBound, formatMoney, googleConversionActionSemantics, googleUploadClicksSetupSemantics, moneyFromProviderUnits, moneyToProviderUnits, parseMoney, parseResonanceAcceptCommand, parseResonanceAccountCapability, parseResonanceAudienceDraftSaveCommand, parseResonanceAudienceRuleRef, parseResonanceBindingCommand, parseResonanceCampaignDefinition, parseResonanceCampaignDraft, parseResonanceCampaignSaveCommand, parseResonanceCampaignView, parseResonanceClickIdentifiers, parseResonanceCommand, parseResonanceCommandPrepareRequest, parseResonanceCommandPrepareResponse, parseResonanceConsentResponse, parseResonanceConsentSnapshot, parseResonanceConsentUpdate, parseResonanceConversionEnvelope, parseResonanceExperimentCompleteCommand, parseResonanceExperimentCreateCommand, parseResonanceExperimentExposure, parseResonanceExperimentLifecycleCommand, parseResonanceExperimentLinkCommand, parseResonanceExperimentRef, parseResonanceExperimentUpdateCommand, parseResonanceGoogleConfigurationReview, parseResonanceGoogleConfigurationSaveCommand, parseResonanceGoogleConfigurationSaveResponse, parseResonanceGoogleConfigurationSnapshot, parseResonanceGoogleConfigurationView, parseResonanceGoogleUploadClicksCustomGoalSpec, parseResonanceMandateApprovalPayload, parseResonanceMandateDraftRequest, parseResonanceMandateRef, parseResonanceMandateScope, parseResonanceMandateTarget, parseResonanceMeasurementConfig, parseResonanceMeasurementConfigurationCurrent, parseResonanceMeasurementConfigurationSaveCommand, parseResonanceMeasurementConfigurationSaveResponse, parseResonanceMeasurementConfigurationSnapshot, parseResonanceMeasurementOccurrence, parseResonanceMetaConfigurationSaveCommand, parseResonanceMetaConfigurationSaveResponse, parseResonanceMetaConfigurationSnapshot, parseResonanceMetaConfigurationView, parseResonanceMetricObservation, parseResonanceOccurrenceResponse, parseResonanceOptimizationDecision, parseResonanceOptimizationEvidence, parseResonanceOptimizationPolicy, parseResonancePrepareCommand, parseResonancePreparedPlan, parseResonanceQualificationRule, parseResonanceReceipt, parseResonanceResolvedQualificationRule, parseResonanceResourceRef, parseResonanceSourceMarker, parseResonanceSubjectRenewCommand, parseResonanceWebsiteVisitFeedReview, projectResonanceGoogleConfiguration, projectResonanceMeasurementConfiguration, projectResonanceMetaConfiguration, resonanceCommandDigestInput, resonanceGoogleConfigurationDigestInput, resonanceGoogleSetupDigestInput, resonanceMandateDigestInput, resonanceMeasurementConfigDigestInput, resonanceMeasurementConfigurationSaveDigestInput, resonanceMetaConfigurationDigestInput, resonanceMetaConfigurationSaveDigestInput, resonanceOptimizationDecisionDigestInput, resonanceOptimizationEvidenceDigestInput, resonanceOptimizationPolicyDigestInput, resonancePlanIssues, resonanceWebsiteVisitEventTime, resonanceWebsiteVisitProfileDigestInput, subtractMoney };
2083
+ export { MAX_MONEY_MICROS, META_AUDIENCE_RULE_LIMIT, META_CALL_TO_ACTIONS, META_SAC_CUSTOM_AUDIENCE_EXCLUSION_VERIFIED, META_WEBSITE_AUDIENCE_MAX_RETENTION_DAYS, MONEY_EXPONENT, MONEY_JSON_SCHEMA, RESONANCE_ACCEPT_COMMAND_JSON_SCHEMA, RESONANCE_ACCOUNT_CAPABILITY_JSON_SCHEMA, RESONANCE_ATTRIBUTION_MODEL, RESONANCE_AUDIENCE_DRAFT_SAVE_COMMAND_JSON_SCHEMA, RESONANCE_AUDIENCE_RULE_REF_JSON_SCHEMA, RESONANCE_BINDING_COMMAND_JSON_SCHEMA, RESONANCE_CAMPAIGN_DEFINITION_JSON_SCHEMA, RESONANCE_CAMPAIGN_DRAFT_JSON_SCHEMA, RESONANCE_CAMPAIGN_VIEW_JSON_SCHEMA, RESONANCE_CLICK_IDENTIFIERS_JSON_SCHEMA, RESONANCE_COMMAND_JSON_SCHEMA, RESONANCE_COMMAND_PREPARE_REQUEST_JSON_SCHEMA, RESONANCE_COMMAND_PREPARE_RESPONSE_JSON_SCHEMA, RESONANCE_CONSENT_JSON_SCHEMA, RESONANCE_CONSENT_RESPONSE_JSON_SCHEMA, RESONANCE_CONSENT_UPDATE_JSON_SCHEMA, RESONANCE_CONVERSION_JSON_SCHEMA, RESONANCE_CPQL_UNCERTAINTY_METHOD, RESONANCE_CURRENCIES, RESONANCE_EXPERIMENT_COMPLETE_COMMAND_JSON_SCHEMA, RESONANCE_EXPERIMENT_CREATE_COMMAND_JSON_SCHEMA, RESONANCE_EXPERIMENT_LIFECYCLE_COMMAND_JSON_SCHEMA, RESONANCE_EXPERIMENT_LINK_COMMAND_JSON_SCHEMA, RESONANCE_EXPERIMENT_REF_JSON_SCHEMA, RESONANCE_EXPERIMENT_UPDATE_COMMAND_JSON_SCHEMA, RESONANCE_GOOGLE_CONFIGURATION_REVIEW_JSON_SCHEMA, RESONANCE_GOOGLE_CONFIGURATION_SAVE_COMMAND_JSON_SCHEMA, RESONANCE_GOOGLE_CONFIGURATION_SAVE_RESPONSE_JSON_SCHEMA, RESONANCE_GOOGLE_CONFIGURATION_SNAPSHOT_JSON_SCHEMA, RESONANCE_GOOGLE_CONFIGURATION_VIEW_JSON_SCHEMA, RESONANCE_GOOGLE_SETUP_SPEC_JSON_SCHEMA, RESONANCE_GOOGLE_SIGNAL_SEMANTICS, RESONANCE_GOOGLE_SOURCE_CATEGORIES, RESONANCE_MANDATE_ACTION_KIND, RESONANCE_MANDATE_APPROVAL_JSON_SCHEMA, RESONANCE_MANDATE_DRAFT_REQUEST_JSON_SCHEMA, RESONANCE_MANDATE_REF_JSON_SCHEMA, RESONANCE_MANDATE_SCOPE_JSON_SCHEMA, RESONANCE_MANDATE_TARGET_JSON_SCHEMA, RESONANCE_MAX_CHANNELS_PER_GROUP, RESONANCE_MEASUREMENT_CONFIGURATION_CURRENT_JSON_SCHEMA, RESONANCE_MEASUREMENT_CONFIGURATION_SAVE_COMMAND_JSON_SCHEMA, RESONANCE_MEASUREMENT_CONFIGURATION_SAVE_RESPONSE_JSON_SCHEMA, RESONANCE_MEASUREMENT_CONFIGURATION_SNAPSHOT_JSON_SCHEMA, RESONANCE_MEASUREMENT_CONFIG_JSON_SCHEMA, RESONANCE_MEASUREMENT_OCCURRENCE_JSON_SCHEMA, RESONANCE_META_CONFIGURATION_SAVE_COMMAND_JSON_SCHEMA, RESONANCE_META_CONFIGURATION_SAVE_RESPONSE_JSON_SCHEMA, RESONANCE_META_CONFIGURATION_SNAPSHOT_JSON_SCHEMA, RESONANCE_META_CONFIGURATION_VIEW_JSON_SCHEMA, RESONANCE_METRIC_JSON_SCHEMA, RESONANCE_OBSERVATIONS_PAGE_JSON_SCHEMA, RESONANCE_OBSERVATION_SUPPORT_JSON_SCHEMA, RESONANCE_OCCURRENCE_RESPONSE_JSON_SCHEMA, RESONANCE_OPTIMIZATION_DECISION_JSON_SCHEMA, RESONANCE_OPTIMIZATION_EVIDENCE_JSON_SCHEMA, RESONANCE_OPTIMIZATION_POLICY_JSON_SCHEMA, RESONANCE_PREPARED_PLAN_JSON_SCHEMA, RESONANCE_PROVIDER_METRIC_NAMES, RESONANCE_PROVIDER_REPORTING_GRANT_JSON_SCHEMA, RESONANCE_PROVIDER_REPORTING_SELECTION_JSON_SCHEMA, RESONANCE_PUBLIC_OBSERVATION_METRIC_JSON_SCHEMA, RESONANCE_QUALIFICATION_RULE_JSON_SCHEMA, RESONANCE_RECEIPT_JSON_SCHEMA, RESONANCE_RESOLVED_QUALIFICATION_RULE_JSON_SCHEMA, RESONANCE_RESOURCE_REF_JSON_SCHEMA, RESONANCE_SAVE_COMMAND_JSON_SCHEMA, RESONANCE_SCHEMA_VERSION, RESONANCE_SOURCE_MARKER_JSON_SCHEMA, RESONANCE_SOURCE_MARKER_PARAMETER, RESONANCE_SUBJECT_HEADER, RESONANCE_SUBJECT_RENEW_COMMAND_JSON_SCHEMA, RESONANCE_WEBSITE_VISIT_FEED_JSON_SCHEMA, RESONANCE_WEBSITE_VISIT_FEED_REVIEW_JSON_SCHEMA, RESONANCE_WEBSITE_VISIT_PROFILE, ResonanceValidationError, addMoney, checkAudienceBand, checkChannelGroups, compareMoney, cpqlMissingOutcomeBound, deriveProviderRatios, expandPropertyChannels, formatMoney, googleConversionActionSemantics, googleUploadClicksSetupSemantics, metaExclusionPolicy, moneyFromProviderUnits, moneyToProviderUnits, parseMoney, parseResonanceAcceptCommand, parseResonanceAccountCapability, parseResonanceAudienceDraftSaveCommand, parseResonanceAudienceRuleRef, parseResonanceBindingCommand, parseResonanceCampaignDefinition, parseResonanceCampaignDraft, parseResonanceCampaignSaveCommand, parseResonanceCampaignView, parseResonanceClickIdentifiers, parseResonanceCommand, parseResonanceCommandPrepareRequest, parseResonanceCommandPrepareResponse, parseResonanceConsentResponse, parseResonanceConsentSnapshot, parseResonanceConsentUpdate, parseResonanceConversionEnvelope, parseResonanceExperimentCompleteCommand, parseResonanceExperimentCreateCommand, parseResonanceExperimentExposure, parseResonanceExperimentLifecycleCommand, parseResonanceExperimentLinkCommand, parseResonanceExperimentRef, parseResonanceExperimentUpdateCommand, parseResonanceGoogleConfigurationReview, parseResonanceGoogleConfigurationSaveCommand, parseResonanceGoogleConfigurationSaveResponse, parseResonanceGoogleConfigurationSnapshot, parseResonanceGoogleConfigurationView, parseResonanceGoogleUploadClicksCustomGoalSpec, parseResonanceMandateApprovalPayload, parseResonanceMandateDraftRequest, parseResonanceMandateRef, parseResonanceMandateScope, parseResonanceMandateTarget, parseResonanceMeasurementConfig, parseResonanceMeasurementConfigurationCurrent, parseResonanceMeasurementConfigurationSaveCommand, parseResonanceMeasurementConfigurationSaveResponse, parseResonanceMeasurementConfigurationSnapshot, parseResonanceMeasurementOccurrence, parseResonanceMetaConfigurationSaveCommand, parseResonanceMetaConfigurationSaveResponse, parseResonanceMetaConfigurationSnapshot, parseResonanceMetaConfigurationView, parseResonanceMetricObservation, parseResonanceObservationSupport, parseResonanceObservationsPage, parseResonanceOccurrenceResponse, parseResonanceOptimizationDecision, parseResonanceOptimizationEvidence, parseResonanceOptimizationPolicy, parseResonancePrepareCommand, parseResonancePreparedPlan, parseResonanceProviderReportingGrant, parseResonanceProviderReportingSelection, parseResonancePublicObservationMetric, parseResonanceQualificationRule, parseResonanceReceipt, parseResonanceResolvedQualificationRule, parseResonanceResourceRef, parseResonanceSourceMarker, parseResonanceSubjectRenewCommand, parseResonanceWebsiteVisitFeedReview, projectResonanceGoogleConfiguration, projectResonanceMeasurementConfiguration, projectResonanceMetaConfiguration, reportedCpqlMissingOutcomeBound, resonanceCommandDigestInput, resonanceGoogleConfigurationDigestInput, resonanceGoogleSetupDigestInput, resonanceMandateDigestInput, resonanceMeasurementConfigDigestInput, resonanceMeasurementConfigurationSaveDigestInput, resonanceMetaConfigurationDigestInput, resonanceMetaConfigurationSaveDigestInput, resonanceOptimizationDecisionDigestInput, resonanceOptimizationEvidenceDigestInput, resonanceOptimizationPolicyDigestInput, resonancePlanIssues, resonanceWebsiteVisitEventTime, resonanceWebsiteVisitProfileDigestInput, splitBudget, subtractMoney, suggestPropertyWeights };