@sonordev/contracts 2.21.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/dist/resonance.js CHANGED
@@ -389,7 +389,7 @@ 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");
@@ -476,7 +476,39 @@ var search = object2({ ...channelBase, localCampaignKey: text2(80), kind: litera
476
476
  var metaAgeConstraint = union2(refine2(object2({ mode: literal2("bounded"), min: integer2(1, 120), max: integer2(1, 120) }), (v, p) => {
477
477
  if (v.min > v.max) fail2(p, "minimum age exceeds maximum");
478
478
  }), object2({ mode: literal2("omitted") }), object2({ mode: literal2("provider_managed") }));
479
- 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) });
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
+ });
480
512
  var owned = object2({ ...channelBase, kind: choice2("funnel", "broadcast", "outreach"), resourceRef: resource });
481
513
  var channel = union2(search, meta, owned);
482
514
  var definitionFields = { schemaVersion: literal2(1), projectId: uuid, name: text2(160), slug: refine2(text2(80), (v, p) => {
@@ -522,6 +554,9 @@ function checkDefinition(v) {
522
554
  if ("bidding" in c && "target" in c.bidding && c.bidding.target.currency !== v.budget.total.currency) fail2("campaign.channels.bidding", "currency mismatch");
523
555
  if ("allocation" in c && c.allocation.currency !== v.budget.total.currency) fail2("campaign.channels.allocation", "currency mismatch");
524
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");
525
560
  const policy = v.optimization.policy;
526
561
  if (policy.algorithm === "finite_meta_candidates_v1") {
527
562
  const guard = policy.measurementGuard, goal = v.objective;
@@ -883,12 +918,13 @@ function parseResonanceCampaignView(v) {
883
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) => {
884
919
  if (v === "0") fail2(p, "zero denominator");
885
920
  }) }));
886
- 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) })) };
887
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) }));
888
923
  function parseResonanceMetricObservation(v) {
889
924
  const r = metric.read(v, "metric");
890
925
  if (["accepted_goals", "qualified_goals", "revenue", "conversion_rate"].includes(r.name) && r.goalRevision === null) fail2("metric.goalRevision", "goal measurement requires explicit revision");
891
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");
892
928
  if (r.state === "observed") {
893
929
  const expected = r.name === "spend" || r.name === "revenue" ? "money" : r.name === "conversion_rate" ? "ratio" : "count";
894
930
  if (r.value.kind !== expected) fail2("metric.value", "metric unit mismatch");
@@ -1229,8 +1265,8 @@ function parseResonanceOptimizationEvidence(v, preparedPlan) {
1229
1265
  parseResonanceMetricObservation(o);
1230
1266
  if (o.projectId !== r.projectId || o.campaignId !== r.campaignId || o.site !== c.site) fail2(p + ".candidates.ownMeasurement", "foreign candidate measurement scope");
1231
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");
1232
- const aggregate = o.source === "provider" && ["spend", "clicks", "impressions"].includes(o.name);
1233
- 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");
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");
1234
1270
  }
1235
1271
  }
1236
1272
  return r;
@@ -1370,9 +1406,11 @@ function checkOptimizationDecisionEvidence(d, e) {
1370
1406
  }
1371
1407
  var RESONANCE_OPTIMIZATION_EVIDENCE_JSON_SCHEMA = optimizationEvidence.schema;
1372
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 });
1373
1410
  var publicDestination = union2(
1374
1411
  object2({ provider: literal2("google_ads"), id: uuid, tagId: text2(40, /^AW-[0-9]+$/) }),
1375
- object2({ provider: literal2("meta_ads"), id: uuid, pixelId: text2(40, /^[0-9]+$/) })
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) })
1376
1414
  );
1377
1415
  var interestResource = object2({ ...scope, type: choice2("page", "article", "product", "listing"), id: text2(160, /^[a-zA-Z0-9._:-]+$/), revision });
1378
1416
  var measurementConfig = object2({
@@ -1384,7 +1422,8 @@ var measurementConfig = object2({
1384
1422
  enabled: bool,
1385
1423
  consentPolicy: object2({ mode: literal2("basic"), requiredPurposes: list2(purpose, 4, 1) }),
1386
1424
  destinations: list2(publicDestination, 10),
1387
- resourceRules: list2(object2({ id: uuid, revision, site, resource: interestResource, path, interestKey: text2(100, /^[a-zA-Z0-9._:-]+$/) }), 500)
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)
1388
1427
  });
1389
1428
  function parseResonanceMeasurementConfig(v) {
1390
1429
  const r = measurementConfig.read(v, "measurementConfig");
@@ -1496,11 +1535,12 @@ var audienceDraft = object2({
1496
1535
  schemaVersion: literal2(1),
1497
1536
  expectedRevision: optional2(integer2(1)),
1498
1537
  idempotencyKey: operationKey,
1499
- 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 })
1500
1539
  });
