@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 +22 -0
- package/README.md +120 -0
- package/dist/funnels.d.ts +37 -0
- package/dist/funnels.js +35 -6
- package/dist/funnels.mjs +34 -7
- package/dist/resonance.d.ts +1583 -84
- package/dist/resonance.js +484 -27
- package/dist/resonance.mjs +461 -28
- package/package.json +1 -1
package/dist/resonance.js
CHANGED
|
@@ -389,14 +389,14 @@ var destination = union2(
|
|
|
389
389
|
object2({ kind: literal2("funnel"), id: uuid, ...scope, path, funnelRef: resource, formSlug: text2(80, /^[a-z0-9]+(?:-[a-z0-9]+)*$/), installationRevision: revision }),
|
|
390
390
|
object2({ kind: literal2("existing_page"), id: uuid, ...scope, path, pageRevision: revision, evidenceDigest: digest })
|
|
391
391
|
);
|
|
392
|
-
var audience = object2({ ...scope, id: uuid, revision, policyRevision: revision, retentionDays: integer2(1, 540), exclusionRuleIds: list2(uuid, 50), consentPurpose: literal2("ad_personalization") });
|
|
392
|
+
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") });
|
|
393
393
|
var experiment = object2({ ...scope, id: uuid, revision: integer2(1), digest });
|
|
394
394
|
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) => {
|
|
395
395
|
if (Date.parse(v.endAt) <= Date.parse(v.startAt)) fail2(p, "end must follow start");
|
|
396
396
|
for (const m of [v.reserveMargin, v.maxChange, ...v.dailyAllocationCeiling ? [v.dailyAllocationCeiling] : []]) if (m.currency !== v.total.currency) fail2(p, "currency mismatch");
|
|
397
397
|
if (BigInt(v.reserveMargin.amountMicros) > BigInt(v.total.amountMicros)) fail2(p, "reserve exceeds total");
|
|
398
398
|
});
|
|
399
|
-
var
|
|
399
|
+
var allocationPolicyFields = {
|
|
400
400
|
schemaVersion: literal2(1),
|
|
401
401
|
sourceRef: nullable2(resource),
|
|
402
402
|
decisionKind: literal2("observational_allocation"),
|
|
@@ -413,7 +413,10 @@ var matureOptimizationPolicy = object2({
|
|
|
413
413
|
uncertaintyMethod: literal2("observational_cpql_missing_outcome_bound_v1"),
|
|
414
414
|
attributionModel: choice2("first_party_source", "first_touch", "last_touch", "provider_reported", RESONANCE_ATTRIBUTION_MODEL),
|
|
415
415
|
requiredChecks: list2(choice2("tracking", "dedupe", "qualification", "uncertainty", "assignment", "power"), 6, 1)
|
|
416
|
-
}
|
|
416
|
+
};
|
|
417
|
+
var matureOptimizationPolicy = object2(allocationPolicyFields);
|
|
418
|
+
var reportedPolicyFields = { ...allocationPolicyFields, algorithm: literal2("reported_cpql_conserved_transfer_v1"), costBasis: literal2("provider_reported_snapshot_v1"), costRevisionRisk: literal2("accepted_provisional") };
|
|
419
|
+
var reportedOptimizationPolicy = object2({ ...reportedPolicyFields, readClockKind: literal2("sql_before_provider_read_lower_bound_v1") });
|
|
417
420
|
function uniqueList(item, max, min = 0) {
|
|
418
421
|
const base = list2(item, max, min);
|
|
419
422
|
return field2({ ...base.schema, uniqueItems: true }, (v, p) => {
|
|
@@ -448,10 +451,10 @@ var finiteMetaCandidatePolicy = object2({
|
|
|
448
451
|
stopRules: uniqueList(finiteStopRule, 8, 8),
|
|
449
452
|
expiresAt: instant
|
|
450
453
|
});
|
|
451
|
-
var optimizationPolicy = union2(matureOptimizationPolicy, finiteMetaCandidatePolicy);
|
|
454
|
+
var optimizationPolicy = union2(matureOptimizationPolicy, finiteMetaCandidatePolicy, reportedOptimizationPolicy);
|
|
452
455
|
function parseResonanceOptimizationPolicy(v) {
|
|
453
456
|
const r = optimizationPolicy.read(v, "optimizationPolicy");
|
|
454
|
-
if (r.algorithm
|
|
457
|
+
if (r.algorithm !== "finite_meta_candidates_v1") {
|
|
455
458
|
unique(r.requiredChecks, "optimizationPolicy.requiredChecks");
|
|
456
459
|
return r;
|
|
457
460
|
}
|
|
@@ -473,7 +476,39 @@ var search = object2({ ...channelBase, localCampaignKey: text2(80), kind: litera
|
|
|
473
476
|
var metaAgeConstraint = union2(refine2(object2({ mode: literal2("bounded"), min: integer2(1, 120), max: integer2(1, 120) }), (v, p) => {
|
|
474
477
|
if (v.min > v.max) fail2(p, "minimum age exceeds maximum");
|
|
475
478
|
}), object2({ mode: literal2("omitted") }), object2({ mode: literal2("provider_managed") }));
|
|
476
|
-
var
|
|
479
|
+
var propertyKey = object2({ key: text2(40, /^[a-z0-9]+(?:-[a-z0-9]+)*$/), label: text2(80) });
|
|
480
|
+
var meta = object2({
|
|
481
|
+
...channelBase,
|
|
482
|
+
localCampaignKey: text2(80),
|
|
483
|
+
kind: literal2("meta_retargeting"),
|
|
484
|
+
provider: literal2("meta_ads"),
|
|
485
|
+
accountBindingId: uuid,
|
|
486
|
+
capabilityRevision: revision,
|
|
487
|
+
allocation: money,
|
|
488
|
+
budgetMode: choice2("lifetime", "daily"),
|
|
489
|
+
audienceRuleRefs: list2(audience, 50, 1),
|
|
490
|
+
objective: choice2("OUTCOME_LEADS", "OUTCOME_SALES", "OUTCOME_TRAFFIC"),
|
|
491
|
+
pageRef: object2({ connectionId: uuid, externalId: text2(160), revision }),
|
|
492
|
+
instagramRef: nullable2(object2({ connectionId: uuid, externalId: text2(160), revision })),
|
|
493
|
+
datasetRef: object2({ id: text2(160), revision }),
|
|
494
|
+
conversionGoalRef: resource,
|
|
495
|
+
optimization: choice2("landing_page_views", "lead", "purchase"),
|
|
496
|
+
billing: literal2("impressions"),
|
|
497
|
+
bid: union2(object2({ strategy: literal2("lowest_cost") }), object2({ strategy: literal2("cost_cap"), cap: money })),
|
|
498
|
+
localAdSetKey: text2(80),
|
|
499
|
+
localAdKey: text2(80),
|
|
500
|
+
budgetOwner: choice2("campaign", "adset"),
|
|
501
|
+
specialCategories: list2(choice2("housing", "employment", "financial_products_services"), 3),
|
|
502
|
+
countryCodes: list2(text2(2, /^[A-Z]{2}$/), 30, 1),
|
|
503
|
+
placement: literal2("automatic"),
|
|
504
|
+
ageConstraint: optional2(metaAgeConstraint),
|
|
505
|
+
// 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.
|
|
506
|
+
channelGroup: optional2(propertyKey),
|
|
507
|
+
property: optional2(propertyKey),
|
|
508
|
+
tier: optional2(object2({ label: text2(40) })),
|
|
509
|
+
primaryText: optional2(text2(2200)),
|
|
510
|
+
convertersAcknowledged: optional2(literal2(true))
|
|
511
|
+
});
|
|
477
512
|
var owned = object2({ ...channelBase, kind: choice2("funnel", "broadcast", "outreach"), resourceRef: resource });
|
|
478
513
|
var channel = union2(search, meta, owned);
|
|
479
514
|
var definitionFields = { schemaVersion: literal2(1), projectId: uuid, name: text2(160), slug: refine2(text2(80), (v, p) => {
|
|
@@ -519,6 +554,9 @@ function checkDefinition(v) {
|
|
|
519
554
|
if ("bidding" in c && "target" in c.bidding && c.bidding.target.currency !== v.budget.total.currency) fail2("campaign.channels.bidding", "currency mismatch");
|
|
520
555
|
if ("allocation" in c && c.allocation.currency !== v.budget.total.currency) fail2("campaign.channels.allocation", "currency mismatch");
|
|
521
556
|
}
|
|
557
|
+
checkChannelGroups(v.channels);
|
|
558
|
+
checkGroupedAllocations(v);
|
|
559
|
+
for (const c of v.channels) if (c.kind === "meta_retargeting") checkMetaAudienceBands(c, "campaign.channels.audienceRuleRefs");
|
|
522
560
|
const policy = v.optimization.policy;
|
|
523
561
|
if (policy.algorithm === "finite_meta_candidates_v1") {
|
|
524
562
|
const guard = policy.measurementGuard, goal = v.objective;
|
|
@@ -575,14 +613,37 @@ var websiteVisitFeed = object2({ profile: literal2(RESONANCE_WEBSITE_VISIT_PROFI
|
|
|
575
613
|
matchingProfileRef
|
|
576
614
|
}), 100, 1) });
|
|
577
615
|
var RESONANCE_WEBSITE_VISIT_FEED_JSON_SCHEMA = websiteVisitFeed.schema;
|
|
578
|
-
var
|
|
579
|
-
|
|
616
|
+
var providerReportingChannelIds = refine2(uniqueList(uuid, 100, 1), (ids, p) => unique(ids.map((id) => id.toLowerCase()), p));
|
|
617
|
+
var providerReportingSelection = object2({ agentContactId: uuid, channelIds: providerReportingChannelIds });
|
|
618
|
+
var providerReportingGrant = refine2(object2({ purpose: literal2("provider_reporting_refresh"), orgId: uuid, projectId: uuid, agentContactId: uuid, principalContactId: uuid, channelIds: providerReportingChannelIds }), (v, p) => {
|
|
619
|
+
if (v.agentContactId.toLowerCase() === v.principalContactId.toLowerCase()) fail2(p + ".principalContactId", "agent and human principal must remain distinct");
|
|
620
|
+
});
|
|
621
|
+
var parseResonanceProviderReportingSelection = (v) => providerReportingSelection.read(v, "providerReportingSelection");
|
|
622
|
+
var parseResonanceProviderReportingGrant = (v) => providerReportingGrant.read(v, "providerReportingGrant");
|
|
623
|
+
var RESONANCE_PROVIDER_REPORTING_SELECTION_JSON_SCHEMA = providerReportingSelection.schema;
|
|
624
|
+
var RESONANCE_PROVIDER_REPORTING_GRANT_JSON_SCHEMA = providerReportingGrant.schema;
|
|
625
|
+
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) });
|
|
626
|
+
function parseResonanceMandateScope(v, preparedPlan) {
|
|
580
627
|
const r = mandateScope.read(v, "mandateScope");
|
|
581
628
|
scoped(r, r.projectId, r.sites, "mandateScope");
|
|
582
629
|
if (r.websiteVisitFeed) {
|
|
583
630
|
unique(r.websiteVisitFeed.channels.map((c) => c.channelId), "mandateScope.websiteVisitFeed.channels");
|
|
584
631
|
for (const c of r.websiteVisitFeed.channels) unique(c.resourceRuleRefs.map((rule) => rule.id), "mandateScope.websiteVisitFeed.resourceRuleRefs");
|
|
585
632
|
}
|
|
633
|
+
if (r.providerReporting) {
|
|
634
|
+
const grant = r.providerReporting, p = "mandateScope.providerReporting";
|
|
635
|
+
if (grant.projectId !== r.projectId) fail2(p + ".projectId", "must match the original mandate project");
|
|
636
|
+
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");
|
|
637
|
+
if (preparedPlan !== void 0) {
|
|
638
|
+
const plan = parseResonancePreparedPlan(preparedPlan);
|
|
639
|
+
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");
|
|
640
|
+
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");
|
|
641
|
+
for (const id of grant.channelIds) {
|
|
642
|
+
const channel2 = plan.definition.channels.find((c) => c.id === id);
|
|
643
|
+
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");
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
}
|
|
586
647
|
return r;
|
|
587
648
|
}
|
|
588
649
|
var websiteVisitTimes = object2({ occurredAt: instant, receivedAt: instant });
|
|
@@ -857,12 +918,13 @@ function parseResonanceCampaignView(v) {
|
|
|
857
918
|
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) => {
|
|
858
919
|
if (v === "0") fail2(p, "zero denominator");
|
|
859
920
|
}) }));
|
|
860
|
-
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) })) };
|
|
921
|
+
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) })) };
|
|
861
922
|
var metric = union2(object2({ ...metricBase, state: literal2("observed"), value: metricValue }), object2({ ...metricBase, state: choice2("unknown", "insufficient", "delayed", "unavailable"), value: literal2(null), reasonCode: text2(80) }));
|
|
862
923
|
function parseResonanceMetricObservation(v) {
|
|
863
924
|
const r = metric.read(v, "metric");
|
|
864
925
|
if (["accepted_goals", "qualified_goals", "revenue", "conversion_rate"].includes(r.name) && r.goalRevision === null) fail2("metric.goalRevision", "goal measurement requires explicit revision");
|
|
865
926
|
if (Date.parse(r.windowEnd) <= Date.parse(r.windowStart)) fail2("metric.window", "invalid window");
|
|
927
|
+
if (r.name === "reach" !== (r.countingUnit === "provider_unique_reach")) fail2("metric.countingUnit", "reach, and only reach, counts unique provider reach");
|
|
866
928
|
if (r.state === "observed") {
|
|
867
929
|
const expected = r.name === "spend" || r.name === "revenue" ? "money" : r.name === "conversion_rate" ? "ratio" : "count";
|
|
868
930
|
if (r.value.kind !== expected) fail2("metric.value", "metric unit mismatch");
|
|
@@ -990,15 +1052,18 @@ var allocationHorizon = union2(
|
|
|
990
1052
|
);
|
|
991
1053
|
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) });
|
|
992
1054
|
function cpqlMissingOutcomeBound(input) {
|
|
1055
|
+
return conditionalCpqlOutcomeBound(input, input.verifiedSpend);
|
|
1056
|
+
}
|
|
1057
|
+
function conditionalCpqlOutcomeBound(input, spend) {
|
|
993
1058
|
const n = BigInt(decimal.read(input.eligibleContacts, "bound.eligibleContacts"));
|
|
994
1059
|
const c = BigInt(decimal.read(input.fullyResolvedContacts, "bound.fullyResolvedContacts"));
|
|
995
1060
|
const k = BigInt(decimal.read(input.qualifiedContacts, "bound.qualifiedContacts"));
|
|
996
1061
|
if (c > n || k > c) fail2("bound", "inconsistent unique-contact source universe");
|
|
997
|
-
if (n === 0n || k === 0n || parseMoney(
|
|
1062
|
+
if (n === 0n || k === 0n || parseMoney(spend).amountMicros === "0") return null;
|
|
998
1063
|
const u = n - c, denominator = 2n * k + u;
|
|
999
1064
|
return Number((10000n * u + denominator - 1n) / denominator);
|
|
1000
1065
|
}
|
|
1001
|
-
var
|
|
1066
|
+
var allocationEvidenceFields = {
|
|
1002
1067
|
id: uuid,
|
|
1003
1068
|
revision,
|
|
1004
1069
|
evidenceDigest: digest,
|
|
@@ -1019,13 +1084,42 @@ var matureOptimizationEvidence = object2({
|
|
|
1019
1084
|
trackingState: choice2("healthy", "blocked", "unknown"),
|
|
1020
1085
|
coverageBasisPoints: nullable2(integer2(0, 1e4)),
|
|
1021
1086
|
assignmentCheck: choice2("pass", "failed", "unknown", "not_applicable"),
|
|
1022
|
-
powerCheck: choice2("pass", "failed", "unknown", "not_applicable")
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1087
|
+
powerCheck: choice2("pass", "failed", "unknown", "not_applicable")
|
|
1088
|
+
};
|
|
1089
|
+
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) => {
|
|
1090
|
+
if (![0, 2, 3, 6].includes(v)) fail2(p, "unsupported provider exponent");
|
|
1091
|
+
}), providerMaxUnits: decimal };
|
|
1092
|
+
var { uncertaintySource: _legacyUncertaintyField, ...reportedChannelFields } = allocationChannelFields;
|
|
1093
|
+
var matureOptimizationEvidence = object2({ ...allocationEvidenceFields, resolvedPolicy: matureOptimizationPolicy, channels: list2(object2({ ...allocationChannelFields, uncertaintySource: nullable2(uncertaintySource) }), 100, 1) });
|
|
1094
|
+
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) };
|
|
1095
|
+
var reportedOutcomeSource = object2({ method: literal2(RESONANCE_CPQL_UNCERTAINTY_METHOD), eligibleContacts: decimal, fullyResolvedContacts: decimal, qualifiedContacts: decimal, sourceRevision: revision, qualificationRuleRef: resource, universeComplete: literal2(true) });
|
|
1096
|
+
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) => {
|
|
1097
|
+
const match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,6}))?(?:Z|\+00:00)$/.exec(v);
|
|
1098
|
+
const projected = match[1] + "." + (match[2] ?? "").padEnd(3, "0").slice(0, 3) + "Z";
|
|
1099
|
+
if (!Number.isFinite(Date.parse(projected)) || new Date(projected).toISOString() !== projected) fail2(p, "invalid native SQL UTC instant");
|
|
1026
1100
|
});
|
|
1101
|
+
var providerReadClock = object2({ kind: literal2("sql_before_provider_read_lower_bound_v1"), notBeforeAt: nativeSqlReadInstant });
|
|
1102
|
+
var channelReportedCost = object2({ ...reportedCostFields, readClock: providerReadClock });
|
|
1103
|
+
var reportedOptimizationEvidence = object2({
|
|
1104
|
+
...allocationEvidenceFields,
|
|
1105
|
+
evidenceKind: literal2("reported_cpql_sql_clock_v1"),
|
|
1106
|
+
resolvedPolicy: reportedOptimizationPolicy,
|
|
1107
|
+
channels: list2(object2({ ...reportedChannelFields, channelReportedCost, outcomeSource: reportedOutcomeSource }), 100, 1)
|
|
1108
|
+
});
|
|
1109
|
+
function reportedCpqlMissingOutcomeBound(input) {
|
|
1110
|
+
return conditionalCpqlOutcomeBound(input, input.reportedSpend);
|
|
1111
|
+
}
|
|
1027
1112
|
function parseMatureOptimizationEvidence(v) {
|
|
1028
1113
|
const r = matureOptimizationEvidence.read(v, "optimizationEvidence");
|
|
1114
|
+
for (const c of r.channels) {
|
|
1115
|
+
if (c.uncertaintySource === null) {
|
|
1116
|
+
if (c.uncertaintyBasisPoints !== null) fail2("optimizationEvidence.channels.uncertainty", "no bound without source witness");
|
|
1117
|
+
} else if (c.uncertaintySource.verifiedSpend.currency !== c.currentAllocation.currency || c.uncertaintyBasisPoints !== cpqlMissingOutcomeBound(c.uncertaintySource)) fail2("optimizationEvidence.channels.uncertainty", "source bound mismatch");
|
|
1118
|
+
}
|
|
1119
|
+
checkAllocationEvidence(r);
|
|
1120
|
+
return r;
|
|
1121
|
+
}
|
|
1122
|
+
function checkAllocationEvidence(r) {
|
|
1029
1123
|
if (r.objective.measurementRevision !== r.goalRevision) fail2("optimizationEvidence.goalRevision", "goal snapshot mismatch");
|
|
1030
1124
|
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");
|
|
1031
1125
|
const sites = r.channels.map((c) => c.site);
|
|
@@ -1033,9 +1127,6 @@ function parseMatureOptimizationEvidence(v) {
|
|
|
1033
1127
|
unique(r.channels.map((c) => c.channelId), "optimizationEvidence.channels");
|
|
1034
1128
|
const currency2 = r.channels[0].currentAllocation.currency;
|
|
1035
1129
|
for (const c of r.channels) {
|
|
1036
|
-
if (c.uncertaintySource === null) {
|
|
1037
|
-
if (c.uncertaintyBasisPoints !== null) fail2("optimizationEvidence.channels.uncertainty", "no bound without source witness");
|
|
1038
|
-
} else if (c.uncertaintySource.verifiedSpend.currency !== c.currentAllocation.currency || c.uncertaintyBasisPoints !== cpqlMissingOutcomeBound(c.uncertaintySource)) fail2("optimizationEvidence.channels.uncertainty", "source bound mismatch");
|
|
1039
1130
|
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");
|
|
1040
1131
|
if (c.coveredNumerator === null || c.eligibleDenominator === null || c.eligibleDenominator === "0") {
|
|
1041
1132
|
if (c.coverageBasisPoints !== null) fail2("optimizationEvidence.channels.coverage", "unknown denominator means unknown coverage");
|
|
@@ -1052,8 +1143,50 @@ function parseMatureOptimizationEvidence(v) {
|
|
|
1052
1143
|
if (observation.campaignId !== r.campaignId || observation.site !== c.site) fail2("optimizationEvidence.channels.observations", "scope mismatch");
|
|
1053
1144
|
}
|
|
1054
1145
|
}
|
|
1146
|
+
}
|
|
1147
|
+
function parseReportedOptimizationEvidence(v) {
|
|
1148
|
+
const r = reportedOptimizationEvidence.read(v, "optimizationEvidence");
|
|
1149
|
+
checkReportedAllocationEvidence(r);
|
|
1055
1150
|
return r;
|
|
1056
1151
|
}
|
|
1152
|
+
function checkReportedAllocationEvidence(r) {
|
|
1153
|
+
const p = "optimizationEvidence";
|
|
1154
|
+
parseResonanceOptimizationPolicy(r.resolvedPolicy);
|
|
1155
|
+
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");
|
|
1156
|
+
if (r.dataThrough !== null) fail2(p + ".dataThrough", "query coverage cannot become mature provider dataThrough");
|
|
1157
|
+
unique(r.channels.map((c) => c.channelReportedCost.observationId), p + ".channels.channelReportedCost.observationId");
|
|
1158
|
+
const observedAt = Date.parse(r.observedAt), windowStart = Date.parse(r.windowStart), windowEnd = Date.parse(r.windowEnd);
|
|
1159
|
+
if (windowEnd <= windowStart || windowEnd > observedAt) fail2(p + ".window", "requires a completed observed interval");
|
|
1160
|
+
let commonZone;
|
|
1161
|
+
for (const c of r.channels) {
|
|
1162
|
+
const cost = c.channelReportedCost, outcome = c.outcomeSource;
|
|
1163
|
+
if (c.dataThrough !== null) fail2(p + ".channels.dataThrough", "query coverage cannot become mature provider dataThrough");
|
|
1164
|
+
if (Date.parse(cost.queriedFrom) !== windowStart || Date.parse(cost.queriedThrough) !== windowEnd) fail2(p + ".channels.channelReportedCost", "requires the exact common query interval");
|
|
1165
|
+
const firstReceived = Date.parse(cost.firstReceivedAt), received = Date.parse(cost.receivedAt), recorded = Date.parse(cost.recordedAt);
|
|
1166
|
+
const anchor = Date.parse(cost.readClock.notBeforeAt);
|
|
1167
|
+
if (received < firstReceived) fail2(p + ".channels.channelReportedCost", "HTTP receipts must retain internal ordering");
|
|
1168
|
+
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");
|
|
1169
|
+
if (cost.reportedSpend.currency !== c.currentAllocation.currency || canonical(outcome.qualificationRuleRef) !== canonical(r.objective.qualificationRuleRef)) fail2(p + ".channels.outcomeSource", "requires original qualification reference and currency");
|
|
1170
|
+
if (c.uncertaintyBasisPoints !== reportedCpqlMissingOutcomeBound({ ...outcome, reportedSpend: cost.reportedSpend })) fail2(p + ".channels.uncertainty", "conditional source bound mismatch");
|
|
1171
|
+
const spends = c.observations.filter((o) => o.name === "spend");
|
|
1172
|
+
if (spends.length !== 1) fail2(p + ".channels.observations", "requires one exact provider spend snapshot, never overlapping sums");
|
|
1173
|
+
const spend = spends[0];
|
|
1174
|
+
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");
|
|
1175
|
+
const outcomes = c.observations.filter((o) => o.name === "qualified_goals");
|
|
1176
|
+
if (outcomes.length !== 1) fail2(p + ".channels.observations", "requires one independent qualified-contact source");
|
|
1177
|
+
const qualified = outcomes[0];
|
|
1178
|
+
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");
|
|
1179
|
+
const formatter = new Intl.DateTimeFormat("en-GB", { timeZone: spend.timeZone, hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" });
|
|
1180
|
+
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");
|
|
1181
|
+
commonZone = spend.timeZone;
|
|
1182
|
+
for (const o of c.observations) {
|
|
1183
|
+
parseResonanceMetricObservation(o);
|
|
1184
|
+
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");
|
|
1185
|
+
if (o.source === "provider" && o.dataThrough !== null) fail2(p + ".channels.observations", "reported provider observation remains nonfinal");
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
checkAllocationEvidence(r);
|
|
1189
|
+
}
|
|
1057
1190
|
var optimizationEvidenceRefFields = { id: uuid, revision, evidenceDigest: digest };
|
|
1058
1191
|
var optimizationEvidenceRef = object2(optimizationEvidenceRefFields);
|
|
1059
1192
|
var finiteOwnMeasurement = union2(
|
|
@@ -1106,11 +1239,12 @@ var finiteOptimizationEvidence = object2({
|
|
|
1106
1239
|
inventoryState: choice2("complete", "incomplete", "unknown"),
|
|
1107
1240
|
candidates: list2(finiteCandidateObservation, 100, 1)
|
|
1108
1241
|
});
|
|
1109
|
-
var optimizationEvidence = union2(matureOptimizationEvidence, finiteOptimizationEvidence);
|
|
1242
|
+
var optimizationEvidence = union2(matureOptimizationEvidence, finiteOptimizationEvidence, reportedOptimizationEvidence);
|
|
1110
1243
|
function parseResonanceOptimizationEvidence(v, preparedPlan) {
|
|
1111
1244
|
const r = optimizationEvidence.read(v, "optimizationEvidence");
|
|
1112
1245
|
if (preparedPlan !== void 0) checkOptimizationEvidencePlan(r, parseResonancePreparedPlan(preparedPlan));
|
|
1113
1246
|
if (!("evidenceKind" in r)) return parseMatureOptimizationEvidence(r);
|
|
1247
|
+
if (r.evidenceKind === "reported_cpql_sql_clock_v1") return parseReportedOptimizationEvidence(r);
|
|
1114
1248
|
const p = "optimizationEvidence", policy = parseResonanceOptimizationPolicy(r.resolvedPolicy);
|
|
1115
1249
|
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");
|
|
1116
1250
|
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");
|
|
@@ -1131,8 +1265,8 @@ function parseResonanceOptimizationEvidence(v, preparedPlan) {
|
|
|
1131
1265
|
parseResonanceMetricObservation(o);
|
|
1132
1266
|
if (o.projectId !== r.projectId || o.campaignId !== r.campaignId || o.site !== c.site) fail2(p + ".candidates.ownMeasurement", "foreign candidate measurement scope");
|
|
1133
1267
|
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");
|
|
1134
|
-
const aggregate = o.source === "provider" &&
|
|
1135
|
-
if (aggregate ? o.countingUnit !==
|
|
1268
|
+
const aggregate = o.source === "provider" && RESONANCE_PROVIDER_METRIC_NAMES.includes(o.name);
|
|
1269
|
+
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");
|
|
1136
1270
|
}
|
|
1137
1271
|
}
|
|
1138
1272
|
return r;
|
|
@@ -1141,6 +1275,15 @@ function checkOptimizationEvidencePlan(e, plan) {
|
|
|
1141
1275
|
const p = "optimizationEvidence";
|
|
1142
1276
|
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");
|
|
1143
1277
|
if (!("evidenceKind" in e)) return;
|
|
1278
|
+
if (e.evidenceKind === "reported_cpql_sql_clock_v1") {
|
|
1279
|
+
const cohort = plan.resolvedQualificationRule?.cohort;
|
|
1280
|
+
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");
|
|
1281
|
+
for (const c of e.channels) {
|
|
1282
|
+
const original = plan.definition.channels.find((x) => x.id === c.channelId), account = plan.accounts.find((x) => x.id === c.accountBindingId);
|
|
1283
|
+
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");
|
|
1284
|
+
}
|
|
1285
|
+
return;
|
|
1286
|
+
}
|
|
1144
1287
|
for (const observed of e.candidates) {
|
|
1145
1288
|
const original = plan.definition.channels.find((c) => c.id === observed.channelId), preview2 = plan.channelPreviews.find((c) => c.channelId === observed.channelId);
|
|
1146
1289
|
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");
|
|
@@ -1220,11 +1363,18 @@ function checkOptimizationDecisionEvidence(d, e) {
|
|
|
1220
1363
|
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");
|
|
1221
1364
|
if (Date.parse(d.createdAt) < Date.parse(e.observedAt)) fail2(p + ".createdAt", "precedes actual evidence");
|
|
1222
1365
|
if (d.decisionKind !== "preapproved_candidate_operation") {
|
|
1223
|
-
if ("evidenceKind" in e) fail2(p + ".decisionKind", "mature decisions cannot borrow finite lifecycle evidence");
|
|
1366
|
+
if ("evidenceKind" in e && e.evidenceKind !== "reported_cpql_sql_clock_v1") fail2(p + ".decisionKind", "mature decisions cannot borrow finite lifecycle evidence");
|
|
1367
|
+
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");
|
|
1368
|
+
if ("evidenceKind" in e && e.evidenceKind === "reported_cpql_sql_clock_v1") {
|
|
1369
|
+
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;
|
|
1370
|
+
if (Date.parse(d.createdAt) > deadline || Date.parse(d.expiresAt) > deadline) fail2(p + ".expiresAt", "outside original HTTP/database evidence freshness");
|
|
1371
|
+
const refs = e.channels.flatMap((c) => [c.channelReportedCost.observationId, c.outcomeSource.sourceRevision]);
|
|
1372
|
+
if (refs.some((ref) => !d.sourceRefs.includes(ref))) fail2(p + ".sourceRefs", "requires immutable reported-cost and independent outcome sources");
|
|
1373
|
+
}
|
|
1224
1374
|
if (d.algorithmRevision === "finite_meta_candidates_v1") fail2(p + ".algorithmRevision", "mature decisions cannot use the finite algorithm");
|
|
1225
1375
|
return;
|
|
1226
1376
|
}
|
|
1227
|
-
if (!("evidenceKind" in e)) fail2(p + ".decisionKind", "finite actions require finite lifecycle evidence");
|
|
1377
|
+
if (!("evidenceKind" in e) || e.evidenceKind !== "finite_candidate_lifecycle_v1") fail2(p + ".decisionKind", "finite actions require finite lifecycle evidence");
|
|
1228
1378
|
const finite = e, policy = finite.resolvedPolicy;
|
|
1229
1379
|
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");
|
|
1230
1380
|
for (const a of d.candidateActions) {
|
|
@@ -1256,9 +1406,11 @@ function checkOptimizationDecisionEvidence(d, e) {
|
|
|
1256
1406
|
}
|
|
1257
1407
|
var RESONANCE_OPTIMIZATION_EVIDENCE_JSON_SCHEMA = optimizationEvidence.schema;
|
|
1258
1408
|
var RESONANCE_OPTIMIZATION_DECISION_JSON_SCHEMA = optimizationDecision.schema;
|
|
1409
|
+
var metaBrowserWitness = object2({ controlsRevision: text2(60, /^[A-Z][A-Z0-9_]*$/), policyRevision: revision, witnessId: uuid, assertedAt: instant });
|
|
1259
1410
|
var publicDestination = union2(
|
|
1260
1411
|
object2({ provider: literal2("google_ads"), id: uuid, tagId: text2(40, /^AW-[0-9]+$/) }),
|
|
1261
|
-
|
|
1412
|
+
// browserWitness and tagManagerAttested are optional so configurations from before the Meta loader keep parsing; absent means no Meta browser loading.
|
|
1413
|
+
object2({ provider: literal2("meta_ads"), id: uuid, pixelId: text2(40, /^[0-9]+$/), browserWitness: optional2(metaBrowserWitness), tagManagerAttested: optional2(bool) })
|
|
1262
1414
|
);
|
|
1263
1415
|
var interestResource = object2({ ...scope, type: choice2("page", "article", "product", "listing"), id: text2(160, /^[a-zA-Z0-9._:-]+$/), revision });
|
|
1264
1416
|
var measurementConfig = object2({
|
|
@@ -1270,7 +1422,8 @@ var measurementConfig = object2({
|
|
|
1270
1422
|
enabled: bool,
|
|
1271
1423
|
consentPolicy: object2({ mode: literal2("basic"), requiredPurposes: list2(purpose, 4, 1) }),
|
|
1272
1424
|
destinations: list2(publicDestination, 10),
|
|
1273
|
-
|
|
1425
|
+
// metaEligible is set by a person with owner or admin standing; absent means false. The browser never decides it.
|
|
1426
|
+
resourceRules: list2(object2({ id: uuid, revision, site, resource: interestResource, path, interestKey: text2(100, /^[a-zA-Z0-9._:-]+$/), metaEligible: optional2(bool) }), 500)
|
|
1274
1427
|
});
|
|
1275
1428
|
function parseResonanceMeasurementConfig(v) {
|
|
1276
1429
|
const r = measurementConfig.read(v, "measurementConfig");
|
|
@@ -1382,11 +1535,12 @@ var audienceDraft = object2({
|
|
|
1382
1535
|
schemaVersion: literal2(1),
|
|
1383
1536
|
expectedRevision: optional2(integer2(1)),
|
|
1384
1537
|
idempotencyKey: operationKey,
|
|
1385
|
-
definition: object2({ name: text2(160), site, accountBindingId: uuid, resourceRuleId: uuid, excludedResourceRuleIds: list2(uuid, 50), retentionDays: integer2(1, 540), policyRevision: revision, currentConsentPolicyRevision: revision })
|
|
1538
|
+
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 })
|
|
1386
1539
|
});
|
|
1387
1540
|
function parseResonanceAudienceDraftSaveCommand(v) {
|
|
1388
1541
|
const r = audienceDraft.read(v, "audienceDraftSave");
|
|
1389
1542
|
unique(r.definition.excludedResourceRuleIds, "audienceDraftSave.definition.excludedResourceRuleIds");
|
|
1543
|
+
if (r.definition.minDaysSinceVisit !== void 0 && r.definition.minDaysSinceVisit >= r.definition.retentionDays) fail2("audienceDraftSave.definition.minDaysSinceVisit", "must be shorter than the retention window");
|
|
1390
1544
|
return r;
|
|
1391
1545
|
}
|
|
1392
1546
|
var RESONANCE_AUDIENCE_DRAFT_SAVE_COMMAND_JSON_SCHEMA = audienceDraft.schema;
|
|
@@ -1555,6 +1709,7 @@ function checkMetaMaterial(v, p) {
|
|
|
1555
1709
|
unique(v.audiences.map((a) => a.audienceRuleRef.id), p + ".audiences");
|
|
1556
1710
|
unique(v.channel.audienceRuleRefs.map((a) => a.id), p + ".channel.audienceRuleRefs");
|
|
1557
1711
|
if (v.audiences.length !== v.channel.audienceRuleRefs.length) fail2(p + ".audiences", "must cover exactly the original logical audiences");
|
|
1712
|
+
checkMetaAudienceBands(v.channel, p + ".channel.audienceRuleRefs");
|
|
1558
1713
|
for (const a of v.audiences) {
|
|
1559
1714
|
if (!v.channel.audienceRuleRefs.some((ref) => canonical(ref) === canonical(a.audienceRuleRef))) fail2(p + ".audiences", "original logical audience version mismatch");
|
|
1560
1715
|
unique(a.excludedResourceRuleRefs.map((ref) => ref.id), p + ".audiences.excludedResourceRuleRefs");
|
|
@@ -1616,7 +1771,7 @@ var feedSelection = refine2(object2({ channels: list2(object2({ channelId: uuid,
|
|
|
1616
1771
|
unique(v.channels.map((c) => c.channelId), p + ".channels");
|
|
1617
1772
|
for (const c of v.channels) unique(c.resourceRuleRefs.map((ref) => ref.id), p + ".resourceRuleRefs");
|
|
1618
1773
|
});
|
|
1619
|
-
var mandateDraftRequest = object2({ expectedRevision: integer2(1), allowedOperations: mandateAllowedOperations, expiresAt: instant, websiteVisitFeedSelection: optional2(feedSelection) });
|
|
1774
|
+
var mandateDraftRequest = object2({ expectedRevision: integer2(1), allowedOperations: mandateAllowedOperations, expiresAt: instant, websiteVisitFeedSelection: optional2(feedSelection), providerReporting: optional2(providerReportingSelection) });
|
|
1620
1775
|
var parseResonanceMandateDraftRequest = (v) => mandateDraftRequest.read(v, "mandateDraftRequest");
|
|
1621
1776
|
var RESONANCE_MANDATE_DRAFT_REQUEST_JSON_SCHEMA = mandateDraftRequest.schema;
|
|
1622
1777
|
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) }) });
|
|
@@ -1648,8 +1803,290 @@ function parseResonanceWebsiteVisitFeedReview(v, context) {
|
|
|
1648
1803
|
return r;
|
|
1649
1804
|
}
|
|
1650
1805
|
var RESONANCE_WEBSITE_VISIT_FEED_REVIEW_JSON_SCHEMA = feedReview.schema;
|
|
1806
|
+
var observationIdentity = { observationId: uuid, channelId: uuid, versionId: uuid, accountBindingId: uuid };
|
|
1807
|
+
var publicObservationMetric = union2(
|
|
1808
|
+
object2({ ...metricBase, ...observationIdentity, source: choice2("provider", "first_party"), state: literal2("observed"), value: metricValue }),
|
|
1809
|
+
object2({ ...metricBase, ...observationIdentity, source: choice2("provider", "first_party"), state: choice2("unknown", "insufficient", "delayed", "unavailable"), value: literal2(null), reasonCode: text2(80) })
|
|
1810
|
+
);
|
|
1811
|
+
function parseResonancePublicObservationMetric(v) {
|
|
1812
|
+
const r = publicObservationMetric.read(v, "observationItem");
|
|
1813
|
+
const { observationId: _observation, channelId: _channel, versionId: _version, accountBindingId: _account, ...body } = r;
|
|
1814
|
+
parseResonanceMetricObservation(body);
|
|
1815
|
+
return r;
|
|
1816
|
+
}
|
|
1817
|
+
var observationDenominators = object2({ eligibleContacts: nullable2(decimal), fullyResolvedContacts: nullable2(decimal), qualifiedContacts: nullable2(decimal) });
|
|
1818
|
+
var observationSupportFields = { ...observationIdentity, currency, fetchedAt: instant, dataThrough: nullable2(instant), coverage: choice2("unknown", "partial", "complete"), reasonCode: nullable2(text2(80)), denominators: observationDenominators };
|
|
1819
|
+
var firstPartyObservationSupport = object2({ ...observationSupportFields, source: literal2("first_party") });
|
|
1820
|
+
var providerObservationSupport = object2({
|
|
1821
|
+
...observationSupportFields,
|
|
1822
|
+
source: literal2("provider"),
|
|
1823
|
+
firstReceivedAt: nullable2(instant),
|
|
1824
|
+
receivedAt: nullable2(instant),
|
|
1825
|
+
recordedAt: nullable2(instant),
|
|
1826
|
+
readClock: nullable2(providerReadClock),
|
|
1827
|
+
providerFinality: literal2("unknown"),
|
|
1828
|
+
correctionsPossible: literal2(true),
|
|
1829
|
+
coverageBasis: choice2("closed_query_snapshot", "not_established")
|
|
1830
|
+
});
|
|
1831
|
+
var observationSupport = union2(firstPartyObservationSupport, providerObservationSupport);
|
|
1832
|
+
function parseResonanceObservationSupport(v) {
|
|
1833
|
+
const r = observationSupport.read(v, "observationSupport"), p = "observationSupport", d = r.denominators;
|
|
1834
|
+
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");
|
|
1835
|
+
if (r.source === "provider") {
|
|
1836
|
+
if (Object.values(d).some((v2) => v2 !== null)) fail2(p + ".denominators", "provider reporting cannot supply qualified-contact denominators");
|
|
1837
|
+
if (r.firstReceivedAt !== null && (r.receivedAt === null || Date.parse(r.firstReceivedAt) > Date.parse(r.receivedAt))) fail2(p + ".firstReceivedAt", "preserve actual internal HTTP receipt order");
|
|
1838
|
+
if (r.recordedAt !== null && Date.parse(r.recordedAt) !== Date.parse(r.fetchedAt)) fail2(p + ".recordedAt", "must retain the native immutable SQL write time");
|
|
1839
|
+
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");
|
|
1840
|
+
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");
|
|
1841
|
+
}
|
|
1842
|
+
return r;
|
|
1843
|
+
}
|
|
1844
|
+
var observationsPage = object2({ items: list2(publicObservationMetric, 500), nextCursor: nullable2(uuid), observedAt: instant, support: list2(observationSupport, 500) });
|
|
1845
|
+
function parseResonanceObservationsPage(v) {
|
|
1846
|
+
const r = observationsPage.read(v, "observationsPage"), p = "observationsPage";
|
|
1847
|
+
if (r.items.length !== r.support.length) fail2(p + ".support", "requires one support entry for each metric item");
|
|
1848
|
+
const pairs = /* @__PURE__ */ new Set(), rows = /* @__PURE__ */ new Map(), observedAt = Date.parse(r.observedAt);
|
|
1849
|
+
let previous;
|
|
1850
|
+
const first = r.items[0];
|
|
1851
|
+
for (let i = 0; i < r.items.length; i++) {
|
|
1852
|
+
const item = parseResonancePublicObservationMetric(r.items[i]), s = parseResonanceObservationSupport(r.support[i]), rowId = item.observationId.toLowerCase();
|
|
1853
|
+
if (Object.keys(observationIdentity).some((k) => item[k] !== s[k])) fail2(p + ".support", "item/support observation, channel, version and account must align in order");
|
|
1854
|
+
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");
|
|
1855
|
+
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");
|
|
1856
|
+
if (item.state === "observed" && item.value.kind === "money" && item.value.money.currency !== s.currency) fail2(p + ".support.currency", "observed money must retain account currency");
|
|
1857
|
+
if (previous !== void 0 && rowId < previous) fail2(p + ".items", "native-row UUID order cannot be replaced by metric/time sorting");
|
|
1858
|
+
previous = rowId;
|
|
1859
|
+
const key = rowId + ":" + item.name;
|
|
1860
|
+
if (pairs.has(key)) fail2(p + ".items", "duplicate observation/metric pair");
|
|
1861
|
+
pairs.add(key);
|
|
1862
|
+
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) } : {} };
|
|
1863
|
+
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 });
|
|
1864
|
+
if (rows.has(rowId) && rows.get(rowId) !== row) fail2(p + ".support", "one immutable native observation cannot change identity or support across metrics");
|
|
1865
|
+
rows.set(rowId, row);
|
|
1866
|
+
if (s.source === "provider") {
|
|
1867
|
+
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");
|
|
1868
|
+
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");
|
|
1869
|
+
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");
|
|
1870
|
+
} else {
|
|
1871
|
+
const d = s.denominators;
|
|
1872
|
+
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");
|
|
1873
|
+
const coverage = d.eligibleContacts === null || d.eligibleContacts === "0" || d.fullyResolvedContacts === null ? null : Number(BigInt(d.fullyResolvedContacts) * 10000n / BigInt(d.eligibleContacts));
|
|
1874
|
+
if (item.coverageBasisPoints !== coverage) fail2(p + ".support.denominators", "contact resolution coverage must match the independent universe");
|
|
1875
|
+
if (item.state !== "observed" && (s.coverage === "complete" || s.reasonCode !== item.reasonCode)) fail2(p + ".support", "unresolved qualified sources keep incomplete coverage and their native reason");
|
|
1876
|
+
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");
|
|
1877
|
+
}
|
|
1878
|
+
}
|
|
1879
|
+
if (rows.size > 100) fail2(p + ".items", "at most 100 native rows per page");
|
|
1880
|
+
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");
|
|
1881
|
+
return r;
|
|
1882
|
+
}
|
|
1883
|
+
var RESONANCE_PUBLIC_OBSERVATION_METRIC_JSON_SCHEMA = publicObservationMetric.schema;
|
|
1884
|
+
var RESONANCE_OBSERVATION_SUPPORT_JSON_SCHEMA = observationSupport.schema;
|
|
1885
|
+
var RESONANCE_OBSERVATIONS_PAGE_JSON_SCHEMA = observationsPage.schema;
|
|
1886
|
+
var META_WEBSITE_AUDIENCE_MAX_RETENTION_DAYS = 180;
|
|
1887
|
+
var META_AUDIENCE_RULE_LIMIT = 10;
|
|
1888
|
+
var META_SAC_CUSTOM_AUDIENCE_EXCLUSION_VERIFIED = false;
|
|
1889
|
+
var META_CALL_TO_ACTIONS = ["LEARN_MORE", "SIGN_UP", "SHOP_NOW", "APPLY_NOW", "BOOK_TRAVEL", "CONTACT_US", "GET_QUOTE"];
|
|
1890
|
+
var RESONANCE_MAX_CHANNELS_PER_GROUP = 20;
|
|
1891
|
+
var RESONANCE_PROVIDER_METRIC_NAMES = ["spend", "impressions", "clicks", "reach", "results"];
|
|
1892
|
+
var providerCountingUnit = (name) => name === "reach" ? "provider_unique_reach" : "provider_aggregate";
|
|
1893
|
+
var isMetaChannel = (c) => c.kind === "meta_retargeting";
|
|
1894
|
+
var usesPropertyModel = (c) => c.channelGroup !== void 0 || c.audienceRuleRefs.some((ref) => ref.minDaysSinceVisit !== void 0);
|
|
1895
|
+
function checkAudienceBand(ref, provider = "meta_ads", at = "audienceRuleRef") {
|
|
1896
|
+
const min = ref.minDaysSinceVisit;
|
|
1897
|
+
if (min !== void 0 && min >= ref.retentionDays) fail2(at + ".minDaysSinceVisit", "must be shorter than the retention window");
|
|
1898
|
+
if (provider === "google_ads") {
|
|
1899
|
+
if (min !== void 0) fail2(at + ".minDaysSinceVisit", "Google audiences have no recency band");
|
|
1900
|
+
return;
|
|
1901
|
+
}
|
|
1902
|
+
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`);
|
|
1903
|
+
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`);
|
|
1904
|
+
}
|
|
1905
|
+
function checkMetaAudienceBands(channel2, at) {
|
|
1906
|
+
if (!usesPropertyModel(channel2)) return;
|
|
1907
|
+
channel2.audienceRuleRefs.forEach((ref, index) => checkAudienceBand(ref, "meta_ads", `${at}[${index}]`));
|
|
1908
|
+
}
|
|
1909
|
+
var bandsOverlap = (a, b) => (a.minDaysSinceVisit ?? 0) < b.retentionDays && (b.minDaysSinceVisit ?? 0) < a.retentionDays;
|
|
1910
|
+
function checkChannelGroups(channels) {
|
|
1911
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1912
|
+
for (const c of channels) if (isMetaChannel(c) && c.channelGroup) groups.set(c.channelGroup.key, [...groups.get(c.channelGroup.key) ?? [], c]);
|
|
1913
|
+
for (const [key, members] of groups) {
|
|
1914
|
+
const at = `campaign.channelGroup.${key}`;
|
|
1915
|
+
if (members.length > RESONANCE_MAX_CHANNELS_PER_GROUP) fail2(at, `at most ${RESONANCE_MAX_CHANNELS_PER_GROUP} channels per group`);
|
|
1916
|
+
const first = members[0];
|
|
1917
|
+
const shared = (c) => canonical([c.site, c.accountBindingId, c.datasetRef.id, c.pageRef, c.instagramRef, c.specialCategories, c.countryCodes, c.objective, c.optimization]);
|
|
1918
|
+
const identity = /* @__PURE__ */ new Set(), destinationOf = /* @__PURE__ */ new Map(), propertyOfDestination = /* @__PURE__ */ new Map();
|
|
1919
|
+
for (const c of members) {
|
|
1920
|
+
if (shared(c) !== shared(first)) fail2(at, "channels in one group must share site, account, dataset, Page, categories, countries, objective and optimization");
|
|
1921
|
+
if (c.specialCategories.length > 0 && c.ageConstraint?.mode !== "provider_managed") fail2(at + ".ageConstraint", "a special category requires provider-managed age");
|
|
1922
|
+
const pk = (c.property ?? fail2(at + ".property", "a grouped channel names its property")).key, tier = c.tier?.label ?? "", id = `${pk}|${tier}`;
|
|
1923
|
+
if (identity.has(id)) fail2(at + ".property", "two channels share one property and tier");
|
|
1924
|
+
identity.add(id);
|
|
1925
|
+
if (destinationOf.has(pk) && destinationOf.get(pk) !== c.destinationId) fail2(at + ".destinationId", "channels for one property share one destination");
|
|
1926
|
+
destinationOf.set(pk, c.destinationId);
|
|
1927
|
+
const other = propertyOfDestination.get(c.destinationId);
|
|
1928
|
+
if (other !== void 0 && other !== pk) fail2(at + ".destinationId", "channels for different properties have different destinations");
|
|
1929
|
+
propertyOfDestination.set(c.destinationId, pk);
|
|
1930
|
+
}
|
|
1931
|
+
for (let i = 0; i < members.length; i++) for (let j = i + 1; j < members.length; j++) {
|
|
1932
|
+
if (members[i].property?.key !== members[j].property?.key) continue;
|
|
1933
|
+
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");
|
|
1934
|
+
}
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1937
|
+
function checkGroupedAllocations(v) {
|
|
1938
|
+
if (!v.channels.some((c) => isMetaChannel(c) && c.channelGroup)) return;
|
|
1939
|
+
let sum = 0n;
|
|
1940
|
+
for (const c of v.channels) if ("allocation" in c) sum += BigInt(c.allocation.amountMicros);
|
|
1941
|
+
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");
|
|
1942
|
+
}
|
|
1943
|
+
function splitBudget(total, weights, quantumMicros) {
|
|
1944
|
+
const t = parseMoney(total), at = "splitBudget";
|
|
1945
|
+
if (!/^[1-9][0-9]{0,29}$/.test(quantumMicros)) fail2(at + ".quantumMicros", "must be a positive whole number of micros");
|
|
1946
|
+
if (weights.length < 1 || weights.length > 100 || weights.some((w) => !Number.isSafeInteger(w) || w < 1)) fail2(at + ".weights", "one to 100 positive whole weights");
|
|
1947
|
+
const quantum = BigInt(quantumMicros), micros = BigInt(t.amountMicros);
|
|
1948
|
+
if (micros % quantum !== 0n) fail2(at + ".total", "must be a whole number of provider quanta");
|
|
1949
|
+
const units = micros / quantum, sum = weights.reduce((a, w) => a + BigInt(w), 0n);
|
|
1950
|
+
const parts = weights.map((w, index) => ({ index, floor: units * BigInt(w) / sum, rest: units * BigInt(w) % sum }));
|
|
1951
|
+
let left = units - parts.reduce((a, p) => a + p.floor, 0n);
|
|
1952
|
+
const order = [...parts].sort((a, b) => a.rest === b.rest ? a.index - b.index : a.rest > b.rest ? -1 : 1);
|
|
1953
|
+
const extra = /* @__PURE__ */ new Set();
|
|
1954
|
+
for (const p of order) {
|
|
1955
|
+
if (left === 0n) break;
|
|
1956
|
+
extra.add(p.index);
|
|
1957
|
+
left -= 1n;
|
|
1958
|
+
}
|
|
1959
|
+
return parts.map((p) => ({ currency: t.currency, amountMicros: ((p.floor + (extra.has(p.index) ? 1n : 0n)) * quantum).toString() }));
|
|
1960
|
+
}
|
|
1961
|
+
function suggestPropertyWeights(visitors, bounds = {}) {
|
|
1962
|
+
const floor = bounds.floorBasisPoints ?? 1e3, ceiling = bounds.ceilingBasisPoints ?? 4e3, n = visitors.length, at = "suggestPropertyWeights";
|
|
1963
|
+
if (n < 1 || n > 100 || visitors.some((v) => !Number.isSafeInteger(v) || v < 0)) fail2(at + ".visitors", "one to 100 whole, non-negative visitor counts");
|
|
1964
|
+
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");
|
|
1965
|
+
const weight = visitors.map((v) => v + 1);
|
|
1966
|
+
const total = (lambda) => weight.reduce((a, w) => a + Math.min(ceiling, Math.max(floor, lambda * w)), 0);
|
|
1967
|
+
let low = 0, high = ceiling / Math.min(...weight) + 1;
|
|
1968
|
+
for (let i = 0; i < 200; i++) {
|
|
1969
|
+
const mid = (low + high) / 2;
|
|
1970
|
+
if (total(mid) < 1e4) low = mid;
|
|
1971
|
+
else high = mid;
|
|
1972
|
+
}
|
|
1973
|
+
const share = weight.map((w) => Math.min(ceiling, Math.max(floor, high * w)));
|
|
1974
|
+
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);
|
|
1975
|
+
let left = 1e4 - whole.reduce((a, b) => a + b, 0);
|
|
1976
|
+
for (const r of rest) {
|
|
1977
|
+
if (left <= 0) break;
|
|
1978
|
+
whole[r.i] += 1;
|
|
1979
|
+
left -= 1;
|
|
1980
|
+
}
|
|
1981
|
+
return whole;
|
|
1982
|
+
}
|
|
1983
|
+
function deterministicUuid(seed) {
|
|
1984
|
+
const mask = (1n << 64n) - 1n, prime = 0x100000001b3n, bytes = new TextEncoder().encode(seed);
|
|
1985
|
+
const hash = (basis) => {
|
|
1986
|
+
let h = basis;
|
|
1987
|
+
for (const b of bytes) {
|
|
1988
|
+
h ^= BigInt(b);
|
|
1989
|
+
h = h * prime & mask;
|
|
1990
|
+
}
|
|
1991
|
+
return h.toString(16).padStart(16, "0");
|
|
1992
|
+
};
|
|
1993
|
+
const hex = hash(0xcbf29ce484222325n) + hash(0x84222325cbf29ce4n);
|
|
1994
|
+
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)}`;
|
|
1995
|
+
}
|
|
1996
|
+
var PLACEHOLDER_CREATIVE_ID = "00000000-0000-4000-8000-000000000000";
|
|
1997
|
+
var clip = (value, max) => value.length <= max ? value : value.slice(0, max);
|
|
1998
|
+
function expandPropertyChannels(definition2, groupKey, additions, options) {
|
|
1999
|
+
const at = "expandPropertyChannels";
|
|
2000
|
+
const group = definition2.channels.filter((c) => isMetaChannel(c) && c.channelGroup?.key === groupKey);
|
|
2001
|
+
if (!group.length) fail2(at + ".group", "needs an existing property channel to use as the template");
|
|
2002
|
+
const template = group[0];
|
|
2003
|
+
const present = new Set(group.map((c) => c.property?.key));
|
|
2004
|
+
const keys = additions.map((a) => a.key);
|
|
2005
|
+
unique(keys, at + ".additions");
|
|
2006
|
+
const fresh = additions.filter((a) => !present.has(a.key));
|
|
2007
|
+
if (!fresh.length) return { channels: [], allocations: [], blockingReasons: [] };
|
|
2008
|
+
const weightOf = (key, own) => own ?? options.weights?.[key] ?? 1;
|
|
2009
|
+
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) }))];
|
|
2010
|
+
const total = group.reduce((a, c) => addMoney(a, c.allocation), { currency: template.allocation.currency, amountMicros: "0" });
|
|
2011
|
+
const split = splitBudget(total, members.map((m) => m.weight), options.quantumMicros);
|
|
2012
|
+
const allocations = members.map((m, i) => ({ channelId: m.id, allocation: split[i] }));
|
|
2013
|
+
const { tier: _tier, primaryText: _primary, convertersAcknowledged: _converters, ...rest } = template;
|
|
2014
|
+
const channels = fresh.map((a) => {
|
|
2015
|
+
const id = members.find((m) => m.key === a.key).id;
|
|
2016
|
+
const proposal = {
|
|
2017
|
+
...rest,
|
|
2018
|
+
id,
|
|
2019
|
+
localCampaignKey: clip(`${groupKey}-${a.key}`, 80),
|
|
2020
|
+
localAdSetKey: clip(`${a.key}-visitors`, 80),
|
|
2021
|
+
localAdKey: clip(`${a.key}-1`, 80),
|
|
2022
|
+
property: { key: a.key, label: a.label },
|
|
2023
|
+
destinationId: a.destinationId,
|
|
2024
|
+
audienceRuleRefs: a.audienceRuleRefs,
|
|
2025
|
+
creativeIds: [],
|
|
2026
|
+
allocation: allocations.find((x) => x.channelId === id).allocation
|
|
2027
|
+
};
|
|
2028
|
+
meta.read({ ...proposal, creativeIds: [PLACEHOLDER_CREATIVE_ID] }, at + ".channel");
|
|
2029
|
+
return proposal;
|
|
2030
|
+
});
|
|
2031
|
+
const combined = [...definition2.channels, ...channels.map((c) => ({ ...c, creativeIds: [PLACEHOLDER_CREATIVE_ID] }))];
|
|
2032
|
+
unique(combined.map((c) => c.id), at + ".channels");
|
|
2033
|
+
checkChannelGroups(combined);
|
|
2034
|
+
const changed = group.some((c) => canonical(allocations.find((x) => x.channelId === c.id).allocation) !== canonical(c.allocation));
|
|
2035
|
+
return { channels, allocations, blockingReasons: [...fresh.map((a) => `property_creative_required:${a.key}`), ...changed ? ["rebalance_changes_running_allocations"] : []] };
|
|
2036
|
+
}
|
|
2037
|
+
function metaExclusionPolicy(channel2, use) {
|
|
2038
|
+
const special = channel2.specialCategories.length > 0;
|
|
2039
|
+
if (use.targetingLevel && special && !META_SAC_CUSTOM_AUDIENCE_EXCLUSION_VERIFIED) return { allowed: false, reason: "meta_exclusion_targeting_blocked_special_category", requiresEligibilityReadback: false };
|
|
2040
|
+
return { allowed: true, reason: null, requiresEligibilityReadback: special && (use.inRule || use.targetingLevel) };
|
|
2041
|
+
}
|
|
2042
|
+
function deriveProviderRatios(items) {
|
|
2043
|
+
const unknown = (reasonCode) => ({ frequency: { state: "unknown", reasonCode }, costPerResult: { state: "unknown", reasonCode }, reasonCodes: [reasonCode] });
|
|
2044
|
+
if (!items.length) return unknown("no_inputs");
|
|
2045
|
+
const first = items[0];
|
|
2046
|
+
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");
|
|
2047
|
+
const named = (name) => items.filter((i) => i.name === name);
|
|
2048
|
+
if (RESONANCE_PROVIDER_METRIC_NAMES.some((name) => named(name).length > 1)) return unknown("duplicate_metric");
|
|
2049
|
+
const count = (name) => {
|
|
2050
|
+
const i = named(name)[0];
|
|
2051
|
+
return i && i.state === "observed" && i.value?.kind === "count" ? BigInt(i.value.count) : null;
|
|
2052
|
+
};
|
|
2053
|
+
const spend = () => {
|
|
2054
|
+
const i = named("spend")[0];
|
|
2055
|
+
return i && i.state === "observed" && i.value?.kind === "money" ? i.value.money : null;
|
|
2056
|
+
};
|
|
2057
|
+
const reasons = [];
|
|
2058
|
+
let frequency;
|
|
2059
|
+
const impressions = count("impressions"), reach = count("reach");
|
|
2060
|
+
if (impressions === null || reach === null) {
|
|
2061
|
+
frequency = { state: "unknown", reasonCode: impressions === null ? "missing_impressions" : "missing_reach" };
|
|
2062
|
+
reasons.push(frequency.reasonCode);
|
|
2063
|
+
} else if (reach === 0n) {
|
|
2064
|
+
frequency = { state: "unknown", reasonCode: "no_reach" };
|
|
2065
|
+
reasons.push("no_reach");
|
|
2066
|
+
} else frequency = { state: "observed", value: { kind: "ratio", numerator: impressions.toString(), denominator: reach.toString() } };
|
|
2067
|
+
let costPerResult;
|
|
2068
|
+
const money2 = spend(), results = count("results");
|
|
2069
|
+
if (money2 === null || results === null) {
|
|
2070
|
+
costPerResult = { state: "unknown", reasonCode: money2 === null ? "missing_spend" : "missing_results" };
|
|
2071
|
+
reasons.push(costPerResult.reasonCode);
|
|
2072
|
+
} else if (results === 0n) {
|
|
2073
|
+
costPerResult = { state: "unknown", reasonCode: "no_results" };
|
|
2074
|
+
reasons.push("no_results");
|
|
2075
|
+
} else {
|
|
2076
|
+
const micros = BigInt(money2.amountMicros);
|
|
2077
|
+
let quotient = micros / results;
|
|
2078
|
+
const twice = 2n * (micros % results);
|
|
2079
|
+
if (twice > results || twice === results && quotient % 2n === 1n) quotient += 1n;
|
|
2080
|
+
costPerResult = { state: "observed", money: { currency: money2.currency, amountMicros: quotient.toString() } };
|
|
2081
|
+
}
|
|
2082
|
+
return { frequency, costPerResult, reasonCodes: reasons };
|
|
2083
|
+
}
|
|
1651
2084
|
|
|
1652
2085
|
exports.MAX_MONEY_MICROS = MAX_MONEY_MICROS;
|
|
2086
|
+
exports.META_AUDIENCE_RULE_LIMIT = META_AUDIENCE_RULE_LIMIT;
|
|
2087
|
+
exports.META_CALL_TO_ACTIONS = META_CALL_TO_ACTIONS;
|
|
2088
|
+
exports.META_SAC_CUSTOM_AUDIENCE_EXCLUSION_VERIFIED = META_SAC_CUSTOM_AUDIENCE_EXCLUSION_VERIFIED;
|
|
2089
|
+
exports.META_WEBSITE_AUDIENCE_MAX_RETENTION_DAYS = META_WEBSITE_AUDIENCE_MAX_RETENTION_DAYS;
|
|
1653
2090
|
exports.MONEY_EXPONENT = MONEY_EXPONENT;
|
|
1654
2091
|
exports.MONEY_JSON_SCHEMA = MONEY_JSON_SCHEMA;
|
|
1655
2092
|
exports.RESONANCE_ACCEPT_COMMAND_JSON_SCHEMA = RESONANCE_ACCEPT_COMMAND_JSON_SCHEMA;
|
|
@@ -1691,6 +2128,7 @@ exports.RESONANCE_MANDATE_DRAFT_REQUEST_JSON_SCHEMA = RESONANCE_MANDATE_DRAFT_RE
|
|
|
1691
2128
|
exports.RESONANCE_MANDATE_REF_JSON_SCHEMA = RESONANCE_MANDATE_REF_JSON_SCHEMA;
|
|
1692
2129
|
exports.RESONANCE_MANDATE_SCOPE_JSON_SCHEMA = RESONANCE_MANDATE_SCOPE_JSON_SCHEMA;
|
|
1693
2130
|
exports.RESONANCE_MANDATE_TARGET_JSON_SCHEMA = RESONANCE_MANDATE_TARGET_JSON_SCHEMA;
|
|
2131
|
+
exports.RESONANCE_MAX_CHANNELS_PER_GROUP = RESONANCE_MAX_CHANNELS_PER_GROUP;
|
|
1694
2132
|
exports.RESONANCE_MEASUREMENT_CONFIGURATION_CURRENT_JSON_SCHEMA = RESONANCE_MEASUREMENT_CONFIGURATION_CURRENT_JSON_SCHEMA;
|
|
1695
2133
|
exports.RESONANCE_MEASUREMENT_CONFIGURATION_SAVE_COMMAND_JSON_SCHEMA = RESONANCE_MEASUREMENT_CONFIGURATION_SAVE_COMMAND_JSON_SCHEMA;
|
|
1696
2134
|
exports.RESONANCE_MEASUREMENT_CONFIGURATION_SAVE_RESPONSE_JSON_SCHEMA = RESONANCE_MEASUREMENT_CONFIGURATION_SAVE_RESPONSE_JSON_SCHEMA;
|
|
@@ -1702,11 +2140,17 @@ exports.RESONANCE_META_CONFIGURATION_SAVE_RESPONSE_JSON_SCHEMA = RESONANCE_META_
|
|
|
1702
2140
|
exports.RESONANCE_META_CONFIGURATION_SNAPSHOT_JSON_SCHEMA = RESONANCE_META_CONFIGURATION_SNAPSHOT_JSON_SCHEMA;
|
|
1703
2141
|
exports.RESONANCE_META_CONFIGURATION_VIEW_JSON_SCHEMA = RESONANCE_META_CONFIGURATION_VIEW_JSON_SCHEMA;
|
|
1704
2142
|
exports.RESONANCE_METRIC_JSON_SCHEMA = RESONANCE_METRIC_JSON_SCHEMA;
|
|
2143
|
+
exports.RESONANCE_OBSERVATIONS_PAGE_JSON_SCHEMA = RESONANCE_OBSERVATIONS_PAGE_JSON_SCHEMA;
|
|
2144
|
+
exports.RESONANCE_OBSERVATION_SUPPORT_JSON_SCHEMA = RESONANCE_OBSERVATION_SUPPORT_JSON_SCHEMA;
|
|
1705
2145
|
exports.RESONANCE_OCCURRENCE_RESPONSE_JSON_SCHEMA = RESONANCE_OCCURRENCE_RESPONSE_JSON_SCHEMA;
|
|
1706
2146
|
exports.RESONANCE_OPTIMIZATION_DECISION_JSON_SCHEMA = RESONANCE_OPTIMIZATION_DECISION_JSON_SCHEMA;
|
|
1707
2147
|
exports.RESONANCE_OPTIMIZATION_EVIDENCE_JSON_SCHEMA = RESONANCE_OPTIMIZATION_EVIDENCE_JSON_SCHEMA;
|
|
1708
2148
|
exports.RESONANCE_OPTIMIZATION_POLICY_JSON_SCHEMA = RESONANCE_OPTIMIZATION_POLICY_JSON_SCHEMA;
|
|
1709
2149
|
exports.RESONANCE_PREPARED_PLAN_JSON_SCHEMA = RESONANCE_PREPARED_PLAN_JSON_SCHEMA;
|
|
2150
|
+
exports.RESONANCE_PROVIDER_METRIC_NAMES = RESONANCE_PROVIDER_METRIC_NAMES;
|
|
2151
|
+
exports.RESONANCE_PROVIDER_REPORTING_GRANT_JSON_SCHEMA = RESONANCE_PROVIDER_REPORTING_GRANT_JSON_SCHEMA;
|
|
2152
|
+
exports.RESONANCE_PROVIDER_REPORTING_SELECTION_JSON_SCHEMA = RESONANCE_PROVIDER_REPORTING_SELECTION_JSON_SCHEMA;
|
|
2153
|
+
exports.RESONANCE_PUBLIC_OBSERVATION_METRIC_JSON_SCHEMA = RESONANCE_PUBLIC_OBSERVATION_METRIC_JSON_SCHEMA;
|
|
1710
2154
|
exports.RESONANCE_QUALIFICATION_RULE_JSON_SCHEMA = RESONANCE_QUALIFICATION_RULE_JSON_SCHEMA;
|
|
1711
2155
|
exports.RESONANCE_RECEIPT_JSON_SCHEMA = RESONANCE_RECEIPT_JSON_SCHEMA;
|
|
1712
2156
|
exports.RESONANCE_RESOLVED_QUALIFICATION_RULE_JSON_SCHEMA = RESONANCE_RESOLVED_QUALIFICATION_RULE_JSON_SCHEMA;
|
|
@@ -1722,11 +2166,16 @@ exports.RESONANCE_WEBSITE_VISIT_FEED_REVIEW_JSON_SCHEMA = RESONANCE_WEBSITE_VISI
|
|
|
1722
2166
|
exports.RESONANCE_WEBSITE_VISIT_PROFILE = RESONANCE_WEBSITE_VISIT_PROFILE;
|
|
1723
2167
|
exports.ResonanceValidationError = ResonanceValidationError;
|
|
1724
2168
|
exports.addMoney = addMoney;
|
|
2169
|
+
exports.checkAudienceBand = checkAudienceBand;
|
|
2170
|
+
exports.checkChannelGroups = checkChannelGroups;
|
|
1725
2171
|
exports.compareMoney = compareMoney;
|
|
1726
2172
|
exports.cpqlMissingOutcomeBound = cpqlMissingOutcomeBound;
|
|
2173
|
+
exports.deriveProviderRatios = deriveProviderRatios;
|
|
2174
|
+
exports.expandPropertyChannels = expandPropertyChannels;
|
|
1727
2175
|
exports.formatMoney = formatMoney;
|
|
1728
2176
|
exports.googleConversionActionSemantics = googleConversionActionSemantics;
|
|
1729
2177
|
exports.googleUploadClicksSetupSemantics = googleUploadClicksSetupSemantics;
|
|
2178
|
+
exports.metaExclusionPolicy = metaExclusionPolicy;
|
|
1730
2179
|
exports.moneyFromProviderUnits = moneyFromProviderUnits;
|
|
1731
2180
|
exports.moneyToProviderUnits = moneyToProviderUnits;
|
|
1732
2181
|
exports.parseMoney = parseMoney;
|
|
@@ -1776,12 +2225,17 @@ exports.parseResonanceMetaConfigurationSaveResponse = parseResonanceMetaConfigur
|
|
|
1776
2225
|
exports.parseResonanceMetaConfigurationSnapshot = parseResonanceMetaConfigurationSnapshot;
|
|
1777
2226
|
exports.parseResonanceMetaConfigurationView = parseResonanceMetaConfigurationView;
|
|
1778
2227
|
exports.parseResonanceMetricObservation = parseResonanceMetricObservation;
|
|
2228
|
+
exports.parseResonanceObservationSupport = parseResonanceObservationSupport;
|
|
2229
|
+
exports.parseResonanceObservationsPage = parseResonanceObservationsPage;
|
|
1779
2230
|
exports.parseResonanceOccurrenceResponse = parseResonanceOccurrenceResponse;
|
|
1780
2231
|
exports.parseResonanceOptimizationDecision = parseResonanceOptimizationDecision;
|
|
1781
2232
|
exports.parseResonanceOptimizationEvidence = parseResonanceOptimizationEvidence;
|
|
1782
2233
|
exports.parseResonanceOptimizationPolicy = parseResonanceOptimizationPolicy;
|
|
1783
2234
|
exports.parseResonancePrepareCommand = parseResonancePrepareCommand;
|
|
1784
2235
|
exports.parseResonancePreparedPlan = parseResonancePreparedPlan;
|
|
2236
|
+
exports.parseResonanceProviderReportingGrant = parseResonanceProviderReportingGrant;
|
|
2237
|
+
exports.parseResonanceProviderReportingSelection = parseResonanceProviderReportingSelection;
|
|
2238
|
+
exports.parseResonancePublicObservationMetric = parseResonancePublicObservationMetric;
|
|
1785
2239
|
exports.parseResonanceQualificationRule = parseResonanceQualificationRule;
|
|
1786
2240
|
exports.parseResonanceReceipt = parseResonanceReceipt;
|
|
1787
2241
|
exports.parseResonanceResolvedQualificationRule = parseResonanceResolvedQualificationRule;
|
|
@@ -1792,6 +2246,7 @@ exports.parseResonanceWebsiteVisitFeedReview = parseResonanceWebsiteVisitFeedRev
|
|
|
1792
2246
|
exports.projectResonanceGoogleConfiguration = projectResonanceGoogleConfiguration;
|
|
1793
2247
|
exports.projectResonanceMeasurementConfiguration = projectResonanceMeasurementConfiguration;
|
|
1794
2248
|
exports.projectResonanceMetaConfiguration = projectResonanceMetaConfiguration;
|
|
2249
|
+
exports.reportedCpqlMissingOutcomeBound = reportedCpqlMissingOutcomeBound;
|
|
1795
2250
|
exports.resonanceCommandDigestInput = resonanceCommandDigestInput;
|
|
1796
2251
|
exports.resonanceGoogleConfigurationDigestInput = resonanceGoogleConfigurationDigestInput;
|
|
1797
2252
|
exports.resonanceGoogleSetupDigestInput = resonanceGoogleSetupDigestInput;
|
|
@@ -1806,4 +2261,6 @@ exports.resonanceOptimizationPolicyDigestInput = resonanceOptimizationPolicyDige
|
|
|
1806
2261
|
exports.resonancePlanIssues = resonancePlanIssues;
|
|
1807
2262
|
exports.resonanceWebsiteVisitEventTime = resonanceWebsiteVisitEventTime;
|
|
1808
2263
|
exports.resonanceWebsiteVisitProfileDigestInput = resonanceWebsiteVisitProfileDigestInput;
|
|
2264
|
+
exports.splitBudget = splitBudget;
|
|
1809
2265
|
exports.subtractMoney = subtractMoney;
|
|
2266
|
+
exports.suggestPropertyWeights = suggestPropertyWeights;
|