@adport/provider-meta 0.1.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Yannick Westermann
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,80 @@
1
+ import { AdProvider, ProviderCapabilities, Account, NormalizedQuery, Report, WriteOperation, WriteGuard, WritePreview, WriteResult, AnyToolDefinition, CredentialStore, ProviderModule } from '@adport/core';
2
+
3
+ interface MetaCredentials {
4
+ /** Long-lived user token or (preferred) a system-user token. */
5
+ accessToken: string;
6
+ /** Optional app id+secret — enables token expiry checks via /debug_token. */
7
+ appId?: string;
8
+ appSecret?: string;
9
+ }
10
+ declare const DEFAULT_GRAPH_VERSION = "v26.0";
11
+ /** Ad account ids are numeric; Graph URL paths require the "act_" prefix. */
12
+ declare function normalizeAccountId(id: string): string;
13
+ /** Account status codes per the Ad Account reference. */
14
+ declare const ACCOUNT_STATUS: Record<number, string>;
15
+ /**
16
+ * Minimal Graph API client for the Marketing API. Bearer-token auth; GET with
17
+ * query params, POST as form-encoded fields (arrays/objects JSON-stringified,
18
+ * matching the documented curl examples).
19
+ */
20
+ declare class MetaGraphClient {
21
+ private readonly credentials;
22
+ private readonly version;
23
+ private readonly fetchImpl;
24
+ constructor(credentials: MetaCredentials, version?: string, fetchImpl?: typeof fetch);
25
+ get<T>(path: string, params?: Record<string, string>): Promise<T>;
26
+ post<T>(path: string, fields: Record<string, unknown>): Promise<T>;
27
+ private send;
28
+ /** Paged GET over an edge, following paging.next up to maxItems. */
29
+ getPaged<T>(path: string, params: Record<string, string>, maxItems: number): Promise<T[]>;
30
+ /** Token health via /debug_token; needs appId+appSecret (app access token). */
31
+ debugToken(): Promise<{
32
+ isValid: boolean;
33
+ expiresAt?: number;
34
+ scopes?: string[];
35
+ } | undefined>;
36
+ }
37
+ /** Graph error shape: error.{message,type,code,error_subcode,error_user_msg,fbtrace_id}. */
38
+ declare function formatMetaError(status: number, raw: string): string;
39
+
40
+ /** Meta budgets are minor currency units (cents); the policy engine speaks micros. */
41
+ declare const CENTS_TO_MICROS = 10000;
42
+ declare class MetaAdsProvider implements AdProvider {
43
+ private readonly client;
44
+ readonly id = "meta";
45
+ constructor(client: MetaGraphClient);
46
+ capabilities(): ProviderCapabilities;
47
+ listAccounts(): Promise<Account[]>;
48
+ report(query: NormalizedQuery): Promise<Report>;
49
+ private toReportRow;
50
+ insights(input: {
51
+ account_id: string;
52
+ level: 'account' | 'campaign' | 'adset' | 'ad';
53
+ fields: string[];
54
+ date_preset?: string;
55
+ time_range?: {
56
+ since: string;
57
+ until: string;
58
+ };
59
+ breakdowns?: string[];
60
+ limit?: number;
61
+ }): Promise<Array<Record<string, unknown>>>;
62
+ previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview>;
63
+ applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult>;
64
+ private plan;
65
+ private withExecutionOptions;
66
+ private planCreateCampaign;
67
+ private planSetStatus;
68
+ /** Works for both campaigns (CBO) and ad sets — daily_budget lives on either. */
69
+ private planSetBudget;
70
+ private planCreateAdSet;
71
+ }
72
+
73
+ declare function metaTools(provider: MetaAdsProvider): AnyToolDefinition[];
74
+
75
+ /** Credential store record first, then META_ACCESS_TOKEN env fallback. */
76
+ declare function resolveMetaCredentials(store: CredentialStore): Promise<MetaCredentials | undefined>;
77
+ /** Provider module for createContext(); undefined when Meta isn't connected. */
78
+ declare function createMetaModule(store: CredentialStore): Promise<ProviderModule | undefined>;
79
+
80
+ export { ACCOUNT_STATUS, CENTS_TO_MICROS, DEFAULT_GRAPH_VERSION, MetaAdsProvider, type MetaCredentials, MetaGraphClient, createMetaModule, formatMetaError, metaTools, normalizeAccountId, resolveMetaCredentials };
package/dist/index.js ADDED
@@ -0,0 +1,535 @@
1
+ // src/client.ts
2
+ import { AdportError } from "@adport/core";
3
+ var GRAPH_BASE = "https://graph.facebook.com";
4
+ var DEFAULT_GRAPH_VERSION = "v26.0";
5
+ function normalizeAccountId(id) {
6
+ const normalized = id.replace(/^act_/, "").trim();
7
+ if (!/^\d+$/.test(normalized)) {
8
+ throw new AdportError("INVALID_INPUT", `"${id}" is not a valid Meta ad account id (numeric, with or without act_).`);
9
+ }
10
+ return normalized;
11
+ }
12
+ var ACCOUNT_STATUS = {
13
+ 1: "ACTIVE",
14
+ 2: "DISABLED",
15
+ 3: "UNSETTLED",
16
+ 7: "PENDING_RISK_REVIEW",
17
+ 8: "PENDING_SETTLEMENT",
18
+ 9: "IN_GRACE_PERIOD",
19
+ 100: "PENDING_CLOSURE",
20
+ 101: "CLOSED"
21
+ };
22
+ var MetaGraphClient = class {
23
+ constructor(credentials, version = process.env.META_API_VERSION ?? DEFAULT_GRAPH_VERSION, fetchImpl = fetch) {
24
+ this.credentials = credentials;
25
+ this.version = version;
26
+ this.fetchImpl = fetchImpl;
27
+ }
28
+ credentials;
29
+ version;
30
+ fetchImpl;
31
+ async get(path, params = {}) {
32
+ const search = new URLSearchParams(params);
33
+ const query = search.size > 0 ? `?${search}` : "";
34
+ return this.send(`${path}${query}`, { method: "GET" });
35
+ }
36
+ async post(path, fields) {
37
+ const body = new URLSearchParams();
38
+ for (const [key, value] of Object.entries(fields)) {
39
+ if (value === void 0) continue;
40
+ body.set(key, typeof value === "object" ? JSON.stringify(value) : String(value));
41
+ }
42
+ return this.send(path, { method: "POST", body });
43
+ }
44
+ async send(path, init) {
45
+ const response = await this.fetchImpl(`${GRAPH_BASE}/${this.version}/${path}`, {
46
+ method: init.method,
47
+ headers: {
48
+ authorization: `Bearer ${this.credentials.accessToken}`,
49
+ ...init.body ? { "content-type": "application/x-www-form-urlencoded" } : {}
50
+ },
51
+ body: init.body
52
+ });
53
+ const raw = await response.text();
54
+ if (!response.ok) {
55
+ throw new AdportError("PROVIDER_ERROR", formatMetaError(response.status, raw), safeJson(raw));
56
+ }
57
+ return raw ? JSON.parse(raw) : {};
58
+ }
59
+ /** Paged GET over an edge, following paging.next up to maxItems. */
60
+ async getPaged(path, params, maxItems) {
61
+ const items = [];
62
+ let url;
63
+ let first = true;
64
+ while (items.length < maxItems) {
65
+ let data;
66
+ if (first) {
67
+ data = await this.get(path, params);
68
+ first = false;
69
+ } else if (url) {
70
+ const response = await this.fetchImpl(url, {
71
+ headers: { authorization: `Bearer ${this.credentials.accessToken}` }
72
+ });
73
+ const raw = await response.text();
74
+ if (!response.ok) {
75
+ throw new AdportError("PROVIDER_ERROR", formatMetaError(response.status, raw), safeJson(raw));
76
+ }
77
+ data = JSON.parse(raw);
78
+ } else {
79
+ break;
80
+ }
81
+ items.push(...data.data ?? []);
82
+ url = data.paging?.next;
83
+ if (!url) break;
84
+ }
85
+ return items.slice(0, maxItems);
86
+ }
87
+ /** Token health via /debug_token; needs appId+appSecret (app access token). */
88
+ async debugToken() {
89
+ if (!this.credentials.appId || !this.credentials.appSecret) return void 0;
90
+ const data = await this.get(
91
+ "debug_token",
92
+ {
93
+ input_token: this.credentials.accessToken,
94
+ access_token: `${this.credentials.appId}|${this.credentials.appSecret}`
95
+ }
96
+ );
97
+ return data.data ? { isValid: data.data.is_valid ?? false, expiresAt: data.data.expires_at, scopes: data.data.scopes } : void 0;
98
+ }
99
+ };
100
+ function safeJson(raw) {
101
+ try {
102
+ return JSON.parse(raw);
103
+ } catch {
104
+ return raw;
105
+ }
106
+ }
107
+ function formatMetaError(status, raw) {
108
+ const parsed = safeJson(raw);
109
+ const error = parsed?.error;
110
+ if (!error) return `Meta Marketing API error (HTTP ${status})`;
111
+ const parts = [`Meta Marketing API error (HTTP ${status}, code ${error.code ?? "?"}`];
112
+ if (error.error_subcode) parts.push(`subcode ${error.error_subcode}`);
113
+ let message = `${parts.join(", ")}): ${error.message ?? "request failed"}`;
114
+ if (error.error_user_msg) message += `
115
+ ${error.error_user_title ? `${error.error_user_title}: ` : ""}${error.error_user_msg}`;
116
+ if (error.code === 190) message += "\n The access token is invalid or expired \u2014 re-run `adport connect meta`.";
117
+ if (error.fbtrace_id) message += ` [fbtrace_id: ${error.fbtrace_id}]`;
118
+ return message;
119
+ }
120
+
121
+ // src/provider.ts
122
+ import {
123
+ AdportError as AdportError2,
124
+ resolveDateRange
125
+ } from "@adport/core";
126
+ var CENTS_TO_MICROS = 1e4;
127
+ var INSIGHTS_LEVEL = {
128
+ account: "account",
129
+ campaign: "campaign",
130
+ ad_group: "adset",
131
+ ad: "ad"
132
+ };
133
+ var MetaAdsProvider = class {
134
+ constructor(client) {
135
+ this.client = client;
136
+ }
137
+ client;
138
+ id = "meta";
139
+ capabilities() {
140
+ return { serverDryRun: true };
141
+ }
142
+ async listAccounts() {
143
+ const rows = await this.client.getPaged("me/adaccounts", { fields: "account_id,name,currency,account_status", limit: "100" }, 500);
144
+ return rows.map((row) => ({
145
+ provider: this.id,
146
+ id: row.account_id ?? "",
147
+ name: row.name ?? `(account ${row.account_id})`,
148
+ currency: row.currency,
149
+ status: row.account_status !== void 0 ? ACCOUNT_STATUS[row.account_status] ?? String(row.account_status) : void 0
150
+ }));
151
+ }
152
+ async report(query) {
153
+ const range = resolveDateRange(query.dateRange);
154
+ const level = INSIGHTS_LEVEL[query.level];
155
+ const accountIds = query.accountIds ?? (await this.listAccounts()).map((a) => a.id);
156
+ const idFields = {
157
+ account: ["account_id"],
158
+ campaign: ["campaign_id", "campaign_name"],
159
+ adset: ["adset_id", "adset_name"],
160
+ ad: ["ad_id", "ad_name"]
161
+ }[level];
162
+ const fields = [...idFields, "spend", "impressions", "clicks", "actions", "action_values"].join(",");
163
+ const rows = [];
164
+ for (const accountId of accountIds) {
165
+ const act = normalizeAccountId(accountId);
166
+ const results = await this.client.getPaged(
167
+ `act_${act}/insights`,
168
+ {
169
+ level,
170
+ fields,
171
+ time_range: JSON.stringify({ since: range.start, until: range.end }),
172
+ limit: "100"
173
+ },
174
+ query.limit ?? 1e3
175
+ );
176
+ for (const row of results) {
177
+ rows.push(this.toReportRow(row, act, query));
178
+ }
179
+ }
180
+ return { rows };
181
+ }
182
+ toReportRow(row, accountId, query) {
183
+ const spend = Number(row.spend ?? 0);
184
+ const impressions = Number(row.impressions ?? 0);
185
+ const clicks = Number(row.clicks ?? 0);
186
+ const conversions = actionValue(row.actions, "omni_purchase");
187
+ const conversionValue = actionValue(row.action_values, "omni_purchase");
188
+ const all = {
189
+ spend: round2(spend),
190
+ impressions,
191
+ clicks,
192
+ conversions,
193
+ conversion_value: round2(conversionValue),
194
+ ctr: impressions > 0 ? round2(clicks / impressions * 100) : 0,
195
+ cpc: clicks > 0 ? round2(spend / clicks) : 0,
196
+ cpm: impressions > 0 ? round2(spend / impressions * 1e3) : 0,
197
+ cpa: conversions > 0 ? round2(spend / conversions) : 0,
198
+ roas: spend > 0 ? round2(conversionValue / spend) : 0
199
+ };
200
+ const entity = query.level === "account" ? { level: "account", id: accountId, name: accountId } : query.level === "campaign" ? { level: "campaign", id: row.campaign_id ?? "", name: row.campaign_name ?? "" } : query.level === "ad_group" ? { level: "ad_group", id: row.adset_id ?? "", name: row.adset_name ?? "" } : { level: "ad", id: row.ad_id ?? "", name: row.ad_name ?? `ad ${row.ad_id ?? "?"}` };
201
+ return {
202
+ provider: this.id,
203
+ accountId,
204
+ entity,
205
+ metrics: Object.fromEntries(query.metrics.map((m) => [m, all[m]]))
206
+ };
207
+ }
208
+ async insights(input) {
209
+ const act = normalizeAccountId(input.account_id);
210
+ const params = {
211
+ level: input.level,
212
+ fields: input.fields.join(","),
213
+ limit: "100"
214
+ };
215
+ if (input.time_range) params.time_range = JSON.stringify(input.time_range);
216
+ else params.date_preset = input.date_preset ?? "last_30d";
217
+ if (input.breakdowns?.length) params.breakdowns = input.breakdowns.join(",");
218
+ return this.client.getPaged(`act_${act}/insights`, params, Math.min(input.limit ?? 200, 5e3));
219
+ }
220
+ async previewWrite(op, guard) {
221
+ const plan = await this.plan(op, guard);
222
+ await plan.execute(true);
223
+ return {
224
+ summary: plan.summary,
225
+ changes: plan.changes,
226
+ coercions: plan.coercions,
227
+ budgetDeltas: plan.budgetDeltas,
228
+ serverValidated: true
229
+ };
230
+ }
231
+ async applyWrite(op, guard) {
232
+ const plan = await this.plan(op, guard);
233
+ const resourceIds = await plan.execute(false);
234
+ return { applied: true, resourceIds };
235
+ }
236
+ // ---- write planning ------------------------------------------------------
237
+ async plan(op, guard) {
238
+ const act = normalizeAccountId(op.accountId);
239
+ const payload = op.payload;
240
+ switch (op.tool) {
241
+ case "meta_create_campaign":
242
+ return this.planCreateCampaign(act, payload, guard);
243
+ case "meta_set_campaign_status":
244
+ return this.planSetStatus(payload, "campaign");
245
+ case "meta_set_budget":
246
+ return this.planSetBudget(payload);
247
+ case "meta_create_ad_set":
248
+ return this.planCreateAdSet(act, payload, guard);
249
+ case "meta_set_ad_set_status":
250
+ return this.planSetStatus(payload, "ad set");
251
+ default:
252
+ throw new AdportError2("PROVIDER_ERROR", `meta: unsupported write tool ${op.tool}`);
253
+ }
254
+ }
255
+ withExecutionOptions(fields, validateOnly) {
256
+ return validateOnly ? { ...fields, execution_options: ["validate_only"] } : fields;
257
+ }
258
+ async planCreateCampaign(act, payload, guard) {
259
+ const coercions = [];
260
+ let status = payload.status ?? "ACTIVE";
261
+ if (guard.forcePausedCreation && status === "ACTIVE") {
262
+ status = "PAUSED";
263
+ coercions.push("status coerced to PAUSED by policy (paused_creation)");
264
+ }
265
+ const fields = {
266
+ name: payload.name,
267
+ objective: payload.objective,
268
+ status,
269
+ // Required by the API even when empty.
270
+ special_ad_categories: payload.special_ad_categories ?? []
271
+ };
272
+ const budgetDeltas = [];
273
+ const changes = [`+ campaign "${payload.name}" objective=${payload.objective} status=${status}`];
274
+ if (payload.daily_budget_cents) {
275
+ fields.daily_budget = payload.daily_budget_cents;
276
+ changes.push(`+ campaign-level (Advantage/CBO) daily budget ${payload.daily_budget_cents} minor units`);
277
+ budgetDeltas.push({
278
+ target: `new campaign "${payload.name}" daily budget`,
279
+ toMicros: payload.daily_budget_cents * CENTS_TO_MICROS
280
+ });
281
+ }
282
+ return {
283
+ summary: `Create Meta campaign "${payload.name}" (${payload.objective}, ${status})`,
284
+ changes,
285
+ coercions,
286
+ budgetDeltas,
287
+ execute: async (validateOnly) => {
288
+ const res = await this.client.post(
289
+ `act_${act}/campaigns`,
290
+ this.withExecutionOptions(fields, validateOnly)
291
+ );
292
+ return res.id ? [res.id] : [];
293
+ }
294
+ };
295
+ }
296
+ async planSetStatus(payload, kind) {
297
+ const objectId = payload.campaign_id ?? payload.ad_set_id ?? payload.object_id;
298
+ if (!objectId) throw new AdportError2("INVALID_INPUT", `meta: missing id for ${kind} status change`);
299
+ const current = await this.client.get(objectId, {
300
+ fields: "name,status"
301
+ });
302
+ return {
303
+ summary: `Set ${kind} "${current.name ?? objectId}" status ${current.status ?? "?"} \u2192 ${payload.status}`,
304
+ changes: [`~ ${kind} ${objectId} status ${current.status ?? "?"} \u2192 ${payload.status}`],
305
+ coercions: [],
306
+ budgetDeltas: [],
307
+ execute: async (validateOnly) => {
308
+ await this.client.post(
309
+ objectId,
310
+ this.withExecutionOptions({ status: payload.status }, validateOnly)
311
+ );
312
+ return [objectId];
313
+ }
314
+ };
315
+ }
316
+ /** Works for both campaigns (CBO) and ad sets — daily_budget lives on either. */
317
+ async planSetBudget(payload) {
318
+ const current = await this.client.get(payload.object_id, {
319
+ fields: "name,daily_budget"
320
+ });
321
+ const fromCents = current.daily_budget !== void 0 ? Number(current.daily_budget) : void 0;
322
+ if (fromCents === void 0) {
323
+ throw new AdportError2(
324
+ "PROVIDER_ERROR",
325
+ `meta: object ${payload.object_id} ("${current.name ?? "?"}") has no daily_budget \u2014 the budget may live on the other level (campaign vs ad set) or be a lifetime budget.`
326
+ );
327
+ }
328
+ return {
329
+ summary: `Change "${current.name ?? payload.object_id}" daily budget ${fromCents} \u2192 ${payload.daily_budget_cents} minor units`,
330
+ changes: [`~ ${payload.object_id} daily_budget ${fromCents} \u2192 ${payload.daily_budget_cents}`],
331
+ coercions: [],
332
+ budgetDeltas: [
333
+ {
334
+ target: `"${current.name ?? payload.object_id}" daily budget`,
335
+ fromMicros: fromCents * CENTS_TO_MICROS,
336
+ toMicros: payload.daily_budget_cents * CENTS_TO_MICROS
337
+ }
338
+ ],
339
+ execute: async (validateOnly) => {
340
+ await this.client.post(
341
+ payload.object_id,
342
+ this.withExecutionOptions({ daily_budget: payload.daily_budget_cents }, validateOnly)
343
+ );
344
+ return [payload.object_id];
345
+ }
346
+ };
347
+ }
348
+ async planCreateAdSet(act, payload, guard) {
349
+ const coercions = [];
350
+ let status = payload.status ?? "ACTIVE";
351
+ if (guard.forcePausedCreation && status === "ACTIVE") {
352
+ status = "PAUSED";
353
+ coercions.push("status coerced to PAUSED by policy (paused_creation)");
354
+ }
355
+ const fields = {
356
+ name: payload.name,
357
+ campaign_id: payload.campaign_id,
358
+ optimization_goal: payload.optimization_goal ?? "LINK_CLICKS",
359
+ billing_event: payload.billing_event ?? "IMPRESSIONS",
360
+ targeting: { geo_locations: { countries: payload.countries } },
361
+ status
362
+ };
363
+ const budgetDeltas = [];
364
+ if (payload.daily_budget_cents) {
365
+ fields.daily_budget = payload.daily_budget_cents;
366
+ budgetDeltas.push({
367
+ target: `new ad set "${payload.name}" daily budget`,
368
+ toMicros: payload.daily_budget_cents * CENTS_TO_MICROS
369
+ });
370
+ }
371
+ return {
372
+ summary: `Create ad set "${payload.name}" in campaign ${payload.campaign_id} (${status})`,
373
+ changes: [
374
+ `+ ad_set "${payload.name}" targeting countries=[${payload.countries.join(", ")}] goal=${fields.optimization_goal} billing=${fields.billing_event} status=${status}` + (payload.daily_budget_cents ? ` daily_budget=${payload.daily_budget_cents}` : " (budget on campaign/CBO)")
375
+ ],
376
+ coercions,
377
+ budgetDeltas,
378
+ execute: async (validateOnly) => {
379
+ const res = await this.client.post(
380
+ `act_${act}/adsets`,
381
+ this.withExecutionOptions(fields, validateOnly)
382
+ );
383
+ return res.id ? [res.id] : [];
384
+ }
385
+ };
386
+ }
387
+ };
388
+ function actionValue(stats, actionType) {
389
+ const stat = stats?.find((s) => s.action_type === actionType);
390
+ return stat ? Number(stat.value) : 0;
391
+ }
392
+ function round2(n) {
393
+ return Math.round(n * 100) / 100;
394
+ }
395
+
396
+ // src/tools.ts
397
+ import { defineTool, guardedWriteTool } from "@adport/core";
398
+ import { z } from "zod";
399
+ var statusSchema = z.enum(["ACTIVE", "PAUSED"]);
400
+ var objectiveSchema = z.enum([
401
+ "OUTCOME_APP_PROMOTION",
402
+ "OUTCOME_AWARENESS",
403
+ "OUTCOME_ENGAGEMENT",
404
+ "OUTCOME_LEADS",
405
+ "OUTCOME_SALES",
406
+ "OUTCOME_TRAFFIC"
407
+ ]);
408
+ var specialAdCategorySchema = z.enum([
409
+ "NONE",
410
+ "EMPLOYMENT",
411
+ "HOUSING",
412
+ "CREDIT",
413
+ "ISSUES_ELECTIONS_POLITICS",
414
+ "ONLINE_GAMBLING_AND_GAMING",
415
+ "FINANCIAL_PRODUCTS_SERVICES"
416
+ ]);
417
+ function metaTools(provider) {
418
+ return [
419
+ defineTool({
420
+ name: "meta_insights",
421
+ namespace: "meta",
422
+ description: "Query the Meta Ads Insights API directly: pick a level (account/campaign/adset/ad), fields (spend, impressions, clicks, actions, action_values, purchase_roas, campaign_name, ...), and a date_preset (last_7d, last_30d, maximum, ...) or explicit time_range. Values come back as strings; spend is whole currency units.",
423
+ input: z.object({
424
+ account_id: z.string().describe("Numeric ad account id, act_ prefix optional"),
425
+ level: z.enum(["account", "campaign", "adset", "ad"]).default("campaign"),
426
+ fields: z.array(z.string()).min(1).default(["campaign_id", "campaign_name", "spend", "impressions", "clicks"]),
427
+ date_preset: z.string().optional(),
428
+ time_range: z.object({ since: z.string(), until: z.string() }).optional(),
429
+ breakdowns: z.array(z.string()).optional(),
430
+ limit: z.number().int().positive().max(5e3).default(200)
431
+ }),
432
+ annotations: { readOnly: true },
433
+ async handler(input) {
434
+ const rows = await provider.insights(input);
435
+ return { rows, row_count: rows.length };
436
+ }
437
+ }),
438
+ guardedWriteTool({
439
+ name: "meta_create_campaign",
440
+ namespace: "meta",
441
+ description: "Create a Meta campaign. Budget is optional at campaign level (Advantage/CBO) \u2014 otherwise set it on ad sets. special_ad_categories is required by Meta for regulated verticals; defaults to none.",
442
+ provider: "meta",
443
+ kind: "create",
444
+ payload: z.object({
445
+ name: z.string().min(1),
446
+ objective: objectiveSchema.default("OUTCOME_TRAFFIC"),
447
+ status: statusSchema.optional(),
448
+ special_ad_categories: z.array(specialAdCategorySchema).default([]),
449
+ daily_budget_cents: z.number().int().positive().optional().describe("Minor currency units (cents for EUR/USD) \u2014 campaign-level CBO budget")
450
+ })
451
+ }),
452
+ guardedWriteTool({
453
+ name: "meta_set_campaign_status",
454
+ namespace: "meta",
455
+ description: "Activate or pause a Meta campaign.",
456
+ provider: "meta",
457
+ kind: "update",
458
+ payload: z.object({ campaign_id: z.string(), status: statusSchema })
459
+ }),
460
+ guardedWriteTool({
461
+ name: "meta_set_budget",
462
+ namespace: "meta",
463
+ description: "Change the daily budget of a Meta campaign (CBO) or ad set \u2014 pass the object id that owns the budget. The preview shows the current value and fails clearly when the object has no daily budget.",
464
+ provider: "meta",
465
+ kind: "update",
466
+ payload: z.object({
467
+ object_id: z.string().describe("Campaign id (CBO) or ad set id that owns the daily budget"),
468
+ daily_budget_cents: z.number().int().positive().describe("Minor currency units (cents for EUR/USD)")
469
+ })
470
+ }),
471
+ guardedWriteTool({
472
+ name: "meta_create_ad_set",
473
+ namespace: "meta",
474
+ description: "Create an ad set in a campaign with minimal country targeting. Omit daily_budget_cents when the campaign uses CBO. Defaults: LINK_CLICKS optimization, IMPRESSIONS billing.",
475
+ provider: "meta",
476
+ kind: "create",
477
+ payload: z.object({
478
+ campaign_id: z.string(),
479
+ name: z.string().min(1),
480
+ countries: z.array(z.string().length(2)).min(1).describe("ISO country codes for geo targeting"),
481
+ daily_budget_cents: z.number().int().positive().optional(),
482
+ optimization_goal: z.string().optional(),
483
+ billing_event: z.string().optional(),
484
+ status: statusSchema.optional()
485
+ })
486
+ }),
487
+ guardedWriteTool({
488
+ name: "meta_set_ad_set_status",
489
+ namespace: "meta",
490
+ description: "Activate or pause a Meta ad set.",
491
+ provider: "meta",
492
+ kind: "update",
493
+ payload: z.object({ ad_set_id: z.string(), status: statusSchema })
494
+ })
495
+ ];
496
+ }
497
+
498
+ // src/index.ts
499
+ async function resolveMetaCredentials(store) {
500
+ const record = await store.get("meta");
501
+ if (record?.data.access_token) {
502
+ return {
503
+ accessToken: record.data.access_token,
504
+ appId: record.data.app_id || void 0,
505
+ appSecret: record.data.app_secret || void 0
506
+ };
507
+ }
508
+ if (process.env.META_ACCESS_TOKEN) {
509
+ return {
510
+ accessToken: process.env.META_ACCESS_TOKEN,
511
+ appId: process.env.META_APP_ID || void 0,
512
+ appSecret: process.env.META_APP_SECRET || void 0
513
+ };
514
+ }
515
+ return void 0;
516
+ }
517
+ async function createMetaModule(store) {
518
+ const credentials = await resolveMetaCredentials(store);
519
+ if (!credentials) return void 0;
520
+ const provider = new MetaAdsProvider(new MetaGraphClient(credentials));
521
+ return { provider, tools: metaTools(provider) };
522
+ }
523
+ export {
524
+ ACCOUNT_STATUS,
525
+ CENTS_TO_MICROS,
526
+ DEFAULT_GRAPH_VERSION,
527
+ MetaAdsProvider,
528
+ MetaGraphClient,
529
+ createMetaModule,
530
+ formatMetaError,
531
+ metaTools,
532
+ normalizeAccountId,
533
+ resolveMetaCredentials
534
+ };
535
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts","../src/provider.ts","../src/tools.ts","../src/index.ts"],"sourcesContent":["import { AdportError } from '@adport/core';\n\nexport interface MetaCredentials {\n /** Long-lived user token or (preferred) a system-user token. */\n accessToken: string;\n /** Optional app id+secret — enables token expiry checks via /debug_token. */\n appId?: string;\n appSecret?: string;\n}\n\nconst GRAPH_BASE = 'https://graph.facebook.com';\n// Latest Graph/Marketing API version as of 2026-08 (see docs/graph-api/changelog).\nexport const DEFAULT_GRAPH_VERSION = 'v26.0';\n\n/** Ad account ids are numeric; Graph URL paths require the \"act_\" prefix. */\nexport function normalizeAccountId(id: string): string {\n const normalized = id.replace(/^act_/, '').trim();\n if (!/^\\d+$/.test(normalized)) {\n throw new AdportError('INVALID_INPUT', `\"${id}\" is not a valid Meta ad account id (numeric, with or without act_).`);\n }\n return normalized;\n}\n\n/** Account status codes per the Ad Account reference. */\nexport const ACCOUNT_STATUS: Record<number, string> = {\n 1: 'ACTIVE',\n 2: 'DISABLED',\n 3: 'UNSETTLED',\n 7: 'PENDING_RISK_REVIEW',\n 8: 'PENDING_SETTLEMENT',\n 9: 'IN_GRACE_PERIOD',\n 100: 'PENDING_CLOSURE',\n 101: 'CLOSED',\n};\n\n/**\n * Minimal Graph API client for the Marketing API. Bearer-token auth; GET with\n * query params, POST as form-encoded fields (arrays/objects JSON-stringified,\n * matching the documented curl examples).\n */\nexport class MetaGraphClient {\n constructor(\n private readonly credentials: MetaCredentials,\n private readonly version: string = process.env.META_API_VERSION ?? DEFAULT_GRAPH_VERSION,\n private readonly fetchImpl: typeof fetch = fetch,\n ) {}\n\n async get<T>(path: string, params: Record<string, string> = {}): Promise<T> {\n const search = new URLSearchParams(params);\n const query = search.size > 0 ? `?${search}` : '';\n return this.send<T>(`${path}${query}`, { method: 'GET' });\n }\n\n async post<T>(path: string, fields: Record<string, unknown>): Promise<T> {\n const body = new URLSearchParams();\n for (const [key, value] of Object.entries(fields)) {\n if (value === undefined) continue;\n body.set(key, typeof value === 'object' ? JSON.stringify(value) : String(value));\n }\n return this.send<T>(path, { method: 'POST', body });\n }\n\n private async send<T>(path: string, init: { method: string; body?: URLSearchParams }): Promise<T> {\n const response = await this.fetchImpl(`${GRAPH_BASE}/${this.version}/${path}`, {\n method: init.method,\n headers: {\n authorization: `Bearer ${this.credentials.accessToken}`,\n ...(init.body ? { 'content-type': 'application/x-www-form-urlencoded' } : {}),\n },\n body: init.body,\n });\n const raw = await response.text();\n if (!response.ok) {\n throw new AdportError('PROVIDER_ERROR', formatMetaError(response.status, raw), safeJson(raw));\n }\n return (raw ? JSON.parse(raw) : {}) as T;\n }\n\n /** Paged GET over an edge, following paging.next up to maxItems. */\n async getPaged<T>(path: string, params: Record<string, string>, maxItems: number): Promise<T[]> {\n const items: T[] = [];\n let url: string | undefined;\n let first = true;\n while (items.length < maxItems) {\n let data: { data?: T[]; paging?: { next?: string } };\n if (first) {\n data = await this.get(path, params);\n first = false;\n } else if (url) {\n const response = await this.fetchImpl(url, {\n headers: { authorization: `Bearer ${this.credentials.accessToken}` },\n });\n const raw = await response.text();\n if (!response.ok) {\n throw new AdportError('PROVIDER_ERROR', formatMetaError(response.status, raw), safeJson(raw));\n }\n data = JSON.parse(raw) as { data?: T[]; paging?: { next?: string } };\n } else {\n break;\n }\n items.push(...(data.data ?? []));\n url = data.paging?.next;\n if (!url) break;\n }\n return items.slice(0, maxItems);\n }\n\n /** Token health via /debug_token; needs appId+appSecret (app access token). */\n async debugToken(): Promise<{ isValid: boolean; expiresAt?: number; scopes?: string[] } | undefined> {\n if (!this.credentials.appId || !this.credentials.appSecret) return undefined;\n const data = await this.get<{ data?: { is_valid?: boolean; expires_at?: number; scopes?: string[] } }>(\n 'debug_token',\n {\n input_token: this.credentials.accessToken,\n access_token: `${this.credentials.appId}|${this.credentials.appSecret}`,\n },\n );\n return data.data\n ? { isValid: data.data.is_valid ?? false, expiresAt: data.data.expires_at, scopes: data.data.scopes }\n : undefined;\n }\n}\n\nfunction safeJson(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return raw;\n }\n}\n\n/** Graph error shape: error.{message,type,code,error_subcode,error_user_msg,fbtrace_id}. */\nexport function formatMetaError(status: number, raw: string): string {\n const parsed = safeJson(raw) as {\n error?: {\n message?: string;\n type?: string;\n code?: number;\n error_subcode?: number;\n error_user_title?: string;\n error_user_msg?: string;\n fbtrace_id?: string;\n };\n };\n const error = parsed?.error;\n if (!error) return `Meta Marketing API error (HTTP ${status})`;\n const parts = [`Meta Marketing API error (HTTP ${status}, code ${error.code ?? '?'}`];\n if (error.error_subcode) parts.push(`subcode ${error.error_subcode}`);\n let message = `${parts.join(', ')}): ${error.message ?? 'request failed'}`;\n if (error.error_user_msg) message += `\\n ${error.error_user_title ? `${error.error_user_title}: ` : ''}${error.error_user_msg}`;\n if (error.code === 190) message += '\\n The access token is invalid or expired — re-run `adport connect meta`.';\n if (error.fbtrace_id) message += ` [fbtrace_id: ${error.fbtrace_id}]`;\n return message;\n}\n","import {\n AdportError,\n resolveDateRange,\n type Account,\n type AdProvider,\n type MetricName,\n type NormalizedQuery,\n type ProviderCapabilities,\n type Report,\n type ReportRow,\n type WriteGuard,\n type WriteOperation,\n type WritePreview,\n type WriteResult,\n} from '@adport/core';\nimport { ACCOUNT_STATUS, MetaGraphClient, normalizeAccountId } from './client.js';\n\n/** Meta budgets are minor currency units (cents); the policy engine speaks micros. */\nexport const CENTS_TO_MICROS = 10_000;\n\nconst INSIGHTS_LEVEL = {\n account: 'account',\n campaign: 'campaign',\n ad_group: 'adset',\n ad: 'ad',\n} as const;\n\ninterface ActionStat {\n action_type: string;\n value: string;\n}\n\ninterface InsightsRow {\n account_id?: string;\n campaign_id?: string;\n campaign_name?: string;\n adset_id?: string;\n adset_name?: string;\n ad_id?: string;\n ad_name?: string;\n spend?: string;\n impressions?: string;\n clicks?: string;\n actions?: ActionStat[];\n action_values?: ActionStat[];\n}\n\ninterface WritePlan {\n summary: string;\n changes: string[];\n coercions: string[];\n budgetDeltas: WritePreview['budgetDeltas'];\n execute: (validateOnly: boolean) => Promise<string[]>;\n}\n\nexport class MetaAdsProvider implements AdProvider {\n readonly id = 'meta';\n\n constructor(private readonly client: MetaGraphClient) {}\n\n capabilities(): ProviderCapabilities {\n return { serverDryRun: true };\n }\n\n async listAccounts(): Promise<Account[]> {\n const rows = await this.client.getPaged<{\n account_id?: string;\n name?: string;\n currency?: string;\n account_status?: number;\n }>('me/adaccounts', { fields: 'account_id,name,currency,account_status', limit: '100' }, 500);\n return rows.map((row) => ({\n provider: this.id,\n id: row.account_id ?? '',\n name: row.name ?? `(account ${row.account_id})`,\n currency: row.currency,\n status: row.account_status !== undefined ? (ACCOUNT_STATUS[row.account_status] ?? String(row.account_status)) : undefined,\n }));\n }\n\n async report(query: NormalizedQuery): Promise<Report> {\n const range = resolveDateRange(query.dateRange);\n const level = INSIGHTS_LEVEL[query.level];\n const accountIds = query.accountIds ?? (await this.listAccounts()).map((a) => a.id);\n\n const idFields = {\n account: ['account_id'],\n campaign: ['campaign_id', 'campaign_name'],\n adset: ['adset_id', 'adset_name'],\n ad: ['ad_id', 'ad_name'],\n }[level];\n const fields = [...idFields, 'spend', 'impressions', 'clicks', 'actions', 'action_values'].join(',');\n\n const rows: ReportRow[] = [];\n for (const accountId of accountIds) {\n const act = normalizeAccountId(accountId);\n const results = await this.client.getPaged<InsightsRow>(\n `act_${act}/insights`,\n {\n level,\n fields,\n time_range: JSON.stringify({ since: range.start, until: range.end }),\n limit: '100',\n },\n query.limit ?? 1000,\n );\n for (const row of results) {\n rows.push(this.toReportRow(row, act, query));\n }\n }\n return { rows };\n }\n\n private toReportRow(row: InsightsRow, accountId: string, query: NormalizedQuery): ReportRow {\n // Insights values are strings; spend is whole currency units (not cents).\n const spend = Number(row.spend ?? 0);\n const impressions = Number(row.impressions ?? 0);\n const clicks = Number(row.clicks ?? 0);\n // omni_purchase is Meta's canonical cross-channel purchase action.\n const conversions = actionValue(row.actions, 'omni_purchase');\n const conversionValue = actionValue(row.action_values, 'omni_purchase');\n const all: Record<MetricName, number> = {\n spend: round2(spend),\n impressions,\n clicks,\n conversions,\n conversion_value: round2(conversionValue),\n ctr: impressions > 0 ? round2((clicks / impressions) * 100) : 0,\n cpc: clicks > 0 ? round2(spend / clicks) : 0,\n cpm: impressions > 0 ? round2((spend / impressions) * 1000) : 0,\n cpa: conversions > 0 ? round2(spend / conversions) : 0,\n roas: spend > 0 ? round2(conversionValue / spend) : 0,\n };\n\n const entity: ReportRow['entity'] =\n query.level === 'account'\n ? { level: 'account', id: accountId, name: accountId }\n : query.level === 'campaign'\n ? { level: 'campaign', id: row.campaign_id ?? '', name: row.campaign_name ?? '' }\n : query.level === 'ad_group'\n ? { level: 'ad_group', id: row.adset_id ?? '', name: row.adset_name ?? '' }\n : { level: 'ad', id: row.ad_id ?? '', name: row.ad_name ?? `ad ${row.ad_id ?? '?'}` };\n\n return {\n provider: this.id,\n accountId,\n entity,\n metrics: Object.fromEntries(query.metrics.map((m) => [m, all[m]])),\n };\n }\n\n async insights(input: {\n account_id: string;\n level: 'account' | 'campaign' | 'adset' | 'ad';\n fields: string[];\n date_preset?: string;\n time_range?: { since: string; until: string };\n breakdowns?: string[];\n limit?: number;\n }): Promise<Array<Record<string, unknown>>> {\n const act = normalizeAccountId(input.account_id);\n const params: Record<string, string> = {\n level: input.level,\n fields: input.fields.join(','),\n limit: '100',\n };\n if (input.time_range) params.time_range = JSON.stringify(input.time_range);\n else params.date_preset = input.date_preset ?? 'last_30d';\n if (input.breakdowns?.length) params.breakdowns = input.breakdowns.join(',');\n return this.client.getPaged(`act_${act}/insights`, params, Math.min(input.limit ?? 200, 5000));\n }\n\n async previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview> {\n const plan = await this.plan(op, guard);\n await plan.execute(true); // execution_options=[\"validate_only\"] — server-side dry run\n return {\n summary: plan.summary,\n changes: plan.changes,\n coercions: plan.coercions,\n budgetDeltas: plan.budgetDeltas,\n serverValidated: true,\n };\n }\n\n async applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult> {\n const plan = await this.plan(op, guard);\n const resourceIds = await plan.execute(false);\n return { applied: true, resourceIds };\n }\n\n // ---- write planning ------------------------------------------------------\n\n private async plan(op: WriteOperation, guard: WriteGuard): Promise<WritePlan> {\n const act = normalizeAccountId(op.accountId);\n const payload = op.payload as never;\n switch (op.tool) {\n case 'meta_create_campaign':\n return this.planCreateCampaign(act, payload, guard);\n case 'meta_set_campaign_status':\n return this.planSetStatus(payload, 'campaign');\n case 'meta_set_budget':\n return this.planSetBudget(payload);\n case 'meta_create_ad_set':\n return this.planCreateAdSet(act, payload, guard);\n case 'meta_set_ad_set_status':\n return this.planSetStatus(payload, 'ad set');\n default:\n throw new AdportError('PROVIDER_ERROR', `meta: unsupported write tool ${op.tool}`);\n }\n }\n\n private withExecutionOptions(fields: Record<string, unknown>, validateOnly: boolean): Record<string, unknown> {\n return validateOnly ? { ...fields, execution_options: ['validate_only'] } : fields;\n }\n\n private async planCreateCampaign(\n act: string,\n payload: {\n name: string;\n objective: string;\n status?: string;\n special_ad_categories?: string[];\n daily_budget_cents?: number;\n },\n guard: WriteGuard,\n ): Promise<WritePlan> {\n const coercions: string[] = [];\n let status = payload.status ?? 'ACTIVE';\n if (guard.forcePausedCreation && status === 'ACTIVE') {\n status = 'PAUSED';\n coercions.push('status coerced to PAUSED by policy (paused_creation)');\n }\n const fields: Record<string, unknown> = {\n name: payload.name,\n objective: payload.objective,\n status,\n // Required by the API even when empty.\n special_ad_categories: payload.special_ad_categories ?? [],\n };\n const budgetDeltas: WritePreview['budgetDeltas'] = [];\n const changes = [`+ campaign \"${payload.name}\" objective=${payload.objective} status=${status}`];\n if (payload.daily_budget_cents) {\n fields.daily_budget = payload.daily_budget_cents;\n changes.push(`+ campaign-level (Advantage/CBO) daily budget ${payload.daily_budget_cents} minor units`);\n budgetDeltas.push({\n target: `new campaign \"${payload.name}\" daily budget`,\n toMicros: payload.daily_budget_cents * CENTS_TO_MICROS,\n });\n }\n return {\n summary: `Create Meta campaign \"${payload.name}\" (${payload.objective}, ${status})`,\n changes,\n coercions,\n budgetDeltas,\n execute: async (validateOnly) => {\n const res = await this.client.post<{ id?: string; success?: boolean }>(\n `act_${act}/campaigns`,\n this.withExecutionOptions(fields, validateOnly),\n );\n return res.id ? [res.id] : [];\n },\n };\n }\n\n private async planSetStatus(\n payload: { object_id?: string; campaign_id?: string; ad_set_id?: string; status: 'ACTIVE' | 'PAUSED' },\n kind: string,\n ): Promise<WritePlan> {\n const objectId = payload.campaign_id ?? payload.ad_set_id ?? payload.object_id;\n if (!objectId) throw new AdportError('INVALID_INPUT', `meta: missing id for ${kind} status change`);\n const current = await this.client.get<{ name?: string; status?: string }>(objectId, {\n fields: 'name,status',\n });\n return {\n summary: `Set ${kind} \"${current.name ?? objectId}\" status ${current.status ?? '?'} → ${payload.status}`,\n changes: [`~ ${kind} ${objectId} status ${current.status ?? '?'} → ${payload.status}`],\n coercions: [],\n budgetDeltas: [],\n execute: async (validateOnly) => {\n await this.client.post<{ success?: boolean }>(\n objectId,\n this.withExecutionOptions({ status: payload.status }, validateOnly),\n );\n return [objectId];\n },\n };\n }\n\n /** Works for both campaigns (CBO) and ad sets — daily_budget lives on either. */\n private async planSetBudget(payload: { object_id: string; daily_budget_cents: number }): Promise<WritePlan> {\n const current = await this.client.get<{ name?: string; daily_budget?: string }>(payload.object_id, {\n fields: 'name,daily_budget',\n });\n const fromCents = current.daily_budget !== undefined ? Number(current.daily_budget) : undefined;\n if (fromCents === undefined) {\n throw new AdportError(\n 'PROVIDER_ERROR',\n `meta: object ${payload.object_id} (\"${current.name ?? '?'}\") has no daily_budget — ` +\n 'the budget may live on the other level (campaign vs ad set) or be a lifetime budget.',\n );\n }\n return {\n summary: `Change \"${current.name ?? payload.object_id}\" daily budget ${fromCents} → ${payload.daily_budget_cents} minor units`,\n changes: [`~ ${payload.object_id} daily_budget ${fromCents} → ${payload.daily_budget_cents}`],\n coercions: [],\n budgetDeltas: [\n {\n target: `\"${current.name ?? payload.object_id}\" daily budget`,\n fromMicros: fromCents * CENTS_TO_MICROS,\n toMicros: payload.daily_budget_cents * CENTS_TO_MICROS,\n },\n ],\n execute: async (validateOnly) => {\n await this.client.post<{ success?: boolean }>(\n payload.object_id,\n this.withExecutionOptions({ daily_budget: payload.daily_budget_cents }, validateOnly),\n );\n return [payload.object_id];\n },\n };\n }\n\n private async planCreateAdSet(\n act: string,\n payload: {\n campaign_id: string;\n name: string;\n daily_budget_cents?: number;\n optimization_goal?: string;\n billing_event?: string;\n countries: string[];\n status?: string;\n },\n guard: WriteGuard,\n ): Promise<WritePlan> {\n const coercions: string[] = [];\n let status = payload.status ?? 'ACTIVE';\n if (guard.forcePausedCreation && status === 'ACTIVE') {\n status = 'PAUSED';\n coercions.push('status coerced to PAUSED by policy (paused_creation)');\n }\n const fields: Record<string, unknown> = {\n name: payload.name,\n campaign_id: payload.campaign_id,\n optimization_goal: payload.optimization_goal ?? 'LINK_CLICKS',\n billing_event: payload.billing_event ?? 'IMPRESSIONS',\n targeting: { geo_locations: { countries: payload.countries } },\n status,\n };\n const budgetDeltas: WritePreview['budgetDeltas'] = [];\n if (payload.daily_budget_cents) {\n fields.daily_budget = payload.daily_budget_cents;\n budgetDeltas.push({\n target: `new ad set \"${payload.name}\" daily budget`,\n toMicros: payload.daily_budget_cents * CENTS_TO_MICROS,\n });\n }\n return {\n summary: `Create ad set \"${payload.name}\" in campaign ${payload.campaign_id} (${status})`,\n changes: [\n `+ ad_set \"${payload.name}\" targeting countries=[${payload.countries.join(', ')}] ` +\n `goal=${fields.optimization_goal} billing=${fields.billing_event} status=${status}` +\n (payload.daily_budget_cents ? ` daily_budget=${payload.daily_budget_cents}` : ' (budget on campaign/CBO)'),\n ],\n coercions,\n budgetDeltas,\n execute: async (validateOnly) => {\n const res = await this.client.post<{ id?: string; success?: boolean }>(\n `act_${act}/adsets`,\n this.withExecutionOptions(fields, validateOnly),\n );\n return res.id ? [res.id] : [];\n },\n };\n }\n}\n\nfunction actionValue(stats: ActionStat[] | undefined, actionType: string): number {\n const stat = stats?.find((s) => s.action_type === actionType);\n return stat ? Number(stat.value) : 0;\n}\n\nfunction round2(n: number): number {\n return Math.round(n * 100) / 100;\n}\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { MetaAdsProvider } from './provider.js';\n\nconst statusSchema = z.enum(['ACTIVE', 'PAUSED']);\n\n// Current outcome-based objectives (legacy values exist but new campaigns should use these).\nconst objectiveSchema = z.enum([\n 'OUTCOME_APP_PROMOTION',\n 'OUTCOME_AWARENESS',\n 'OUTCOME_ENGAGEMENT',\n 'OUTCOME_LEADS',\n 'OUTCOME_SALES',\n 'OUTCOME_TRAFFIC',\n]);\n\nconst specialAdCategorySchema = z.enum([\n 'NONE',\n 'EMPLOYMENT',\n 'HOUSING',\n 'CREDIT',\n 'ISSUES_ELECTIONS_POLITICS',\n 'ONLINE_GAMBLING_AND_GAMING',\n 'FINANCIAL_PRODUCTS_SERVICES',\n]);\n\nexport function metaTools(provider: MetaAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({\n name: 'meta_insights',\n namespace: 'meta',\n description:\n 'Query the Meta Ads Insights API directly: pick a level (account/campaign/adset/ad), fields ' +\n '(spend, impressions, clicks, actions, action_values, purchase_roas, campaign_name, ...), and a ' +\n 'date_preset (last_7d, last_30d, maximum, ...) or explicit time_range. Values come back as strings; ' +\n 'spend is whole currency units.',\n input: z.object({\n account_id: z.string().describe('Numeric ad account id, act_ prefix optional'),\n level: z.enum(['account', 'campaign', 'adset', 'ad']).default('campaign'),\n fields: z.array(z.string()).min(1).default(['campaign_id', 'campaign_name', 'spend', 'impressions', 'clicks']),\n date_preset: z.string().optional(),\n time_range: z.object({ since: z.string(), until: z.string() }).optional(),\n breakdowns: z.array(z.string()).optional(),\n limit: z.number().int().positive().max(5000).default(200),\n }),\n annotations: { readOnly: true },\n async handler(input) {\n const rows = await provider.insights(input);\n return { rows, row_count: rows.length };\n },\n }),\n guardedWriteTool({\n name: 'meta_create_campaign',\n namespace: 'meta',\n description:\n 'Create a Meta campaign. Budget is optional at campaign level (Advantage/CBO) — otherwise set it on ad sets. ' +\n 'special_ad_categories is required by Meta for regulated verticals; defaults to none.',\n provider: 'meta',\n kind: 'create',\n payload: z.object({\n name: z.string().min(1),\n objective: objectiveSchema.default('OUTCOME_TRAFFIC'),\n status: statusSchema.optional(),\n special_ad_categories: z.array(specialAdCategorySchema).default([]),\n daily_budget_cents: z\n .number()\n .int()\n .positive()\n .optional()\n .describe('Minor currency units (cents for EUR/USD) — campaign-level CBO budget'),\n }),\n }),\n guardedWriteTool({\n name: 'meta_set_campaign_status',\n namespace: 'meta',\n description: 'Activate or pause a Meta campaign.',\n provider: 'meta',\n kind: 'update',\n payload: z.object({ campaign_id: z.string(), status: statusSchema }),\n }),\n guardedWriteTool({\n name: 'meta_set_budget',\n namespace: 'meta',\n description:\n 'Change the daily budget of a Meta campaign (CBO) or ad set — pass the object id that owns the budget. ' +\n 'The preview shows the current value and fails clearly when the object has no daily budget.',\n provider: 'meta',\n kind: 'update',\n payload: z.object({\n object_id: z.string().describe('Campaign id (CBO) or ad set id that owns the daily budget'),\n daily_budget_cents: z.number().int().positive().describe('Minor currency units (cents for EUR/USD)'),\n }),\n }),\n guardedWriteTool({\n name: 'meta_create_ad_set',\n namespace: 'meta',\n description:\n 'Create an ad set in a campaign with minimal country targeting. Omit daily_budget_cents when the campaign ' +\n 'uses CBO. Defaults: LINK_CLICKS optimization, IMPRESSIONS billing.',\n provider: 'meta',\n kind: 'create',\n payload: z.object({\n campaign_id: z.string(),\n name: z.string().min(1),\n countries: z.array(z.string().length(2)).min(1).describe('ISO country codes for geo targeting'),\n daily_budget_cents: z.number().int().positive().optional(),\n optimization_goal: z.string().optional(),\n billing_event: z.string().optional(),\n status: statusSchema.optional(),\n }),\n }),\n guardedWriteTool({\n name: 'meta_set_ad_set_status',\n namespace: 'meta',\n description: 'Activate or pause a Meta ad set.',\n provider: 'meta',\n kind: 'update',\n payload: z.object({ ad_set_id: z.string(), status: statusSchema }),\n }),\n ];\n}\n","import type { CredentialStore, ProviderModule } from '@adport/core';\nimport { MetaGraphClient, type MetaCredentials } from './client.js';\nimport { MetaAdsProvider } from './provider.js';\nimport { metaTools } from './tools.js';\n\nexport {\n MetaGraphClient,\n DEFAULT_GRAPH_VERSION,\n normalizeAccountId,\n formatMetaError,\n ACCOUNT_STATUS,\n type MetaCredentials,\n} from './client.js';\nexport { MetaAdsProvider, CENTS_TO_MICROS } from './provider.js';\nexport { metaTools } from './tools.js';\n\n/** Credential store record first, then META_ACCESS_TOKEN env fallback. */\nexport async function resolveMetaCredentials(store: CredentialStore): Promise<MetaCredentials | undefined> {\n const record = await store.get('meta');\n if (record?.data.access_token) {\n return {\n accessToken: record.data.access_token,\n appId: record.data.app_id || undefined,\n appSecret: record.data.app_secret || undefined,\n };\n }\n if (process.env.META_ACCESS_TOKEN) {\n return {\n accessToken: process.env.META_ACCESS_TOKEN,\n appId: process.env.META_APP_ID || undefined,\n appSecret: process.env.META_APP_SECRET || undefined,\n };\n }\n return undefined;\n}\n\n/** Provider module for createContext(); undefined when Meta isn't connected. */\nexport async function createMetaModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveMetaCredentials(store);\n if (!credentials) return undefined;\n const provider = new MetaAdsProvider(new MetaGraphClient(credentials));\n return { provider, tools: metaTools(provider) };\n}\n"],"mappings":";AAAA,SAAS,mBAAmB;AAU5B,IAAM,aAAa;AAEZ,IAAM,wBAAwB;AAG9B,SAAS,mBAAmB,IAAoB;AACrD,QAAM,aAAa,GAAG,QAAQ,SAAS,EAAE,EAAE,KAAK;AAChD,MAAI,CAAC,QAAQ,KAAK,UAAU,GAAG;AAC7B,UAAM,IAAI,YAAY,iBAAiB,IAAI,EAAE,sEAAsE;AAAA,EACrH;AACA,SAAO;AACT;AAGO,IAAM,iBAAyC;AAAA,EACpD,GAAG;AAAA,EACH,GAAG;AAAA,EACH,GAAG;AAAA,EACH,GAAG;AAAA,EACH,GAAG;AAAA,EACH,GAAG;AAAA,EACH,KAAK;AAAA,EACL,KAAK;AACP;AAOO,IAAM,kBAAN,MAAsB;AAAA,EAC3B,YACmB,aACA,UAAkB,QAAQ,IAAI,oBAAoB,uBAClD,YAA0B,OAC3C;AAHiB;AACA;AACA;AAAA,EAChB;AAAA,EAHgB;AAAA,EACA;AAAA,EACA;AAAA,EAGnB,MAAM,IAAO,MAAc,SAAiC,CAAC,GAAe;AAC1E,UAAM,SAAS,IAA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WAAW,CAAC;AACrE,SAAO,EAAE,UAAU,OAAO,UAAU,QAAQ,EAAE;AAChD;","names":["AdportError","AdportError"]}
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@adport/provider-meta",
3
+ "version": "0.1.0",
4
+ "description": "Meta (Facebook/Instagram) Ads provider for adport — Marketing API via Graph REST",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "dependencies": {
19
+ "zod": "^3.25.0",
20
+ "@adport/core": "0.1.0"
21
+ },
22
+ "devDependencies": {
23
+ "@types/node": "^22.10.0",
24
+ "tsup": "^8.3.0",
25
+ "typescript": "^5.8.0",
26
+ "vitest": "^3.0.0"
27
+ },
28
+ "scripts": {
29
+ "build": "tsup src/index.ts --format esm --dts --sourcemap --clean",
30
+ "test": "vitest run",
31
+ "typecheck": "tsc --noEmit",
32
+ "clean": "rm -rf dist"
33
+ }
34
+ }