1501
1540
  function parseResonanceAudienceDraftSaveCommand(v) {
1502
1541
  const r = audienceDraft.read(v, "audienceDraftSave");
1503
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");
1504
1544
  return r;
1505
1545
  }
1506
1546
  var RESONANCE_AUDIENCE_DRAFT_SAVE_COMMAND_JSON_SCHEMA = audienceDraft.schema;
@@ -1669,6 +1709,7 @@ function checkMetaMaterial(v, p) {
1669
1709
  unique(v.audiences.map((a) => a.audienceRuleRef.id), p + ".audiences");
1670
1710
  unique(v.channel.audienceRuleRefs.map((a) => a.id), p + ".channel.audienceRuleRefs");
1671
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");
1672
1713
  for (const a of v.audiences) {
1673
1714
  if (!v.channel.audienceRuleRefs.some((ref) => canonical(ref) === canonical(a.audienceRuleRef))) fail2(p + ".audiences", "original logical audience version mismatch");
1674
1715
  unique(a.excludedResourceRuleRefs.map((ref) => ref.id), p + ".audiences.excludedResourceRuleRefs");
@@ -1800,7 +1841,7 @@ function parseResonanceObservationSupport(v) {
1800
1841
  }
1801
1842
  return r;
1802
1843
  }
1803
- var observationsPage = object2({ items: list2(publicObservationMetric, 300), nextCursor: nullable2(uuid), observedAt: instant, support: list2(observationSupport, 300) });
1844
+ var observationsPage = object2({ items: list2(publicObservationMetric, 500), nextCursor: nullable2(uuid), observedAt: instant, support: list2(observationSupport, 500) });
1804
1845
  function parseResonanceObservationsPage(v) {
1805
1846
  const r = observationsPage.read(v, "observationsPage"), p = "observationsPage";
1806
1847
  if (r.items.length !== r.support.length) fail2(p + ".support", "requires one support entry for each metric item");
@@ -1824,7 +1865,7 @@ function parseResonanceObservationsPage(v) {
1824
1865
  rows.set(rowId, row);
1825
1866
  if (s.source === "provider") {
1826
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");
1827
- if (!["spend", "impressions", "clicks"].includes(item.name) || item.sourceRef !== item.observationId || item.countingUnit !== "provider_aggregate" || item.attributionModel !== "provider_reported") fail2(p + ".items", "provider metrics retain exact native observation and aggregate semantics");
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");
1828
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");
1829
1870
  } else {
1830
1871
  const d = s.denominators;
@@ -1842,8 +1883,210 @@ function parseResonanceObservationsPage(v) {
1842
1883
  var RESONANCE_PUBLIC_OBSERVATION_METRIC_JSON_SCHEMA = publicObservationMetric.schema;
1843
1884
  var RESONANCE_OBSERVATION_SUPPORT_JSON_SCHEMA = observationSupport.schema;
1844
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
+ }
1845
2084
 
1846
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;
1847
2090
  exports.MONEY_EXPONENT = MONEY_EXPONENT;
1848
2091
  exports.MONEY_JSON_SCHEMA = MONEY_JSON_SCHEMA;
1849
2092
  exports.RESONANCE_ACCEPT_COMMAND_JSON_SCHEMA = RESONANCE_ACCEPT_COMMAND_JSON_SCHEMA;
@@ -1885,6 +2128,7 @@ exports.RESONANCE_MANDATE_DRAFT_REQUEST_JSON_SCHEMA = RESONANCE_MANDATE_DRAFT_RE
1885
2128
  exports.RESONANCE_MANDATE_REF_JSON_SCHEMA = RESONANCE_MANDATE_REF_JSON_SCHEMA;
1886
2129
  exports.RESONANCE_MANDATE_SCOPE_JSON_SCHEMA = RESONANCE_MANDATE_SCOPE_JSON_SCHEMA;
1887
2130
  exports.RESONANCE_MANDATE_TARGET_JSON_SCHEMA = RESONANCE_MANDATE_TARGET_JSON_SCHEMA;
2131
+ exports.RESONANCE_MAX_CHANNELS_PER_GROUP = RESONANCE_MAX_CHANNELS_PER_GROUP;
1888
2132
  exports.RESONANCE_MEASUREMENT_CONFIGURATION_CURRENT_JSON_SCHEMA = RESONANCE_MEASUREMENT_CONFIGURATION_CURRENT_JSON_SCHEMA;
1889
2133
  exports.RESONANCE_MEASUREMENT_CONFIGURATION_SAVE_COMMAND_JSON_SCHEMA = RESONANCE_MEASUREMENT_CONFIGURATION_SAVE_COMMAND_JSON_SCHEMA;
1890
2134
  exports.RESONANCE_MEASUREMENT_CONFIGURATION_SAVE_RESPONSE_JSON_SCHEMA = RESONANCE_MEASUREMENT_CONFIGURATION_SAVE_RESPONSE_JSON_SCHEMA;
@@ -1903,6 +2147,7 @@ exports.RESONANCE_OPTIMIZATION_DECISION_JSON_SCHEMA = RESONANCE_OPTIMIZATION_DEC
1903
2147
  exports.RESONANCE_OPTIMIZATION_EVIDENCE_JSON_SCHEMA = RESONANCE_OPTIMIZATION_EVIDENCE_JSON_SCHEMA;
1904
2148
  exports.RESONANCE_OPTIMIZATION_POLICY_JSON_SCHEMA = RESONANCE_OPTIMIZATION_POLICY_JSON_SCHEMA;
1905
2149
  exports.RESONANCE_PREPARED_PLAN_JSON_SCHEMA = RESONANCE_PREPARED_PLAN_JSON_SCHEMA;
2150
+ exports.RESONANCE_PROVIDER_METRIC_NAMES = RESONANCE_PROVIDER_METRIC_NAMES;
1906
2151
  exports.RESONANCE_PROVIDER_REPORTING_GRANT_JSON_SCHEMA = RESONANCE_PROVIDER_REPORTING_GRANT_JSON_SCHEMA;
1907
2152
  exports.RESONANCE_PROVIDER_REPORTING_SELECTION_JSON_SCHEMA = RESONANCE_PROVIDER_REPORTING_SELECTION_JSON_SCHEMA;
1908
2153
  exports.RESONANCE_PUBLIC_OBSERVATION_METRIC_JSON_SCHEMA = RESONANCE_PUBLIC_OBSERVATION_METRIC_JSON_SCHEMA;
@@ -1921,11 +2166,16 @@ exports.RESONANCE_WEBSITE_VISIT_FEED_REVIEW_JSON_SCHEMA = RESONANCE_WEBSITE_VISI
1921
2166
  exports.RESONANCE_WEBSITE_VISIT_PROFILE = RESONANCE_WEBSITE_VISIT_PROFILE;
1922
2167
  exports.ResonanceValidationError = ResonanceValidationError;
1923
2168
  exports.addMoney = addMoney;
2169
+ exports.checkAudienceBand = checkAudienceBand;
2170
+ exports.checkChannelGroups = checkChannelGroups;
1924
2171
  exports.compareMoney = compareMoney;
1925
2172
  exports.cpqlMissingOutcomeBound = cpqlMissingOutcomeBound;
2173
+ exports.deriveProviderRatios = deriveProviderRatios;
2174
+ exports.expandPropertyChannels = expandPropertyChannels;
1926
2175
  exports.formatMoney = formatMoney;
1927
2176
  exports.googleConversionActionSemantics = googleConversionActionSemantics;
1928
2177
  exports.googleUploadClicksSetupSemantics = googleUploadClicksSetupSemantics;
2178
+ exports.metaExclusionPolicy = metaExclusionPolicy;
1929
2179
  exports.moneyFromProviderUnits = moneyFromProviderUnits;
1930
2180
  exports.moneyToProviderUnits = moneyToProviderUnits;
1931
2181
  exports.parseMoney = parseMoney;
@@ -2011,4 +2261,6 @@ exports.resonanceOptimizationPolicyDigestInput = resonanceOptimizationPolicyDige
2011
2261
  exports.resonancePlanIssues = resonancePlanIssues;
2012
2262
  exports.resonanceWebsiteVisitEventTime = resonanceWebsiteVisitEventTime;
2013
2263
  exports.resonanceWebsiteVisitProfileDigestInput = resonanceWebsiteVisitProfileDigestInput;
2264
+ exports.splitBudget = splitBudget;
2014
2265
  exports.subtractMoney = subtractMoney;
2266
+ exports.suggestPropertyWeights = suggestPropertyWeights;