@adport/provider-gravity 0.0.0-stage → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,810 @@
1
+ // src/client.ts
2
+ import { AdportError } from "@adport/core";
3
+ var GRAVITY_API_BASE = "https://platform.trygravity.com/advertiser-dashboard/";
4
+ var ORIGIN = "https://platform.trygravity.com";
5
+ var GravityClient = class {
6
+ constructor(credentials, fetchImpl = fetch) {
7
+ this.credentials = credentials;
8
+ this.fetchImpl = fetchImpl;
9
+ if (!credentials.apiKey.trim()) throw new AdportError("INVALID_INPUT", "gravity: API key is empty");
10
+ }
11
+ credentials;
12
+ fetchImpl;
13
+ async get(path, schema, params = {}) {
14
+ return this.parse(await this.send(this.url(path, params), "GET"), schema);
15
+ }
16
+ async post(path, schema, body) {
17
+ return this.parse(await this.send(this.url(path), "POST", body), schema);
18
+ }
19
+ async patch(path, schema, body) {
20
+ return this.parse(await this.send(this.url(path), "PATCH", body), schema);
21
+ }
22
+ parse(data, schema) {
23
+ const parsed = schema.safeParse(data);
24
+ if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "gravity: malformed API response", { response_issues: parsed.error.issues.slice(0, 20).map((issue) => ({ path: issue.path, code: issue.code })) });
25
+ return parsed.data;
26
+ }
27
+ url(path, params = {}) {
28
+ const url = new URL(path, GRAVITY_API_BASE);
29
+ if (url.origin !== ORIGIN || !url.pathname.startsWith("/advertiser-dashboard/") || url.username || url.password || url.hash) throw new AdportError("INVALID_INPUT", "gravity: invalid API URL");
30
+ for (const [key, value] of Object.entries(params)) if (value !== void 0) url.searchParams.set(key, value);
31
+ return url;
32
+ }
33
+ redact(value) {
34
+ return value.replaceAll(this.credentials.apiKey, "[redacted]").slice(0, 2e3);
35
+ }
36
+ async send(url, method, body) {
37
+ let response;
38
+ try {
39
+ response = await this.fetchImpl(url.href, {
40
+ method,
41
+ headers: {
42
+ "x-api-key": this.credentials.apiKey,
43
+ accept: "application/json",
44
+ ...body !== void 0 ? { "content-type": "application/json" } : {}
45
+ },
46
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {},
47
+ redirect: "error",
48
+ signal: AbortSignal.timeout(3e4)
49
+ });
50
+ } catch {
51
+ throw new AdportError("PROVIDER_ERROR", "gravity: request failed before a response was received. Check connectivity and reconcile any pending write.");
52
+ }
53
+ const raw = await response.json().catch(() => void 0);
54
+ if (!response.ok) {
55
+ const retryAfter = response.headers.get("retry-after");
56
+ const advice = response.status === 401 ? " Use the current advertiser API key from Gravity Settings \u2192 Organization." : response.status === 402 ? " Billing is not ready for activation; add a payment method in the Gravity dashboard." : response.status === 429 ? ` Rate limited; retry after ${retryAfter && /^\d+$/.test(retryAfter) ? `${retryAfter} s` : "a short wait"}.` : "";
57
+ const message = errorMessage(raw);
58
+ const code = errorCode(raw);
59
+ throw new AdportError("PROVIDER_ERROR", `gravity: HTTP ${response.status}.${advice}${message ? ` ${this.redact(message)}` : ""}`, {
60
+ http_status: response.status,
61
+ ...code ? { provider_code: code } : {}
62
+ });
63
+ }
64
+ return raw;
65
+ }
66
+ };
67
+ function errorMessage(raw) {
68
+ if (!raw || typeof raw !== "object") return void 0;
69
+ const detail = raw.detail;
70
+ if (typeof detail === "string") return detail;
71
+ if (Array.isArray(detail)) return detail.map((item) => item && typeof item === "object" && typeof item.msg === "string" ? item.msg : "").filter(Boolean).slice(0, 5).join("; ") || void 0;
72
+ if (detail && typeof detail === "object" && typeof detail.message === "string") return detail.message;
73
+ return void 0;
74
+ }
75
+ function errorCode(raw) {
76
+ if (!raw || typeof raw !== "object") return void 0;
77
+ const { error, detail } = raw;
78
+ for (const envelope of [error, detail]) {
79
+ if (!envelope || typeof envelope !== "object") continue;
80
+ const code = envelope.code;
81
+ if (typeof code === "string" && /^[a-z0-9_]{1,64}$/.test(code)) return code;
82
+ }
83
+ return void 0;
84
+ }
85
+
86
+ // src/provider.ts
87
+ import { z as z2 } from "zod";
88
+ import {
89
+ AdportError as AdportError2,
90
+ resolveDateRange
91
+ } from "@adport/core";
92
+
93
+ // src/schemas.ts
94
+ import { z } from "zod";
95
+ var gravityId = z.string().regex(/^[A-Za-z0-9_-]{1,128}$/);
96
+ var gravityStatus = z.enum(["active", "paused"]);
97
+ var gravityBudgetMicros = z.number().int().min(1e4).max(1e12).refine((value) => value % 1e4 === 0, "Use whole cents (multiples of 10,000 micros)");
98
+ var isoDateTime = z.iso.datetime({ offset: true });
99
+ var money = z.number().finite().nullable().optional();
100
+ var count = z.number().finite().nullable().optional();
101
+ var advertiserSchema = z.looseObject({ advertiser_id: gravityId, name: z.string().nullable().optional() });
102
+ var campaignSchema = z.looseObject({
103
+ campaign_id: gravityId,
104
+ name: z.string(),
105
+ status: z.string(),
106
+ is_active: z.boolean().optional(),
107
+ daily_budget: money,
108
+ total_budget: money,
109
+ budget_type: z.string().nullable().optional(),
110
+ landing_page: z.string().nullable().optional(),
111
+ campaign_objective: z.string().nullable().optional(),
112
+ billing_model: z.string().nullable().optional(),
113
+ bid_strategy: z.string().nullable().optional(),
114
+ conversion_type: z.string().nullable().optional(),
115
+ delivery_status: z.string().nullable().optional(),
116
+ delivery_issues: z.array(z.string()).nullable().optional(),
117
+ start_time: z.string().nullable().optional(),
118
+ end_time: z.string().nullable().optional(),
119
+ impressions: count,
120
+ clicks: count,
121
+ spend: money,
122
+ conversions: count,
123
+ conversion_value: money
124
+ });
125
+ var campaignListSchema = z.looseObject({ campaigns: z.array(campaignSchema) });
126
+ var adSchema = z.looseObject({
127
+ id: gravityId,
128
+ ad_group_id: gravityId.optional(),
129
+ campaign_id: gravityId.optional(),
130
+ name: z.string().nullable().optional(),
131
+ headline: z.string().nullable().optional(),
132
+ status: z.string(),
133
+ source: z.string().nullable().optional(),
134
+ review_status: z.string().nullable().optional(),
135
+ copy: z.string().nullable().optional(),
136
+ cta: z.string().nullable().optional(),
137
+ landing_page: z.string().nullable().optional()
138
+ });
139
+ var adGroupSchema = z.looseObject({
140
+ id: gravityId,
141
+ campaign_id: gravityId,
142
+ name: z.string(),
143
+ group_type: z.string().optional(),
144
+ status: z.string(),
145
+ ads: z.array(adSchema).optional(),
146
+ ads_total: z.number().int().optional()
147
+ });
148
+ var totals = {
149
+ total_impressions: count,
150
+ total_clicks: count,
151
+ total_spend: money,
152
+ total_conversions: count,
153
+ total_revenue: money
154
+ };
155
+ var metricsSchema = z.looseObject({ data: z.array(z.looseObject({ date: z.string() })), ...totals });
156
+ var adGroupMetricsSchema = z.looseObject({
157
+ ad_groups: z.array(z.looseObject({ ad_group_id: gravityId, campaign_id: gravityId, name: z.string(), status: z.string().nullable().optional(), ...totals })),
158
+ total_ad_groups: z.number().int().nonnegative(),
159
+ offset: z.number().int().nonnegative().optional(),
160
+ truncated: z.boolean()
161
+ });
162
+ var adUnitMetricsSchema = z.looseObject({
163
+ ad_units: z.array(z.looseObject({ ad_unit_id: gravityId, campaign_id: gravityId, name: z.string().nullable().optional(), data_source: z.string().optional(), ...totals }))
164
+ });
165
+ var conversionSchema = z.looseObject({
166
+ conversion_id: z.string(),
167
+ event_type: z.string(),
168
+ value_cents: z.number().int().nullable().optional(),
169
+ currency: z.string().nullable().optional(),
170
+ conversion_timestamp: z.string(),
171
+ campaign_id: z.string().nullable().optional(),
172
+ source: z.string().nullable().optional(),
173
+ is_attributed: z.boolean().optional(),
174
+ attribution_type: z.string().nullable().optional()
175
+ });
176
+ var conversionPageSchema = z.looseObject({
177
+ conversions: z.array(conversionSchema),
178
+ has_more: z.boolean(),
179
+ next_cursor: z.string().nullable().optional(),
180
+ total_conversions: z.number().int().optional(),
181
+ total_click_through_conversions: z.number().int().optional(),
182
+ total_view_through_conversions: z.number().int().optional()
183
+ });
184
+ var billingSchema = z.looseObject({
185
+ total_spend_dollars: z.number().finite(),
186
+ total_billed_dollars: z.number().finite(),
187
+ unbilled_dollars: z.number().finite(),
188
+ credits_dollars: z.number().finite(),
189
+ billing_enabled: z.boolean()
190
+ });
191
+ var listCampaignsSchema = z.object({ account_id: gravityId, status: z.enum(["active", "paused", "draft"]).optional() });
192
+ var listAdGroupsSchema = z.object({ account_id: gravityId, campaign_id: gravityId.optional(), include_archived: z.boolean().default(false) });
193
+ var listConversionsSchema = z.object({
194
+ account_id: gravityId,
195
+ campaign_id: gravityId.optional(),
196
+ event_type: z.string().min(1).max(100).optional().describe("For example purchase or lead"),
197
+ attribution_type: z.enum(["click_through", "view_through"]).optional(),
198
+ limit: z.number().int().min(1).max(500).default(100)
199
+ });
200
+ var billingInputSchema = z.object({ account_id: gravityId });
201
+ var getAdSchema = z.object({ account_id: gravityId, ad_id: gravityId });
202
+ var webUrl = z.url({ protocol: /^https?$/ }).max(2e3);
203
+ var pixelSchema = z.object({
204
+ pixel_id: gravityId,
205
+ name: z.string(),
206
+ url: webUrl,
207
+ is_active: z.boolean(),
208
+ is_functional: z.boolean().nullable()
209
+ });
210
+ var createPixelSchema = z.object({ url: webUrl, name: z.string().trim().min(1).max(255).optional() }).strict();
211
+ var conversionStatsInput = z.object({
212
+ account_id: gravityId,
213
+ days: z.number().int().min(1).max(365).optional(),
214
+ start_date: z.iso.date().optional(),
215
+ end_date: z.iso.date().optional(),
216
+ event_type: z.string().trim().min(1).max(100).optional()
217
+ }).refine((input) => {
218
+ if (!input.start_date && !input.end_date) return true;
219
+ return Boolean(!input.days && input.start_date && input.end_date && input.start_date <= input.end_date);
220
+ }, "Supply days or an ordered start_date and end_date pair");
221
+ var conversionStatsSchema = z.object({
222
+ time_series: z.array(z.object({ date: z.string(), conversions: z.number().int().nonnegative() })),
223
+ total: z.number().int().nonnegative(),
224
+ by_event_type: z.array(z.object({ event_type: z.string(), total: z.number().int().nonnegative() }))
225
+ });
226
+ var countries = z.array(z.string().regex(/^[A-Z]{2}$/)).min(1).max(250).refine((ids) => new Set(ids).size === ids.length, "Use unique countries");
227
+ var createCampaignSchema = z.object({
228
+ name: z.string().min(1).max(255).refine((value) => value.trim().length > 0, "Name cannot be blank"),
229
+ landing_page: webUrl,
230
+ status: z.enum(["draft", "paused", "active"]).default("draft"),
231
+ campaign_objective: z.enum(["clicks", "reach", "conversions"]),
232
+ conversion_type: z.string().min(1).max(100).optional().describe("Conversion event, for example purchase; required for conversions"),
233
+ daily_budget_micros: gravityBudgetMicros.optional(),
234
+ total_budget_micros: gravityBudgetMicros.optional().describe("Total budget for the whole schedule; requires end_time"),
235
+ start_time: isoDateTime.optional(),
236
+ end_time: isoDateTime.optional(),
237
+ allowed_countries: countries.optional(),
238
+ allowed_devices: z.array(z.enum(["web", "ios_app", "android_app"])).min(1).max(3).refine((ids) => new Set(ids).size === ids.length, "Use unique devices").optional(),
239
+ english_only: z.boolean().optional(),
240
+ ad_group_name: z.string().min(1).max(500).optional().describe('Defaults to "<name> (Generative)"'),
241
+ context: z.string().min(1).max(5e3).describe("Target context of the generative ad group; Gravity writes the ads from it"),
242
+ negative_context: z.string().min(1).max(5e3).optional(),
243
+ brand_name: z.string().min(1).max(500).optional().describe("Brand shown to users; defaults to the landing page host")
244
+ }).strict().refine((input) => Number(input.daily_budget_micros !== void 0) + Number(input.total_budget_micros !== void 0) === 1, "Set exactly one daily or total budget").refine((input) => input.total_budget_micros === void 0 || input.end_time !== void 0, "A total budget requires end_time").refine((input) => input.campaign_objective === "conversions" ? Boolean(input.conversion_type) : true, "A conversions campaign requires conversion_type").refine((input) => !input.start_time || !input.end_time || Date.parse(input.end_time) > Date.parse(input.start_time), "end_time must be after start_time");
245
+ var setCampaignStatusSchema = z.object({ campaign_id: gravityId, status: gravityStatus });
246
+ var setAdGroupStatusSchema = z.object({ ad_group_id: gravityId, status: gravityStatus });
247
+ var setAdStatusSchema = z.object({ ad_id: gravityId, status: gravityStatus });
248
+ var createAdGroupSchema = z.object({
249
+ campaign_id: gravityId,
250
+ name: z.string().trim().min(1).max(500),
251
+ group_type: z.enum(["generative", "manual"]),
252
+ context: z.string().trim().min(1).max(5e3).optional(),
253
+ negative_context: z.string().trim().min(1).max(5e3).optional(),
254
+ brand_name: z.string().trim().min(1).max(500).optional(),
255
+ landing_page: webUrl.optional(),
256
+ image_url: webUrl.optional(),
257
+ allowed_countries: countries.optional(),
258
+ status: gravityStatus.default("paused")
259
+ }).strict().refine((input) => input.group_type === "manual" || Boolean(input.context), "Generative groups require a target context");
260
+ var createAdSchema = z.object({
261
+ ad_group_id: gravityId,
262
+ headline: z.string().trim().min(1).max(50),
263
+ copy: z.string().trim().min(1).max(500),
264
+ cta: z.string().trim().min(1).max(80),
265
+ landing_page: webUrl,
266
+ image_url: webUrl.optional(),
267
+ name: z.string().trim().min(1).max(500).optional(),
268
+ status: gravityStatus.default("paused")
269
+ }).strict();
270
+ var setBudgetSchema = z.object({
271
+ campaign_id: gravityId,
272
+ field: z.enum(["daily_budget", "total_budget"]).default("daily_budget"),
273
+ budget_micros: gravityBudgetMicros
274
+ });
275
+
276
+ // src/provider.ts
277
+ var CURRENCY = "USD";
278
+ var REPORT_TZ = "UTC";
279
+ var STATUS_TOOLS = {
280
+ gravity_set_campaign_status: { path: "campaigns", label: "campaign", schema: setCampaignStatusSchema, key: "campaign_id", entity: campaignSchema, id: (value) => value.campaign_id },
281
+ gravity_set_ad_group_status: { path: "ad-groups", label: "ad group", schema: setAdGroupStatusSchema, key: "ad_group_id", entity: adGroupSchema, id: (value) => value.id },
282
+ gravity_set_ad_status: { path: "ads", label: "ad", schema: setAdStatusSchema, key: "ad_id", entity: adSchema, id: (value) => value.id }
283
+ };
284
+ var GravityProvider = class {
285
+ constructor(client, oauthScopes) {
286
+ this.client = client;
287
+ this.oauthScopes = oauthScopes;
288
+ }
289
+ client;
290
+ oauthScopes;
291
+ id = "gravity";
292
+ advertiser;
293
+ /** API access for read tools; callers check the account first. */
294
+ get api() {
295
+ return this.client;
296
+ }
297
+ capabilities() {
298
+ return { serverDryRun: false };
299
+ }
300
+ standardActions() {
301
+ return { pauseCampaign: (accountId, campaignId) => ({
302
+ tool: "gravity_set_campaign_status",
303
+ input: { account_id: accountId, campaign_id: campaignId, status: "paused" }
304
+ }) };
305
+ }
306
+ /** The advertiser API key belongs to exactly one advertiser account. */
307
+ keyAccount() {
308
+ this.advertiser ??= this.client.get("info", advertiserSchema).catch((error) => {
309
+ this.advertiser = void 0;
310
+ throw error;
311
+ });
312
+ return this.advertiser;
313
+ }
314
+ async assertAccount(accountId) {
315
+ const advertiser = await this.keyAccount();
316
+ if (gravityId.parse(accountId) !== advertiser.advertiser_id) throw new AdportError2("INVALID_INPUT", "gravity: account_id does not match the advertiser of the connected credential");
317
+ return advertiser;
318
+ }
319
+ async listAccounts() {
320
+ const advertiser = await this.keyAccount();
321
+ return [{ provider: this.id, id: advertiser.advertiser_id, name: advertiser.name || advertiser.advertiser_id, currency: CURRENCY, timezone: REPORT_TZ }];
322
+ }
323
+ async accountMetadata(accountId) {
324
+ await this.assertAccount(accountId);
325
+ return { currency: CURRENCY, timezone: REPORT_TZ };
326
+ }
327
+ async listCampaigns(accountId, status) {
328
+ await this.assertAccount(accountId);
329
+ return { items: (await this.client.get("campaigns", campaignListSchema, { status })).campaigns };
330
+ }
331
+ async listAdGroups(accountId, campaignId, includeArchived = false) {
332
+ await this.assertAccount(accountId);
333
+ return { items: await this.client.get("ad-groups", z2.array(adGroupSchema), { campaign_id: campaignId, include_archived: includeArchived ? "true" : void 0 }) };
334
+ }
335
+ async report(query) {
336
+ const range = resolveDateRange(query.dateRange);
337
+ const limit = query.limit ?? 1e3;
338
+ if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError2("INVALID_INPUT", "gravity: report limit must be a positive integer");
339
+ const advertiser = await this.keyAccount();
340
+ for (const id of new Set(query.accountIds ?? [advertiser.advertiser_id])) await this.assertAccount(id);
341
+ const window = { start_date: range.start, end_date: range.end, tz: REPORT_TZ };
342
+ const row = (level, id, name, status, totals2) => ({
343
+ provider: this.id,
344
+ accountId: advertiser.advertiser_id,
345
+ currency: CURRENCY,
346
+ entity: { level, id, name: name || id, ...status ? { status } : {} },
347
+ metrics: normalize(totals2, query.metrics)
348
+ });
349
+ if (query.level === "account") {
350
+ const totals2 = await this.client.get("metrics", metricsSchema, window);
351
+ return { rows: [row("account", advertiser.advertiser_id, advertiser.name, void 0, totals2)] };
352
+ }
353
+ if (query.level === "campaign") {
354
+ const campaigns = (await this.client.get("campaigns", campaignListSchema)).campaigns;
355
+ const selected = campaigns.slice(0, limit), rows2 = [];
356
+ for (let i = 0; i < selected.length; i += 5) {
357
+ const batch = await Promise.all(selected.slice(i, i + 5).map(async (campaign) => row("campaign", campaign.campaign_id, campaign.name, campaign.status, await this.client.get("metrics", metricsSchema, { ...window, campaign_id: campaign.campaign_id }))));
358
+ rows2.push(...batch);
359
+ }
360
+ return { rows: rows2, ...campaigns.length > limit ? { truncated: true } : {} };
361
+ }
362
+ if (query.level === "ad_group") return this.adGroupReport(window, limit, row);
363
+ const { ad_units } = await this.client.get("ad-unit-metrics", adUnitMetricsSchema, window);
364
+ const rows = ad_units.slice(0, limit).map((unit) => {
365
+ const name = `${unit.name || unit.ad_unit_id} \xB7 ${unit.campaign_id}${unit.data_source === "campaign_fallback" ? " (campaign totals)" : ""}`;
366
+ const totals2 = { total_impressions: unit.total_impressions, total_clicks: unit.total_clicks, total_spend: unit.total_spend };
367
+ return row("ad", `${unit.campaign_id}/${unit.ad_unit_id}`, name, void 0, totals2);
368
+ });
369
+ return { rows, ...ad_units.length > limit ? { truncated: true } : {} };
370
+ }
371
+ async adGroupReport(window, limit, row) {
372
+ const rows = [];
373
+ const seen = /* @__PURE__ */ new Set();
374
+ for (let offset = 0, pages = 0; ; pages++) {
375
+ if (pages >= 100) throw new AdportError2("PROVIDER_ERROR", "gravity: pagination did not terminate; refusing incomplete results");
376
+ const page = await this.client.get("ad-group-metrics", adGroupMetricsSchema, { ...window, offset: String(offset) });
377
+ if (page.offset !== void 0 && page.offset !== offset) throw new AdportError2("PROVIDER_ERROR", "gravity: ad group metrics returned the wrong page offset");
378
+ for (const group of page.ad_groups) {
379
+ if (seen.has(group.ad_group_id)) throw new AdportError2("PROVIDER_ERROR", "gravity: ad group metrics returned overlapping rows");
380
+ seen.add(group.ad_group_id);
381
+ rows.push(row("ad_group", group.ad_group_id, group.name, group.status, group));
382
+ }
383
+ if (rows.length > limit || rows.length === limit && page.truncated) return { rows: rows.slice(0, limit), truncated: true };
384
+ if (!page.truncated) return { rows };
385
+ if (!page.ad_groups.length) throw new AdportError2("PROVIDER_ERROR", "gravity: ad group metrics are truncated but the page is empty");
386
+ offset += page.ad_groups.length;
387
+ }
388
+ }
389
+ async previewWrite(op, guard) {
390
+ const { execute: _execute, ...preview } = await this.plan(op, guard);
391
+ return { ...preview, serverValidated: false };
392
+ }
393
+ async applyWrite(op, guard) {
394
+ return (await this.plan(op, guard)).execute();
395
+ }
396
+ async plan(op, guard) {
397
+ if (op.provider !== this.id) throw new AdportError2("INVALID_INPUT", "gravity: provider mismatch");
398
+ this.requireScope("write");
399
+ await this.assertAccount(op.accountId);
400
+ if (op.tool === "gravity_create_campaign" && op.kind === "create") return this.planCreate(op, guard);
401
+ if (op.tool === "gravity_create_ad_group" && op.kind === "create") return this.planAdGroup(op, guard);
402
+ if (op.tool === "gravity_create_ad" && op.kind === "create") return this.planAd(op, guard);
403
+ if (op.tool === "gravity_create_pixel" && op.kind === "create") return this.planPixel(op);
404
+ if (op.tool === "gravity_set_budget" && op.kind === "update") return this.planBudget(op);
405
+ if (op.kind === "update" && Object.hasOwn(STATUS_TOOLS, op.tool)) return this.planStatus(op);
406
+ throw new AdportError2("INVALID_INPUT", `gravity: unsupported write ${op.tool}`);
407
+ }
408
+ requireScope(scope) {
409
+ if (this.oauthScopes && !this.oauthScopes.includes(scope)) throw new AdportError2("POLICY_VIOLATION", "Reconnect Gravity with the " + scope + " permission for this change.");
410
+ }
411
+ planCreate(op, guard) {
412
+ const input = createCampaignSchema.parse(op.payload);
413
+ const status = guard.forcePausedCreation && input.status === "active" ? "paused" : input.status;
414
+ if (status === "active") this.requireScope("spend");
415
+ const budget = input.daily_budget_micros !== void 0 ? { budget_type: "daily", daily_budget: dollars(input.daily_budget_micros) } : { budget_type: "total", total_budget: dollars(input.total_budget_micros) };
416
+ const adGroup = {
417
+ name: input.ad_group_name ?? `${input.name} (Generative)`,
418
+ group_type: "generative",
419
+ context: input.context,
420
+ ...input.negative_context ? { negative_context: input.negative_context } : {},
421
+ ...input.brand_name ? { brand_name: input.brand_name } : {}
422
+ };
423
+ const body = {
424
+ name: input.name,
425
+ landing_page: input.landing_page,
426
+ status,
427
+ campaign_objective: input.campaign_objective,
428
+ ...budget,
429
+ ...input.conversion_type ? { conversion_type: input.conversion_type } : {},
430
+ ...input.start_time ? { start_time: input.start_time } : {},
431
+ ...input.end_time ? { end_time: input.end_time } : {},
432
+ ...input.allowed_countries ? { allowed_countries: input.allowed_countries } : {},
433
+ ...input.allowed_devices ? { allowed_devices: input.allowed_devices } : {},
434
+ ...input.english_only !== void 0 ? { english_only: input.english_only } : {},
435
+ ad_groups: [adGroup]
436
+ };
437
+ const budgetField = input.daily_budget_micros !== void 0 ? "daily_budget" : "total_budget";
438
+ return {
439
+ summary: `Create Gravity campaign "${input.name}" (${status})`,
440
+ changes: [`+ ${JSON.stringify(body)}`],
441
+ coercions: status !== input.status ? ["status coerced to paused by policy (paused_creation)"] : [],
442
+ budgetDeltas: [{ target: `new campaign ${budgetField}`, toMicros: input.daily_budget_micros ?? input.total_budget_micros }],
443
+ execute: async () => {
444
+ const created = await this.client.post("campaigns", campaignSchema.extend({ ad_groups: z2.array(adGroupSchema).optional() }), body);
445
+ const amount = created[budgetField];
446
+ const [group] = created.ad_groups ?? [];
447
+ if (created.name !== body.name || created.status !== status || typeof amount !== "number" || micros(amount) !== (input.daily_budget_micros ?? input.total_budget_micros) || created.campaign_objective !== body.campaign_objective || created.ad_groups?.length !== 1 || group?.campaign_id !== created.campaign_id || group.name !== adGroup.name || group.group_type !== "generative") {
448
+ throw new AdportError2("PROVIDER_ERROR", "gravity: campaign creation receipt mismatch; reconcile before retrying", { resource_ids: [created.campaign_id] });
449
+ }
450
+ return { applied: true, resourceIds: [created.campaign_id, group.id] };
451
+ }
452
+ };
453
+ }
454
+ async planAdGroup(op, guard) {
455
+ const input = createAdGroupSchema.parse(op.payload);
456
+ if (!guard.forcePausedCreation && input.status === "active") this.requireScope("spend");
457
+ const campaign = await this.client.get(`campaigns/${input.campaign_id}`, campaignSchema);
458
+ if (campaign.campaign_id !== input.campaign_id) throw new AdportError2("PROVIDER_ERROR", "gravity: campaign response does not match the parent campaign");
459
+ return creativePlan(`ad group "${input.name}" in "${campaign.name}"`, input, guard, async (body) => {
460
+ const group = await this.client.post("ad-groups", adGroupSchema, body);
461
+ if (group.campaign_id !== campaign.campaign_id || group.name !== input.name || group.group_type !== input.group_type || group.status !== body.status) {
462
+ throw new AdportError2("PROVIDER_ERROR", "gravity: ad group creation receipt mismatch; reconcile before retrying", { resource_ids: [group.id] });
463
+ }
464
+ return { applied: true, resourceIds: [group.id] };
465
+ });
466
+ }
467
+ async planAd(op, guard) {
468
+ const { ad_group_id, ...input } = createAdSchema.parse(op.payload);
469
+ if (!guard.forcePausedCreation && input.status === "active") this.requireScope("spend");
470
+ const group = await this.client.get(`ad-groups/${ad_group_id}`, adGroupSchema);
471
+ if (group.id !== ad_group_id) throw new AdportError2("PROVIDER_ERROR", "gravity: ad group response does not match the parent ad group");
472
+ if (group.group_type !== "manual") throw new AdportError2("INVALID_INPUT", "gravity: authored ads require a manual ad group");
473
+ return creativePlan(`ad "${input.headline}" in "${group.name}"`, input, guard, async (body) => {
474
+ const ad = await this.client.post(`ad-groups/${group.id}/ads`, adSchema, body);
475
+ if (ad.ad_group_id !== group.id || ad.campaign_id !== group.campaign_id || ad.source !== "manual" || ad.status !== body.status || ad.headline !== body.headline || ad.copy !== body.copy || ad.cta !== body.cta || !sameWebUrl(ad.landing_page, body.landing_page)) {
476
+ throw new AdportError2("PROVIDER_ERROR", "gravity: ad creation receipt mismatch; reconcile before retrying", { resource_ids: [ad.id] });
477
+ }
478
+ return { applied: true, resourceIds: [ad.id] };
479
+ });
480
+ }
481
+ planPixel(op) {
482
+ const body = createPixelSchema.parse(op.payload);
483
+ return {
484
+ summary: `Register Gravity conversion pixel for ${body.url}`,
485
+ changes: [`+ ${JSON.stringify(body)}`],
486
+ coercions: [],
487
+ budgetDeltas: [],
488
+ execute: async () => {
489
+ const pixel = await this.client.post("pixels", pixelSchema, body);
490
+ if (!sameWebUrl(pixel.url, body.url) || body.name !== void 0 && pixel.name !== body.name) {
491
+ throw new AdportError2("PROVIDER_ERROR", "gravity: pixel creation receipt mismatch; reconcile before retrying", { resource_ids: [pixel.pixel_id] });
492
+ }
493
+ return { applied: true, resourceIds: [pixel.pixel_id] };
494
+ }
495
+ };
496
+ }
497
+ async planBudget(op) {
498
+ const input = setBudgetSchema.parse(op.payload);
499
+ const current = await this.client.get(`campaigns/${input.campaign_id}`, campaignSchema);
500
+ if (current.campaign_id !== input.campaign_id) throw new AdportError2("PROVIDER_ERROR", "gravity: campaign response does not match the requested campaign");
501
+ const available = ["daily", "total"].filter((type2) => typeof current[`${type2}_budget`] === "number");
502
+ const uncappedDaily = current.bid_strategy === "target_cpa" && current.daily_budget === null && current.total_budget == null;
503
+ const type = current.budget_type ?? (available.length === 1 ? available[0] : uncappedDaily ? "daily" : void 0);
504
+ if (type !== "daily" && type !== "total") throw new AdportError2("PROVIDER_ERROR", "gravity: could not establish the current campaign budget type");
505
+ if (`${type}_budget` !== input.field) throw new AdportError2("INVALID_INPUT", `gravity: campaign uses a ${type} budget; update ${type}_budget instead (budget-type changes are not supported)`);
506
+ const currentAmount = current[input.field];
507
+ if (typeof currentAmount !== "number" && !(type === "daily" && uncappedDaily)) {
508
+ throw new AdportError2("PROVIDER_ERROR", "gravity: could not establish the current campaign budget for policy checks");
509
+ }
510
+ const previous = typeof currentAmount === "number" ? micros(currentAmount) : void 0;
511
+ if (previous === void 0 || input.budget_micros > previous) this.requireScope("spend");
512
+ const amount = dollars(input.budget_micros);
513
+ return {
514
+ summary: `Change Gravity campaign "${current.name}" ${input.field}`,
515
+ changes: [`~ ${current.campaign_id} ${input.field}: ${previous === void 0 ? "unset" : `$${previous / 1e6}`} \u2192 $${amount}`],
516
+ fieldChanges: [{ field: input.field, before: previous === void 0 ? "unset" : String(previous), after: String(input.budget_micros) }],
517
+ coercions: [],
518
+ budgetDeltas: [{ target: `campaign ${current.campaign_id} ${input.field}`, ...previous !== void 0 ? { fromMicros: previous } : {}, toMicros: input.budget_micros }],
519
+ execute: async () => {
520
+ const updated = await this.client.patch(`campaigns/${current.campaign_id}`, campaignSchema, { [input.field]: amount });
521
+ const value = updated[input.field];
522
+ if (updated.campaign_id !== current.campaign_id || typeof value !== "number" || micros(value) !== input.budget_micros) throw new AdportError2("PROVIDER_ERROR", "gravity: campaign budget receipt mismatch; reconcile before retrying", { resource_ids: [current.campaign_id] });
523
+ return { applied: true, resourceIds: [current.campaign_id] };
524
+ }
525
+ };
526
+ }
527
+ async planStatus(op) {
528
+ const spec = STATUS_TOOLS[op.tool];
529
+ const input = spec.schema.parse(op.payload);
530
+ const id = input[spec.key], status = input.status;
531
+ if (status === "active") this.requireScope("spend");
532
+ const entity = spec.entity;
533
+ const readId = spec.id;
534
+ const current = await this.client.get(`${spec.path}/${id}`, entity);
535
+ if (readId(current) !== id) throw new AdportError2("PROVIDER_ERROR", `gravity: ${spec.label} response does not match the requested ${spec.label}`);
536
+ if (op.tool === "gravity_set_ad_status" && current.source !== "manual") throw new AdportError2("INVALID_INPUT", "gravity: only manual ads can be changed; pause the generative ad group instead");
537
+ const label = current.name || current.headline || id;
538
+ return {
539
+ summary: `${status === "active" ? "Activate" : "Pause"} Gravity ${spec.label} "${label}"`,
540
+ changes: [`~ ${id} status: ${current.status} \u2192 ${status}`],
541
+ fieldChanges: [{ field: "status", before: String(current.status), after: status }],
542
+ ...status === "active" && op.tool === "gravity_set_campaign_status" ? { notes: ["Gravity checks billing and the conversion event on activation, and may send the campaign to review again."] } : {},
543
+ coercions: [],
544
+ budgetDeltas: [],
545
+ execute: async () => {
546
+ const updated = await this.client.patch(`${spec.path}/${id}`, entity, { status });
547
+ if (readId(updated) !== id || updated.status !== status) throw new AdportError2("PROVIDER_ERROR", `gravity: ${spec.label} status receipt mismatch; reconcile before retrying`, { resource_ids: [id] });
548
+ return { applied: true, resourceIds: [id] };
549
+ }
550
+ };
551
+ }
552
+ };
553
+ function creativePlan(label, input, guard, submit) {
554
+ const status = guard.forcePausedCreation ? "paused" : input.status;
555
+ const body = { ...input, status };
556
+ return {
557
+ summary: `Create Gravity ${label} (${status})`,
558
+ changes: [`+ ${JSON.stringify(body)}`],
559
+ budgetDeltas: [],
560
+ coercions: status !== input.status ? ["status coerced to paused by policy (paused_creation)"] : [],
561
+ execute: () => submit(body)
562
+ };
563
+ }
564
+ function sameWebUrl(actual, expected) {
565
+ return Boolean(actual && URL.canParse(actual) && new URL(actual).href === new URL(expected).href);
566
+ }
567
+ var dollars = (value) => value / 1e6;
568
+ var micros = (value) => Math.round(value * 1e6);
569
+ function normalize(totals2, metrics) {
570
+ const mapped = {};
571
+ const fields = { spend: "total_spend", impressions: "total_impressions", clicks: "total_clicks", conversions: "total_conversions", conversion_value: "total_revenue" };
572
+ for (const [metric, field] of Object.entries(fields)) {
573
+ const value = totals2[field];
574
+ if (typeof value === "number") mapped[metric] = value;
575
+ }
576
+ for (const [metric, numerator, denominator, factor] of [
577
+ ["ctr", "clicks", "impressions", 100],
578
+ ["cpc", "spend", "clicks", 1],
579
+ ["cpm", "spend", "impressions", 1e3],
580
+ ["cpa", "spend", "conversions", 1],
581
+ ["roas", "conversion_value", "spend", 1]
582
+ ]) {
583
+ if (mapped[numerator] !== void 0 && mapped[denominator]) mapped[metric] = mapped[numerator] / mapped[denominator] * factor;
584
+ }
585
+ return Object.fromEntries(metrics.filter((metric) => mapped[metric] !== void 0).map((metric) => [metric, mapped[metric]]));
586
+ }
587
+
588
+ // src/tools.ts
589
+ import { AdportError as AdportError3, defineTool, guardedWriteTool } from "@adport/core";
590
+ import { z as z3 } from "zod";
591
+ async function listConversions(provider, input) {
592
+ await provider.assertAccount(input.account_id);
593
+ const items = [];
594
+ const seen = /* @__PURE__ */ new Set(), ids = /* @__PURE__ */ new Set();
595
+ const totalKeys = ["total_conversions", "total_click_through_conversions", "total_view_through_conversions"];
596
+ const totals2 = {};
597
+ let cursor;
598
+ while (true) {
599
+ const page = await provider.api.get("conversions", conversionPageSchema, {
600
+ limit: String(Math.min(100, input.limit - items.length)),
601
+ cursor,
602
+ campaign_id: input.campaign_id,
603
+ event_type: input.event_type,
604
+ attribution_type: input.attribution_type
605
+ });
606
+ for (const conversion of page.conversions) {
607
+ if (ids.has(conversion.conversion_id)) throw new AdportError3("PROVIDER_ERROR", "gravity: conversion pagination returned overlapping rows");
608
+ ids.add(conversion.conversion_id);
609
+ items.push(conversion);
610
+ }
611
+ for (const key of totalKeys) if (page[key] !== void 0) totals2[key] ??= page[key];
612
+ if (items.length > input.limit || items.length === input.limit && page.has_more) return { items: items.slice(0, input.limit), truncated: true, ...totals2 };
613
+ if (!page.has_more) return { items, ...totals2 };
614
+ if (!page.conversions.length) throw new AdportError3("PROVIDER_ERROR", "gravity: conversion pagination returned an empty intermediate page");
615
+ const next = page.next_cursor ?? void 0;
616
+ if (!next || seen.has(next) || seen.size >= 1e3) throw new AdportError3("PROVIDER_ERROR", "gravity: pagination did not terminate; refusing incomplete results");
617
+ seen.add(next);
618
+ cursor = next;
619
+ }
620
+ }
621
+ function gravityTools(provider) {
622
+ return [
623
+ defineTool({
624
+ name: "gravity_list_campaigns",
625
+ namespace: "gravity",
626
+ description: "List Gravity campaigns (ads in AI assistants) with status, delivery status, budgets in dollars and lifetime totals.",
627
+ input: listCampaignsSchema,
628
+ annotations: { readOnly: true },
629
+ handler: (input) => provider.listCampaigns(input.account_id, input.status)
630
+ }),
631
+ defineTool({
632
+ name: "gravity_ad_groups",
633
+ namespace: "gravity",
634
+ description: "List Gravity ad groups (generative or manual) with up to 100 ads each, optionally for one campaign.",
635
+ input: listAdGroupsSchema,
636
+ annotations: { readOnly: true },
637
+ handler: (input) => provider.listAdGroups(input.account_id, input.campaign_id, input.include_archived)
638
+ }),
639
+ defineTool({
640
+ name: "gravity_ads",
641
+ namespace: "gravity",
642
+ description: "List ads in one Gravity ad group with creative, status and the available count.",
643
+ input: z3.object({ account_id: gravityId, ad_group_id: gravityId }).strict(),
644
+ annotations: { readOnly: true },
645
+ handler: async ({ account_id, ad_group_id }) => {
646
+ await provider.assertAccount(account_id);
647
+ const group = await provider.api.get(`ad-groups/${ad_group_id}`, adGroupSchema);
648
+ if (group.id !== ad_group_id || !group.ads || group.ads.some((ad) => ad.ad_group_id != null && ad.ad_group_id !== group.id) || group.ads_total != null && group.ads_total < group.ads.length) {
649
+ throw new AdportError3("PROVIDER_ERROR", "Gravity returned incomplete or inconsistent ad-group data.");
650
+ }
651
+ return { items: group.ads, total_count: group.ads_total ?? null, truncated: group.ads_total == null ? null : group.ads_total > group.ads.length };
652
+ }
653
+ }),
654
+ defineTool({
655
+ name: "gravity_get_ad",
656
+ namespace: "gravity",
657
+ description: "Read a Gravity ad by ID, including creative, source, status and review status.",
658
+ input: getAdSchema,
659
+ annotations: { readOnly: true },
660
+ handler: async (input) => {
661
+ await provider.assertAccount(input.account_id);
662
+ const ad = await provider.api.get(`ads/${input.ad_id}`, adSchema);
663
+ if (ad.id !== input.ad_id) throw new AdportError3("PROVIDER_ERROR", "gravity: ad response does not match the requested ad");
664
+ return ad;
665
+ }
666
+ }),
667
+ defineTool({
668
+ name: "gravity_pixels",
669
+ namespace: "gravity",
670
+ description: "List conversion pixels and their installation status. A null status means verification is pending or unavailable.",
671
+ input: billingInputSchema,
672
+ annotations: { readOnly: true },
673
+ handler: async (input) => {
674
+ await provider.assertAccount(input.account_id);
675
+ return { items: await provider.api.get("pixels", z3.array(pixelSchema)) };
676
+ }
677
+ }),
678
+ defineTool({
679
+ name: "gravity_conversion_stats",
680
+ namespace: "gravity",
681
+ description: "Read conversion totals by day and event type for a lookback or date range.",
682
+ input: conversionStatsInput,
683
+ annotations: { readOnly: true },
684
+ handler: async (input) => {
685
+ await provider.assertAccount(input.account_id);
686
+ return provider.api.get("events/conversion-stats", conversionStatsSchema, {
687
+ days: input.days?.toString(),
688
+ start_date: input.start_date,
689
+ end_date: input.end_date,
690
+ event_type: input.event_type
691
+ });
692
+ }
693
+ }),
694
+ defineTool({
695
+ name: "gravity_conversions",
696
+ namespace: "gravity",
697
+ description: "List recent Gravity conversions (event type, value in cents, source, click- or view-through attribution) to check that pixel or server tracking arrives.",
698
+ input: listConversionsSchema,
699
+ annotations: { readOnly: true },
700
+ handler: (input) => listConversions(provider, input)
701
+ }),
702
+ defineTool({
703
+ name: "gravity_billing",
704
+ namespace: "gravity",
705
+ description: "Show the Gravity billing summary: total spend, billed, unbilled and credits in dollars.",
706
+ input: billingInputSchema,
707
+ annotations: { readOnly: true },
708
+ handler: async (input) => {
709
+ await provider.assertAccount(input.account_id);
710
+ return provider.api.get("billing", billingSchema);
711
+ }
712
+ }),
713
+ guardedWriteTool({
714
+ name: "gravity_create_campaign",
715
+ namespace: "gravity",
716
+ provider: "gravity",
717
+ kind: "create",
718
+ description: "Create a draft or paused Gravity campaign with one generative ad group built from a target context. Exactly one daily or total budget in micros (whole cents); total budgets need end_time. Conversions campaigns need conversion_type. Preview is local.",
719
+ payload: createCampaignSchema
720
+ }),
721
+ guardedWriteTool({
722
+ name: "gravity_set_campaign_status",
723
+ namespace: "gravity",
724
+ provider: "gravity",
725
+ kind: "update",
726
+ description: "Pause or activate a Gravity campaign; reads its current status first. Activation can fail on billing or the conversion event check.",
727
+ payload: setCampaignStatusSchema
728
+ }),
729
+ guardedWriteTool({
730
+ name: "gravity_set_ad_group_status",
731
+ namespace: "gravity",
732
+ provider: "gravity",
733
+ kind: "update",
734
+ description: "Pause or activate a Gravity ad group; reads its current status first.",
735
+ payload: setAdGroupStatusSchema
736
+ }),
737
+ guardedWriteTool({
738
+ name: "gravity_set_ad_status",
739
+ namespace: "gravity",
740
+ provider: "gravity",
741
+ kind: "update",
742
+ description: "Pause or activate a manual Gravity ad; generated ads are refused. Reads its current status first.",
743
+ payload: setAdStatusSchema
744
+ }),
745
+ guardedWriteTool({
746
+ name: "gravity_set_budget",
747
+ namespace: "gravity",
748
+ provider: "gravity",
749
+ kind: "update",
750
+ description: "Update a Gravity campaign\u2019s existing daily or total budget, in micros (whole cents); reads the current value for policy checks. Budget-type changes are not supported.",
751
+ payload: setBudgetSchema
752
+ }),
753
+ guardedWriteTool({
754
+ name: "gravity_create_ad_group",
755
+ namespace: "gravity",
756
+ provider: "gravity",
757
+ kind: "create",
758
+ description: "Create a paused manual or generative ad group in a Gravity campaign. Generative groups need target context.",
759
+ payload: createAdGroupSchema
760
+ }),
761
+ guardedWriteTool({
762
+ name: "gravity_create_ad",
763
+ namespace: "gravity",
764
+ provider: "gravity",
765
+ kind: "create",
766
+ description: "Create an authored ad in a manual Gravity ad group. Defaults to paused.",
767
+ payload: createAdSchema
768
+ }),
769
+ guardedWriteTool({
770
+ name: "gravity_create_pixel",
771
+ namespace: "gravity",
772
+ provider: "gravity",
773
+ kind: "create",
774
+ description: "Register a site conversion pixel. Gravity checks the installation after creation.",
775
+ payload: createPixelSchema
776
+ })
777
+ ];
778
+ }
779
+
780
+ // src/index.ts
781
+ function gravityCredentialsFromData(data) {
782
+ const apiKey = data?.api_key?.trim();
783
+ return apiKey ? { apiKey } : void 0;
784
+ }
785
+ function gravityEnvironmentData() {
786
+ return { api_key: process.env.GRAVITY_API_KEY ?? "" };
787
+ }
788
+ async function resolveGravityCredentials(store) {
789
+ return gravityCredentialsFromData((await store.get("gravity"))?.data) ?? gravityCredentialsFromData(gravityEnvironmentData());
790
+ }
791
+ async function createGravityModule(store) {
792
+ const credentials = await resolveGravityCredentials(store);
793
+ if (!credentials) return void 0;
794
+ const provider = new GravityProvider(new GravityClient(credentials));
795
+ return { provider, tools: gravityTools(provider) };
796
+ }
797
+ export {
798
+ GRAVITY_API_BASE,
799
+ GravityClient,
800
+ GravityProvider,
801
+ adGroupSchema,
802
+ advertiserSchema,
803
+ campaignSchema,
804
+ createGravityModule,
805
+ gravityCredentialsFromData,
806
+ gravityEnvironmentData,
807
+ gravityTools,
808
+ resolveGravityCredentials
809
+ };
810
+ //# sourceMappingURL=index.js.map