@mj-biz-apps/marketing-server 0.3.0 → 0.4.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.
Files changed (56) hide show
  1. package/dist/__tests__/linkedInTargeting.test.d.ts +2 -0
  2. package/dist/__tests__/linkedInTargeting.test.d.ts.map +1 -0
  3. package/dist/__tests__/linkedInTargeting.test.js +65 -0
  4. package/dist/__tests__/linkedInTargeting.test.js.map +1 -0
  5. package/dist/agents/MarketingCreativeAgent.d.ts +16 -0
  6. package/dist/agents/MarketingCreativeAgent.d.ts.map +1 -0
  7. package/dist/agents/MarketingCreativeAgent.js +28 -0
  8. package/dist/agents/MarketingCreativeAgent.js.map +1 -0
  9. package/dist/agents/MarketingExperimentationAgent.d.ts +39 -0
  10. package/dist/agents/MarketingExperimentationAgent.d.ts.map +1 -1
  11. package/dist/agents/MarketingExperimentationAgent.js +73 -3
  12. package/dist/agents/MarketingExperimentationAgent.js.map +1 -1
  13. package/dist/agents/index.d.ts +1 -0
  14. package/dist/agents/index.d.ts.map +1 -1
  15. package/dist/agents/index.js +3 -0
  16. package/dist/agents/index.js.map +1 -1
  17. package/dist/index.d.ts +3 -2
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +3 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/programs/google/GoogleAdsProgramDriver.d.ts.map +1 -1
  22. package/dist/programs/google/GoogleAdsProgramDriver.js +14 -3
  23. package/dist/programs/google/GoogleAdsProgramDriver.js.map +1 -1
  24. package/dist/programs/google/googleBrandAssets.d.ts +5 -0
  25. package/dist/programs/google/googleBrandAssets.d.ts.map +1 -1
  26. package/dist/programs/google/googleBrandAssets.js +20 -15
  27. package/dist/programs/google/googleBrandAssets.js.map +1 -1
  28. package/dist/programs/index.d.ts +4 -0
  29. package/dist/programs/index.d.ts.map +1 -1
  30. package/dist/programs/index.js +5 -0
  31. package/dist/programs/index.js.map +1 -1
  32. package/dist/programs/linkedin/LinkedInAdsClient.d.ts +123 -2
  33. package/dist/programs/linkedin/LinkedInAdsClient.d.ts.map +1 -1
  34. package/dist/programs/linkedin/LinkedInAdsClient.js +183 -26
  35. package/dist/programs/linkedin/LinkedInAdsClient.js.map +1 -1
  36. package/dist/programs/linkedin/LinkedInAdsProgramDriver.d.ts +38 -7
  37. package/dist/programs/linkedin/LinkedInAdsProgramDriver.d.ts.map +1 -1
  38. package/dist/programs/linkedin/LinkedInAdsProgramDriver.js +364 -70
  39. package/dist/programs/linkedin/LinkedInAdsProgramDriver.js.map +1 -1
  40. package/dist/programs/linkedin/linkedInExecutionContext.d.ts +6 -0
  41. package/dist/programs/linkedin/linkedInExecutionContext.d.ts.map +1 -1
  42. package/dist/programs/linkedin/linkedInExecutionContext.js +2 -1
  43. package/dist/programs/linkedin/linkedInExecutionContext.js.map +1 -1
  44. package/dist/programs/meta/MetaAdsClient.d.ts +101 -0
  45. package/dist/programs/meta/MetaAdsClient.d.ts.map +1 -0
  46. package/dist/programs/meta/MetaAdsClient.js +239 -0
  47. package/dist/programs/meta/MetaAdsClient.js.map +1 -0
  48. package/dist/programs/meta/MetaAdsProgramDriver.d.ts +76 -0
  49. package/dist/programs/meta/MetaAdsProgramDriver.d.ts.map +1 -0
  50. package/dist/programs/meta/MetaAdsProgramDriver.js +431 -0
  51. package/dist/programs/meta/MetaAdsProgramDriver.js.map +1 -0
  52. package/dist/programs/meta/metaAdsExecutionContext.d.ts +39 -0
  53. package/dist/programs/meta/metaAdsExecutionContext.d.ts.map +1 -0
  54. package/dist/programs/meta/metaAdsExecutionContext.js +99 -0
  55. package/dist/programs/meta/metaAdsExecutionContext.js.map +1 -0
  56. package/package.json +9 -8
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MetaAdsProgramDriver.d.ts","sourceRoot":"","sources":["../../../src/programs/meta/MetaAdsProgramDriver.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,OAAO,EAAgC,KAAK,QAAQ,EAAE,MAA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CAAC,OAAO,EAAE,gBAAgB,EAAE,MAAM,EAAE,sBAAsB,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAsB7G,yGAAyG;IACnF,aAAa,CAAC,OAAO,EAAE,gBAAgB,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,gBAAgB,CAAC;YAoBhG,QAAQ;YAWR,OAAO;YAqBP,cAAc;IAO5B,OAAO,CAAC,SAAS;IAWjB,OAAO,CAAC,SAAS;IAKjB,OAAO,CAAC,aAAa;IAMrB,OAAO,CAAC,WAAW;IAMnB,OAAO,CAAC,WAAW;CAItB;AAED,wBAAgB,wBAAwB,SAAK"}
@@ -0,0 +1,431 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ /**
11
+ * Meta Ads program driver (D-27) — the third executing ad type: Facebook and Instagram link ads through the
12
+ * Marketing API, for a brand with a Business Manager, an ad account and a Facebook Page.
13
+ *
14
+ * Deliberately a structural clone of `GoogleAdsProgramDriver` / `LinkedInAdsProgramDriver` — same shared levers
15
+ * (`AdCampaignConfig`, frozen at lock), same `ProgramPlatformRef` memory, same honesty rules (platform metrics are
16
+ * ALWAYS 'Inferred', V3-4; retire throws loudly if it cannot pause; a missing image degrades to the brand image,
17
+ * never to no ad). Platform differences live entirely below the contract. Meta's object ladder maps onto the ref
18
+ * kinds the two existing drivers already use:
19
+ *
20
+ * Meta campaign → 'CampaignGroup' (the objective shell, like LinkedIn's campaign group)
21
+ * Meta ad set → 'Campaign' (budget + schedule + targeting — the thing that spends and gets rescheduled)
22
+ * Meta creative → 'Creative'
23
+ * Meta ad → 'Other' with role 'ad'
24
+ * custom audience → 'Audience'
25
+ *
26
+ * Spend gating is NOT here by design: LockProgramAction runs the S4 guardrails and the approval gate (V3-12)
27
+ * BEFORE onLock — by the time this runs, a human approved the spend. The connection's launch state decides whether
28
+ * the objects are born PAUSED (default) or ACTIVE.
29
+ */
30
+ import { LogStatus, Metadata, RunView } from '@memberjunction/core';
31
+ import { EscapeSQLString, RegisterClass } from '@memberjunction/global';
32
+ import { ConvergeObservation } from '@mj-biz-apps/marketing-actions';
33
+ import { BaseProgramTypeDriver, META_ADS_TYPE_NAME, META_DEFAULT_COUNTRIES, assertPublicHttpUrl, effectiveCreative, elapsedReportingRange, parseAdCampaignConfig, platformObjectName, platformRunSchedule, stampUtm, toMarketingEntityName, } from '@mj-biz-apps/marketing-core';
34
+ import { META_CREDENTIAL_TYPE, isMetaRefused, resolveMetaExecutionContext, } from './metaAdsExecutionContext.js';
35
+ const REFS_ENTITY = 'MJ_BizApps_Marketing: Program Platform Refs';
36
+ /** The ad rides the 'Other' kind; StateJSON names the role. */
37
+ const AD_ROLE = 'ad';
38
+ /**
39
+ * Where the ad set serves. Meta requires at least one location; the app has no per-brand country lever yet, so
40
+ * every program targets the United States (the brands in rehearsal are US companies). A lever is a later ruling.
41
+ */
42
+ const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
43
+ let MetaAdsProgramDriver = class MetaAdsProgramDriver extends BaseProgramTypeDriver {
44
+ constructor(contextUser, resolveContext = resolveMetaExecutionContext) {
45
+ super();
46
+ this.contextUser = contextUser;
47
+ this.resolveContext = resolveContext;
48
+ this.typeName = META_ADS_TYPE_NAME;
49
+ /** Mirrors AdCampaignConfig — the parser is the enforcement, this is the declaration. */
50
+ this.paramSpecs = [
51
+ { name: 'tacticConfigJSON', valueType: 'Scalar', isArray: false, isRequired: true, description: 'The levers as JSON (Program.TacticConfigJSON): audience (targeted | website-retargeting), dailyBudgetUsd, landingPageUrl, optional creativeHeadline/creativeBody/creativeImageUrl/audienceWindowDays.' },
52
+ { name: 'campaignCode', valueType: 'Scalar', isArray: false, isRequired: true, description: 'Program.Code — stamped as utm_campaign and prefixed onto every platform object name.' },
53
+ ];
54
+ }
55
+ async validateProposal(program) {
56
+ const parsed = parseAdCampaignConfig(this.rawConfig(program));
57
+ const issues = [...parsed.issues];
58
+ if (parsed.config)
59
+ issues.push(...this.validateMetaCreative(parsed.config));
60
+ const user = this.contextUser;
61
+ if (user) {
62
+ const ctx = await this.resolveContext(program.brandId, user);
63
+ if (isMetaRefused(ctx)) {
64
+ // A staged proposal is legal; the proposer must know lock will refuse.
65
+ issues.push(...ctx.issues.map(i => ({
66
+ severity: 'warning',
67
+ code: i.code,
68
+ message: `${i.message} Lock will refuse until this is resolved.`,
69
+ })));
70
+ }
71
+ else if (parsed.config?.audience === 'website-retargeting' && !ctx.pixelId) {
72
+ issues.push({ severity: 'error', code: 'MA_NO_PIXEL', message: 'Website retargeting on Meta needs the brand\'s Pixel id on the Meta Ads credential — add it (Rotate) in Settings → Connections, or propose a targeted audience.' });
73
+ }
74
+ }
75
+ return issues;
76
+ }
77
+ /**
78
+ * Meta's link-ad copy limits, enforced at PROPOSE so the agent's copy is refused with field-level messages
79
+ * instead of silently truncating in the feed: headline ≤ 40 characters (Meta truncates beyond — an error here,
80
+ * a truncated promise is not the agent's promise), primary text ≤ 125 and description ≤ 30 are recommendations
81
+ * (the feed hides the rest behind "See more") — notices.
82
+ */
83
+ validateMetaCreative(config) {
84
+ const issues = [];
85
+ const creative = effectiveCreative(config);
86
+ for (const h of creative.headlines) {
87
+ if (h.length > 40)
88
+ issues.push({ severity: 'error', code: 'MA_HEADLINE_TOO_LONG', message: `Headline "${h.slice(0, 40)}…" exceeds Meta's 40-character limit (${h.length}).` });
89
+ }
90
+ const primary = creative.longHeadline ?? creative.descriptions[0] ?? null;
91
+ if (primary && primary.length > 125) {
92
+ issues.push({ severity: 'notice', code: 'MA_PRIMARY_TEXT_LONG', message: `The primary text runs ${primary.length} characters; Meta shows 125 before "See more".` });
93
+ }
94
+ for (const d of creative.descriptions) {
95
+ if (d.length > 30)
96
+ issues.push({ severity: 'notice', code: 'MA_DESCRIPTION_LONG', message: `Description "${d.slice(0, 30)}…" runs ${d.length} characters; Meta shows about 30 under the headline.` });
97
+ }
98
+ if (creative.headlines.length === 0) {
99
+ issues.push({ severity: 'notice', code: 'MA_CREATIVE_INCOMPLETE', message: 'Creative has no headline — Meta requires one; the ad will not be created until a headline is added.' });
100
+ }
101
+ return issues;
102
+ }
103
+ async onLock(program) {
104
+ const user = this.requireUser();
105
+ const config = this.requireConfig(program);
106
+ const code = this.requireCode(program);
107
+ const ctx = await this.resolveContext(program.brandId, user);
108
+ if (isMetaRefused(ctx)) {
109
+ throw new Error(`Meta Ads launch refused: ${ctx.issues.map(i => i.message).join(' ')}`);
110
+ }
111
+ const programId = program.id;
112
+ if (!programId)
113
+ throw new Error('Meta Ads launch requires a saved program (no id).');
114
+ // Per-object reuse, NOT an early return: every step reuses its recorded ref or creates fresh, so a lock
115
+ // that failed partway resumes exactly where it stopped (the Google driver's spike lesson).
116
+ const existing = await this.loadRefs(programId, user);
117
+ const stampedUrl = stampUtm(config.landingPageUrl, code, 'meta');
118
+ const status = ctx.launchState === 'Active' ? 'ACTIVE' : 'PAUSED';
119
+ const audienceId = await this.ensureAudience(programId, code, config, ctx, existing, user);
120
+ const campaignId = await this.ensureCampaign(programId, code, status, ctx, existing, user);
121
+ const adSetId = await this.ensureAdSet(program, programId, code, config, status, campaignId, audienceId, ctx, existing, user);
122
+ const adNote = await this.ensureAd(program, programId, code, config, status, adSetId, stampedUrl, ctx, existing, user);
123
+ LogStatus(`MetaAdsProgramDriver.onLock: ${code} ${status === 'ACTIVE' ? 'launched' : 'created PAUSED (Settings → Connections decides when it serves)'} — ${config.audience} audience, `
124
+ + `$${config.dailyBudgetUsd}/day, campaign ${campaignId}, ad set ${adSetId}; ${adNote}. Stamped landing URL recorded on the ad set ref.`);
125
+ }
126
+ async ensureAudience(programId, code, config, ctx, existing, user) {
127
+ if (config.audience !== 'website-retargeting')
128
+ return null;
129
+ const recorded = existing.find(r => r.ExternalKind === 'Audience')?.ExternalURN ?? null;
130
+ if (recorded)
131
+ return recorded;
132
+ if (!ctx.pixelId)
133
+ throw new Error('Meta Ads launch refused: website retargeting needs the brand\'s Pixel id on the Meta Ads credential (Settings → Connections).');
134
+ const days = config.audienceWindowDays ?? 90;
135
+ const name = platformObjectName(code, 'audience', `${days}d`);
136
+ const id = await ctx.client.findByName('customaudience', name)
137
+ ?? await ctx.client.createWebsiteCustomAudience(name, ctx.pixelId, days);
138
+ await this.saveRef(programId, ctx.brandConnectionId, 'Audience', id, { lookbackDays: days, pixelId: ctx.pixelId }, user);
139
+ return id;
140
+ }
141
+ async ensureCampaign(programId, code, status, ctx, existing, user) {
142
+ const recorded = existing.find(r => r.ExternalKind === 'CampaignGroup')?.ExternalURN ?? null;
143
+ if (recorded)
144
+ return recorded;
145
+ const name = platformObjectName(code, 'campaign');
146
+ const id = await ctx.client.findByName('campaign', name) ?? await ctx.client.createCampaign({ name, status });
147
+ await this.saveRef(programId, ctx.brandConnectionId, 'CampaignGroup', id, { objective: 'OUTCOME_TRAFFIC', status }, user);
148
+ return id;
149
+ }
150
+ async ensureAdSet(program, programId, code, config, status, campaignId, audienceId, ctx, existing, user) {
151
+ const recorded = existing.find(r => r.ExternalKind === 'Campaign')?.ExternalURN ?? null;
152
+ if (recorded)
153
+ return recorded;
154
+ const name = platformObjectName(code, 'campaign', 'ad set');
155
+ const runSchedule = await this.runScheduleFor(program, user);
156
+ const id = await ctx.client.findByName('adset', name) ?? await ctx.client.createAdSet({
157
+ name, campaignId, status, runSchedule,
158
+ dailyBudgetUsd: config.dailyBudgetUsd,
159
+ countries: [...META_DEFAULT_COUNTRIES],
160
+ customAudienceId: audienceId,
161
+ });
162
+ await this.saveRef(programId, ctx.brandConnectionId, 'Campaign', id, {
163
+ dailyBudgetUsd: config.dailyBudgetUsd,
164
+ landingPageUrl: stampUtm(config.landingPageUrl, code, 'meta'),
165
+ audience: config.audience,
166
+ runSchedule, status,
167
+ }, user);
168
+ return id;
169
+ }
170
+ /**
171
+ * The ad itself — copy authored in the levers (by the agent, frozen at lock), the image from the program's own
172
+ * lever first (KI-117) and the brand's landscape image as the default. A missing headline is an HONEST state:
173
+ * the ad set exists but cannot serve, and the log says exactly why.
174
+ */
175
+ async ensureAd(program, programId, code, config, status, adSetId, stampedUrl, ctx, existing, user) {
176
+ if (existing.some(r => r.ExternalKind === 'Other' && this.stateRole(r) === AD_ROLE))
177
+ return 'ad already attached (idempotent)';
178
+ const creative = effectiveCreative(config);
179
+ const headline = creative.headlines[0] ?? null;
180
+ if (!headline)
181
+ return 'no headline in the levers — ad set launches ad-less';
182
+ const description = creative.descriptions[0] ?? null;
183
+ // Primary text (above the card): the long headline when the agent wrote one, else the description, else the headline.
184
+ const message = creative.longHeadline ?? description ?? headline;
185
+ const { imageHash, imageNote } = await this.resolveImage(program.brandId, code, creative.imageUrl, ctx, user);
186
+ let creativeId = existing.find(r => r.ExternalKind === 'Creative')?.ExternalURN ?? null;
187
+ if (!creativeId) {
188
+ creativeId = await ctx.client.createCreative({
189
+ name: platformObjectName(code, 'campaign', 'creative'),
190
+ pageId: ctx.pageId, link: stampedUrl, message, headline, description, imageHash,
191
+ });
192
+ await this.saveRef(programId, ctx.brandConnectionId, 'Creative', creativeId, {
193
+ headline, description, message, imageHash, callToAction: 'LEARN_MORE', landingPageUrl: stampedUrl, pageId: ctx.pageId,
194
+ }, user);
195
+ }
196
+ const adId = await ctx.client.createAd({ name: platformObjectName(code, 'campaign', 'ad'), adSetId, creativeId, status });
197
+ await this.saveRef(programId, ctx.brandConnectionId, 'Other', adId, { role: AD_ROLE, creativeId, status }, user);
198
+ return `${imageNote} attached as ad ${adId}`;
199
+ }
200
+ async resolveImage(brandId, code, programImageUrl, ctx, user) {
201
+ if (programImageUrl) {
202
+ try {
203
+ return { imageHash: await this.uploadImageFromUrl(programImageUrl, 'program creative image', code, ctx), imageNote: 'link ad with the program\'s own creative image' };
204
+ }
205
+ catch (e) {
206
+ LogStatus(`MetaAdsProgramDriver.onLock: ${code} program creative image not used (${e instanceof Error ? e.message : String(e)}) — falling back to the brand image`);
207
+ }
208
+ }
209
+ try {
210
+ const hash = await this.uploadBrandImage(brandId, code, ctx, user);
211
+ if (hash)
212
+ return { imageHash: hash, imageNote: programImageUrl ? 'link ad with the brand marketing image (program image unusable)' : 'link ad with the brand marketing image' };
213
+ return { imageHash: null, imageNote: 'link ad without an image (no brand marketing image)' };
214
+ }
215
+ catch (e) {
216
+ const note = `link ad without an image — brand image not used (${e instanceof Error ? e.message : String(e)})`;
217
+ LogStatus(`MetaAdsProgramDriver.onLock: ${code} ${note}`);
218
+ return { imageHash: null, imageNote: note };
219
+ }
220
+ }
221
+ /** The brand's marketing image (Brand.MarketingImageURL — Settings → Brand ad assets). Null when the brand has none. */
222
+ async uploadBrandImage(brandId, code, ctx, user) {
223
+ const brand = await new Metadata().GetEntityObject('MJ_BizApps_Marketing: Brands', user);
224
+ if (!await brand.Load(brandId) || !brand.MarketingImageURL)
225
+ return null;
226
+ return this.uploadImageFromUrl(brand.MarketingImageURL, 'marketing image', code, ctx);
227
+ }
228
+ /** One fetch-and-upload for every image source (brand or program): public URL only (SSRF-guarded), PNG/JPEG, 5MB. */
229
+ async uploadImageFromUrl(url, label, code, ctx) {
230
+ const safety = assertPublicHttpUrl(url);
231
+ if (!safety.ok)
232
+ throw new Error(`${label} URL refused: ${safety.reason}`);
233
+ const res = await fetch(url, { redirect: 'follow' });
234
+ if (!res.ok)
235
+ throw new Error(`${label} URL returned ${res.status}`);
236
+ const type = (res.headers.get('content-type') ?? '').split(';')[0].trim().toLowerCase();
237
+ if (type !== 'image/png' && type !== 'image/jpeg')
238
+ throw new Error(`${label} is ${type || 'unknown type'} — PNG or JPEG required`);
239
+ const bytes = new Uint8Array(await res.arrayBuffer());
240
+ if (bytes.byteLength > MAX_IMAGE_BYTES)
241
+ throw new Error(`${label} exceeds 5MB`);
242
+ return ctx.client.uploadImage(bytes, platformObjectName(code, 'campaign', label));
243
+ }
244
+ /**
245
+ * The program's sprint window as the ad set's schedule — the LinkedIn driver's rule: lock passes the window on
246
+ * the driver shape before stamping it on the row; the row is only a fallback. Meta rejects a start in the past,
247
+ * so a sprint already under way starts now; a missing end leaves the window open (the decision pauses it anyway).
248
+ */
249
+ async runScheduleFor(program, user) {
250
+ let startMs = program.startDate ? new Date(program.startDate).getTime() : NaN;
251
+ let endMs = program.decisionDate ? new Date(program.decisionDate).getTime() : NaN;
252
+ if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) {
253
+ const row = (await new RunView().RunView({
254
+ EntityName: toMarketingEntityName('Programs'),
255
+ ExtraFilter: `ID='${EscapeSQLString(program.id ?? '')}'`,
256
+ Fields: ['StartDate', 'DecisionDate'],
257
+ MaxRows: 1, ResultType: 'simple', BypassCache: true,
258
+ }, user)).Results?.[0];
259
+ if (!Number.isFinite(startMs) && row?.StartDate)
260
+ startMs = new Date(row.StartDate).getTime();
261
+ if (!Number.isFinite(endMs) && row?.DecisionDate)
262
+ endMs = new Date(row.DecisionDate).getTime();
263
+ }
264
+ return platformRunSchedule(Number.isFinite(startMs) ? new Date(startMs) : null, Number.isFinite(endMs) ? new Date(endMs) : null);
265
+ }
266
+ async collectMetrics(program, window) {
267
+ const user = this.contextUser;
268
+ if (!user || !program.id)
269
+ return null;
270
+ const refs = await this.loadRefs(program.id, user);
271
+ const adSets = refs.filter(r => r.ExternalKind === 'Campaign').map(r => r.ExternalURN);
272
+ if (adSets.length === 0)
273
+ return null;
274
+ const ctx = await this.resolveContext(program.brandId, user);
275
+ if (isMetaRefused(ctx)) {
276
+ LogStatus(`MetaAdsProgramDriver.collectMetrics: connection unavailable (${ctx.issues.map(i => i.code).join(', ')}) — no observation.`);
277
+ return null;
278
+ }
279
+ // KI-89: ask the platform only for time that has happened (the window stays the observation's key).
280
+ const range = elapsedReportingRange(window, new Date());
281
+ if (!range)
282
+ return null;
283
+ const m = await ctx.client.adSetMetrics(adSets, range.from, range.to);
284
+ // All-zero is still an observation (KI-34): the ad set exists, the connection answered, nothing served.
285
+ return [{
286
+ segmentLabel: null,
287
+ observedMetric: m.conversions,
288
+ conversionsCount: m.conversions,
289
+ sampleSize: m.impressions,
290
+ source: `meta:insights:${ctx.adAccountId}`,
291
+ // Platform-reported attribution is an INPUT, never proof (V3-4).
292
+ attribution: 'Inferred',
293
+ }];
294
+ }
295
+ /** The continuous poll (HA-7), converged under the `meta:` source family (HA-5, KI-93). */
296
+ async refreshStatus(program, window) {
297
+ const user = this.contextUser;
298
+ if (!user || !program.id)
299
+ return { refreshed: false, sprintsUpdated: 0, observationsWritten: 0, note: 'MetaAdsProgramDriver: no user context.' };
300
+ const sprintId = window.sprintId;
301
+ if (!sprintId)
302
+ return { refreshed: false, sprintsUpdated: 0, observationsWritten: 0, note: 'MetaAdsProgramDriver: refresh needs a sprint window, not a roll-up.' };
303
+ const observations = await this.collectMetrics(program, window);
304
+ const top = observations?.find(o => o.segmentLabel === null) ?? null;
305
+ if (!top)
306
+ return { refreshed: false, sprintsUpdated: 0, observationsWritten: 0, note: 'MetaAdsProgramDriver: no ad set ref or the connection is unavailable — nothing to observe.' };
307
+ const saved = await ConvergeObservation({ programId: program.id, sprintId, attribution: top.attribution ?? 'Inferred', sourceRefPrefix: 'meta:' }, { window, activityCount: top.sampleSize ?? 0, conversionsCount: top.conversionsCount, observedMetric: top.observedMetric, sourceRef: top.source,
308
+ notes: `platform-reported (Inferred): conversions ${top.conversionsCount}, impressions ${top.sampleSize ?? 0}` }, user);
309
+ const note = `MetaAdsProgramDriver: ${top.conversionsCount} platform conversion(s) over ${top.sampleSize ?? 0} impressions — ${saved ? 'observation converged' : 'observation NOT saved'}.`;
310
+ LogStatus(`MetaAdsProgramDriver.refreshStatus: ${note}`);
311
+ return { refreshed: true, sprintsUpdated: 0, observationsWritten: saved ? 1 : 0, note };
312
+ }
313
+ async onRetire(program, reason) {
314
+ const user = this.requireUser();
315
+ if (!program.id)
316
+ return { stoodDown: false, note: 'Meta Ads: nothing to stand down — the program has no id.' };
317
+ const refs = await this.loadRefs(program.id, user);
318
+ const spending = refs.filter(r => r.ExternalKind === 'Campaign' || r.ExternalKind === 'CampaignGroup');
319
+ if (spending.length === 0)
320
+ return { stoodDown: false, note: 'Meta Ads: nothing to stand down — no campaign was ever launched for this program.' };
321
+ const ctx = await this.resolveContext(program.brandId, user);
322
+ if (isMetaRefused(ctx)) {
323
+ // The one unacceptable silence: a decided program whose ad set keeps spending.
324
+ throw new Error(`Meta Ads retire (${reason}) could not reach the platform — the ad set is still live: `
325
+ + ctx.issues.map(i => i.message).join(' '));
326
+ }
327
+ // Ad set first (the spender), then the campaign shell.
328
+ for (const ref of [...spending].sort(r => r.ExternalKind === 'Campaign' ? -1 : 1)) {
329
+ await ctx.client.setStatus(ref.ExternalURN, 'PAUSED');
330
+ await this.updateRefState(ref, { status: 'PAUSED', retiredFor: reason });
331
+ }
332
+ const note = `Meta Ads: ${spending.length} object(s) paused (${reason}).`;
333
+ LogStatus(`MetaAdsProgramDriver.onRetire: ${program.name ?? program.id} — ${note}`);
334
+ return { stoodDown: true, note };
335
+ }
336
+ /** KI-119 for Meta: the sprint moved after lock — the ad set gets the window the program now carries. */
337
+ async onWindowMoved(program, window) {
338
+ const user = this.requireUser();
339
+ if (!program.id)
340
+ return { rescheduled: false, note: 'Meta Ads: no saved program (no id).' };
341
+ const refs = await this.loadRefs(program.id, user);
342
+ const adSetId = refs.find(r => r.ExternalKind === 'Campaign')?.ExternalURN ?? null;
343
+ if (!adSetId)
344
+ return { rescheduled: false, note: 'Meta Ads: no ad set on the platform yet — nothing to move.' };
345
+ const ctx = await this.resolveContext(program.brandId, user);
346
+ if (isMetaRefused(ctx)) {
347
+ throw new Error(`Meta Ads reschedule refused: ${ctx.issues.map(i => i.message).join(' ')}`);
348
+ }
349
+ const runSchedule = platformRunSchedule(window.startDate, window.endDate);
350
+ await ctx.client.setAdSetSchedule(adSetId, runSchedule);
351
+ const fmt = (ms) => ms == null ? 'open' : new Date(ms).toISOString().slice(0, 10);
352
+ const note = `Meta Ads: ad set ${adSetId} now runs ${fmt(runSchedule.start)} → ${fmt(runSchedule.end)}`;
353
+ LogStatus(`MetaAdsProgramDriver.onWindowMoved: ${program.name ?? program.id} — ${note}`);
354
+ return { rescheduled: true, note };
355
+ }
356
+ // ── refs (the driver's memory) ──────────────────────────────────────────
357
+ async loadRefs(programId, user) {
358
+ const res = await new RunView().RunView({
359
+ EntityName: REFS_ENTITY,
360
+ // THIS platform's refs only (KI-105): a program also carries refs on other connections (HubSpot attribution).
361
+ ExtraFilter: `ProgramID='${EscapeSQLString(programId)}' AND BrandConnectionID IN (SELECT ID FROM __mj_BizAppsMarketing.vwBrandConnections WHERE CredentialType='${EscapeSQLString(META_CREDENTIAL_TYPE)}')`,
362
+ ResultType: 'entity_object',
363
+ BypassCache: true,
364
+ }, user);
365
+ return res.Success ? res.Results ?? [] : [];
366
+ }
367
+ async saveRef(programId, brandConnectionId, kind, urn, state, user) {
368
+ const existing = await this.loadRefs(programId, user);
369
+ if (existing.some(r => r.ExternalKind === kind && r.ExternalURN === urn))
370
+ return;
371
+ const md = new Metadata();
372
+ const ref = await md.GetEntityObject(REFS_ENTITY, user);
373
+ ref.NewRecord();
374
+ ref.ProgramID = programId;
375
+ ref.BrandConnectionID = brandConnectionId;
376
+ ref.ExternalKind = kind;
377
+ ref.ExternalURN = urn;
378
+ ref.StateJSON = state ? JSON.stringify(state) : null;
379
+ if (!await ref.Save()) {
380
+ throw new Error(`Could not record the ${kind} ref ${urn}: ${ref.LatestResult?.CompleteMessage ?? 'save failed'} `
381
+ + '— the platform object EXISTS; re-running lock is idempotent once the ref saves.');
382
+ }
383
+ }
384
+ async updateRefState(ref, patch) {
385
+ let state = {};
386
+ try {
387
+ state = ref.StateJSON ? JSON.parse(ref.StateJSON) : {};
388
+ }
389
+ catch { /* breadcrumbs only */ }
390
+ ref.StateJSON = JSON.stringify({ ...state, ...patch });
391
+ await ref.Save();
392
+ }
393
+ stateRole(ref) {
394
+ try {
395
+ const state = ref.StateJSON ? JSON.parse(ref.StateJSON) : {};
396
+ return typeof state['role'] === 'string' ? state['role'] : null;
397
+ }
398
+ catch {
399
+ return null;
400
+ }
401
+ }
402
+ // ── small guards ────────────────────────────────────────────────────────
403
+ rawConfig(program) {
404
+ const v = program.params['tacticConfigJSON'];
405
+ return typeof v === 'string' && v.trim() ? v : null;
406
+ }
407
+ requireConfig(program) {
408
+ const parsed = parseAdCampaignConfig(this.rawConfig(program));
409
+ if (!parsed.config)
410
+ throw new Error(`Meta Ads launch refused: ${parsed.issues.map(i => i.message).join(' ')}`);
411
+ return parsed.config;
412
+ }
413
+ requireCode(program) {
414
+ const code = typeof program.params['campaignCode'] === 'string' ? program.params['campaignCode'].trim() : '';
415
+ if (!code)
416
+ throw new Error('Meta Ads launch requires Program.Code (the campaign stamp) — lock assigns it before the driver runs.');
417
+ return code;
418
+ }
419
+ requireUser() {
420
+ if (!this.contextUser)
421
+ throw new Error('MetaAdsProgramDriver requires a contextUser.');
422
+ return this.contextUser;
423
+ }
424
+ };
425
+ MetaAdsProgramDriver = __decorate([
426
+ RegisterClass(BaseProgramTypeDriver, 'MetaAdsProgramDriver'),
427
+ __metadata("design:paramtypes", [Function, Function])
428
+ ], MetaAdsProgramDriver);
429
+ export { MetaAdsProgramDriver };
430
+ export function LoadMetaAdsProgramDriver() { }
431
+ //# sourceMappingURL=MetaAdsProgramDriver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MetaAdsProgramDriver.js","sourceRoot":"","sources":["../../../src/programs/meta/MetaAdsProgramDriver.ts"],"names":[],"mappings":";;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;GAmB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8XhC;;AAED,MAAM,UAAU,wBAAwB,KAAI,CAAC"}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Meta Ads execution context (D-27): from a brand to a ready API client — or an HONEST list of what's missing, in
3
+ * Settings → Connections vocabulary. The Meta twin of `googleAdsExecutionContext`.
4
+ *
5
+ * Chain: BrandConnection (brand × 'Meta Ads' credential type) → CredentialEngine (decrypted appSecret / accessToken,
6
+ * optional pixelId — the ONLY place secrets are resolved; they go straight into the client instance and nowhere
7
+ * else) → ExternalAccountID (the ad account, `act_<digits>` or bare digits) → the Facebook Page on the connection's
8
+ * configuration (`meta.pageId`), which every creative is published from.
9
+ */
10
+ import { type UserInfo } from '@memberjunction/core';
11
+ import { type CampaignLaunchState, type DriverValidationIssue } from '@mj-biz-apps/marketing-core';
12
+ import { MetaAdsClient } from './MetaAdsClient.js';
13
+ export declare const META_CREDENTIAL_TYPE = "Meta Ads";
14
+ export interface MetaExecutionReady {
15
+ ok: true;
16
+ client: MetaAdsClient;
17
+ brandConnectionId: string;
18
+ /** `act_<digits>`. */
19
+ adAccountId: string;
20
+ /** The Facebook Page the ads are published from (digits). */
21
+ pageId: string;
22
+ /** The Meta Pixel on the brand's site — null when the credential carries none (website retargeting is refused then). */
23
+ pixelId: string | null;
24
+ /** How lock hands the objects to Meta: PAUSED (default) or ACTIVE. Settings → Connections. */
25
+ launchState: CampaignLaunchState;
26
+ }
27
+ export interface MetaExecutionRefused {
28
+ ok: false;
29
+ issues: DriverValidationIssue[];
30
+ }
31
+ export type MetaExecutionContext = MetaExecutionReady | MetaExecutionRefused;
32
+ /** Explicit guard — this package compiles without strict, where `!ctx.ok` does not narrow. */
33
+ export declare function isMetaRefused(ctx: MetaExecutionContext): ctx is MetaExecutionRefused;
34
+ /** Test seam: the driver takes a resolver function so its flows are testable without a DB. */
35
+ export type MetaContextResolver = (brandId: string, contextUser: UserInfo) => Promise<MetaExecutionContext>;
36
+ /** `act_123` or `123` → `act_123`; anything else → null. */
37
+ export declare function normalizeMetaAdAccountId(raw: string | null | undefined): string | null;
38
+ export declare function resolveMetaExecutionContext(brandId: string, contextUser: UserInfo): Promise<MetaExecutionContext>;
39
+ //# sourceMappingURL=metaAdsExecutionContext.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metaAdsExecutionContext.d.ts","sourceRoot":"","sources":["../../../src/programs/meta/metaAdsExecutionContext.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAW,KAAK,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAG9D,OAAO,EAAmC,KAAK,mBAAmB,EAAE,KAAK,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAEpI,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,eAAO,MAAM,oBAAoB,aAAa,CAAC;AAE/C,MAAM,WAAW,kBAAkB;IAC/B,EAAE,EAAE,IAAI,CAAC;IACT,MAAM,EAAE,aAAa,CAAC;IACtB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,sBAAsB;IACtB,WAAW,EAAE,MAAM,CAAC;IACpB,6DAA6D;IAC7D,MAAM,EAAE,MAAM,CAAC;IACf,wHAAwH;IACxH,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,8FAA8F;IAC9F,WAAW,EAAE,mBAAmB,CAAC;CACpC;AACD,MAAM,WAAW,oBAAoB;IACjC,EAAE,EAAE,KAAK,CAAC;IACV,MAAM,EAAE,qBAAqB,EAAE,CAAC;CACnC;AACD,MAAM,MAAM,oBAAoB,GAAG,kBAAkB,GAAG,oBAAoB,CAAC;AAE7E,8FAA8F;AAC9F,wBAAgB,aAAa,CAAC,GAAG,EAAE,oBAAoB,GAAG,GAAG,IAAI,oBAAoB,CAEpF;AAED,8FAA8F;AAC9F,MAAM,MAAM,mBAAmB,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,KAAK,OAAO,CAAC,oBAAoB,CAAC,CAAC;AAE5G,4DAA4D;AAC5D,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,GAAG,IAAI,CAItF;AAED,wBAAsB,2BAA2B,CAC7C,OAAO,EAAE,MAAM,EACf,WAAW,EAAE,QAAQ,GACtB,OAAO,CAAC,oBAAoB,CAAC,CAyE/B"}
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Meta Ads execution context (D-27): from a brand to a ready API client — or an HONEST list of what's missing, in
3
+ * Settings → Connections vocabulary. The Meta twin of `googleAdsExecutionContext`.
4
+ *
5
+ * Chain: BrandConnection (brand × 'Meta Ads' credential type) → CredentialEngine (decrypted appSecret / accessToken,
6
+ * optional pixelId — the ONLY place secrets are resolved; they go straight into the client instance and nowhere
7
+ * else) → ExternalAccountID (the ad account, `act_<digits>` or bare digits) → the Facebook Page on the connection's
8
+ * configuration (`meta.pageId`), which every creative is published from.
9
+ */
10
+ import { RunView } from '@memberjunction/core';
11
+ import { EscapeSQLString, UUIDsEqual } from '@memberjunction/global';
12
+ import { CredentialEngine } from '@memberjunction/credentials';
13
+ import { campaignLaunchState, metaPageId } from '@mj-biz-apps/marketing-core';
14
+ import { MetaAdsClient } from './MetaAdsClient.js';
15
+ export const META_CREDENTIAL_TYPE = 'Meta Ads';
16
+ /** Explicit guard — this package compiles without strict, where `!ctx.ok` does not narrow. */
17
+ export function isMetaRefused(ctx) {
18
+ return !ctx.ok;
19
+ }
20
+ /** `act_123` or `123` → `act_123`; anything else → null. */
21
+ export function normalizeMetaAdAccountId(raw) {
22
+ const trimmed = (raw ?? '').trim();
23
+ const m = /^(?:act_)?(\d+)$/.exec(trimmed);
24
+ return m ? `act_${m[1]}` : null;
25
+ }
26
+ export async function resolveMetaExecutionContext(brandId, contextUser) {
27
+ const issues = [];
28
+ const engine = CredentialEngine.Instance;
29
+ await engine.Config(false, contextUser);
30
+ const credType = engine.getCredentialTypeByName(META_CREDENTIAL_TYPE);
31
+ if (!credType) {
32
+ return refusal([{
33
+ severity: 'error', code: 'MA_TYPE_NOT_INSTALLED',
34
+ message: `The '${META_CREDENTIAL_TYPE}' credential type is not installed — the app's metadata seed provides it.`,
35
+ }]);
36
+ }
37
+ const res = await new RunView().RunView({
38
+ EntityName: 'MJ_BizApps_Marketing: Brand Connections',
39
+ ExtraFilter: `BrandID='${EscapeSQLString(brandId)}'`,
40
+ ResultType: 'entity_object',
41
+ BypassCache: true,
42
+ }, contextUser);
43
+ const connection = (res.Success ? res.Results ?? [] : [])
44
+ .find(c => UUIDsEqual(c.CredentialTypeID, credType.ID));
45
+ if (!connection || !connection.CredentialID) {
46
+ return refusal([{
47
+ severity: 'error', code: 'MA_NOT_CONNECTED',
48
+ message: 'Meta Ads is not connected for this brand — connect it in Settings → Connections (a Business Manager system-user token with ads_management on the ad account).',
49
+ }]);
50
+ }
51
+ const credential = engine.getCredentialById(connection.CredentialID);
52
+ if (!credential || !credential.IsActive) {
53
+ return refusal([{
54
+ severity: 'error', code: 'MA_CREDENTIAL_INACTIVE',
55
+ message: 'The Meta Ads credential is disconnected (parked) — Reconnect it in Settings → Connections.',
56
+ }]);
57
+ }
58
+ const adAccountId = normalizeMetaAdAccountId(connection.ExternalAccountID);
59
+ if (!adAccountId) {
60
+ issues.push({
61
+ severity: 'error', code: 'MA_NO_AD_ACCOUNT',
62
+ message: 'The Meta Ads connection needs the ad account id (digits, with or without the act_ prefix) as its account id — add it in Settings → Connections.',
63
+ });
64
+ }
65
+ const pageId = metaPageId(connection.ConfigurationJSON);
66
+ if (!pageId) {
67
+ issues.push({
68
+ severity: 'error', code: 'MA_NO_PAGE',
69
+ message: 'The Meta Ads connection needs the Facebook Page the ads are published from — set it in Settings → Connections (the Page\'s numeric id).',
70
+ });
71
+ }
72
+ const resolved = await engine.getCredential(credential.Name, {
73
+ credentialId: connection.CredentialID,
74
+ contextUser,
75
+ subsystem: 'MarketingMetaAds',
76
+ });
77
+ const { appSecret, accessToken, pixelId } = resolved.values;
78
+ if (!appSecret || !accessToken) {
79
+ issues.push({
80
+ severity: 'error', code: 'MA_CREDENTIAL_INCOMPLETE',
81
+ message: 'The stored Meta Ads credential is missing appSecret/accessToken — Rotate it in Settings → Connections.',
82
+ });
83
+ }
84
+ if (issues.length > 0 || !adAccountId || !pageId)
85
+ return refusal(issues);
86
+ return {
87
+ ok: true,
88
+ client: new MetaAdsClient({ appSecret, accessToken, adAccountId }),
89
+ brandConnectionId: connection.ID,
90
+ adAccountId,
91
+ pageId,
92
+ pixelId: pixelId && /^\d+$/.test(pixelId.trim()) ? pixelId.trim() : null,
93
+ launchState: campaignLaunchState(connection.ConfigurationJSON),
94
+ };
95
+ }
96
+ function refusal(issues) {
97
+ return { ok: false, issues };
98
+ }
99
+ //# sourceMappingURL=metaAdsExecutionContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metaAdsExecutionContext.js","sourceRoot":"","sources":["../../../src/programs/meta/metaAdsExecutionContext.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,OAAO,EAAiB,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACrE,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAAE,UAAU,EAAwD,MAAM,6BAA6B,CAAC;AAEpI,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,MAAM,CAAC,MAAM,oBAAoB,GAAG,UAAU,CAAC;AAqB/C,8FAA8F;AAC9F,MAAM,UAAU,aAAa,CAAC,GAAyB;IACnD,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;AACnB,CAAC;AAKD,4DAA4D;AAC5D,MAAM,UAAU,wBAAwB,CAAC,GAA8B;IACnE,MAAM,OAAO,GAAG,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACnC,MAAM,CAAC,GAAG,kBAAkB,CAAC,IAAI,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