@rawdash/connector-meta-ads 0.16.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/README.md +131 -0
- package/dist/index.d.ts +393 -0
- package/dist/index.js +553 -0
- package/dist/index.js.map +1 -0
- package/package.json +42 -0
package/README.md
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
<!-- This file is generated from connector metadata by scripts/generate-connector-docs.ts. Do not edit by hand. -->
|
|
2
|
+
|
|
3
|
+
# @rawdash/connector-meta-ads
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/@rawdash/connector-meta-ads)
|
|
6
|
+
[](https://github.com/rawdash/rawdash/blob/main/LICENSE)
|
|
7
|
+
|
|
8
|
+
Sync Meta (Facebook + Instagram) ad campaigns plus daily campaign, adset, and ad-level insights - spend, impressions, clicks, reach, conversions, and conversion value.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install @rawdash/connector-meta-ads
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Authentication
|
|
17
|
+
|
|
18
|
+
A long-lived System User access token from Meta Business Manager, scoped with `ads_read` (and `read_insights` on newer accounts) for the target ad account.
|
|
19
|
+
|
|
20
|
+
1. In Meta Business Manager → Business Settings → Users → System Users, create a System User (or reuse an existing one) and assign it to the ad account with at least the Advertiser role.
|
|
21
|
+
2. Generate a System User access token for the System User; pick `ads_read` and (where available) `read_insights` as the scopes. Choose the longest available expiry - System User tokens can be made effectively non-expiring.
|
|
22
|
+
3. Find the ad account ID in Ads Manager → Settings → Account info; it always starts with `act_`.
|
|
23
|
+
4. Store the token as a secret and reference it from the connector config as `accessToken: secret("META_ACCESS_TOKEN")` alongside `adAccountId: "act_<id>"`.
|
|
24
|
+
|
|
25
|
+
## Configuration
|
|
26
|
+
|
|
27
|
+
| Field | Type | Required | Description |
|
|
28
|
+
| -------------- | ------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
29
|
+
| `adAccountId` | string | Yes | Meta Marketing API ad account ID. Find it in Ads Manager → Settings → Account info; it always starts with `act_`. |
|
|
30
|
+
| `accessToken` | secret | Yes | Long-lived System User access token from Meta Business Manager with `ads_read` (and, for newer accounts, `read_insights`) scopes on the chosen ad account. |
|
|
31
|
+
| `apiVersion` | string | No | Pin a specific Meta Graph API version (e.g. `v21.0`). Defaults to `v21.0`. |
|
|
32
|
+
| `lookbackDays` | number | No | How many calendar days of insights to fetch on a full sync. Defaults to 90. |
|
|
33
|
+
| `resources` | array | No | Which Meta resources to sync. Omit to sync all. Ad-level insights are the most expensive - leave them out if you only need campaign or adset rollups. |
|
|
34
|
+
|
|
35
|
+
## Resources
|
|
36
|
+
|
|
37
|
+
- **`meta_campaign`** _(entity)_ - Meta ad campaigns with name, objective, status, and budget. Upserted by id; one row per campaign in the ad account.
|
|
38
|
+
- Endpoint: `GET /{ad_account_id}/campaigns`
|
|
39
|
+
- **`meta_campaign_insights`** _(metric)_ - Daily campaign-level Meta Ads insights - spend (primary value), impressions, clicks, reach, conversions, and conversion value bucketed by campaign.
|
|
40
|
+
- Endpoint: `GET /{ad_account_id}/insights?level=campaign&time_increment=1`
|
|
41
|
+
- Unit: spend
|
|
42
|
+
- Granularity: day
|
|
43
|
+
- Dimensions: `date`, `campaignId`, `campaignName`, `impressions`, `clicks`, `spend`, `reach`, `conversions`, `conversion_value`
|
|
44
|
+
- Primary value is `spend`. `conversions` is the sum of every entry in the upstream `actions` array; `conversion_value` is the sum of every entry in `action_values`.
|
|
45
|
+
- **`meta_adset_insights`** _(metric)_ - Daily adset-level Meta Ads insights - same fields as the campaign roll-up, bucketed by adset.
|
|
46
|
+
- Endpoint: `GET /{ad_account_id}/insights?level=adset&time_increment=1`
|
|
47
|
+
- Unit: spend
|
|
48
|
+
- Granularity: day
|
|
49
|
+
- Dimensions: `date`, `campaignId`, `campaignName`, `adsetId`, `adsetName`, `impressions`, `clicks`, `spend`, `reach`, `conversions`, `conversion_value`
|
|
50
|
+
- Primary value is `spend`. Includes campaign_id/campaign_name so adset rows are easy to roll up to their parent campaign.
|
|
51
|
+
- **`meta_ad_insights`** _(metric)_ - Daily ad-level Meta Ads insights - same fields as the adset roll-up, bucketed by ad.
|
|
52
|
+
- Endpoint: `GET /{ad_account_id}/insights?level=ad&time_increment=1`
|
|
53
|
+
- Unit: spend
|
|
54
|
+
- Granularity: day
|
|
55
|
+
- Dimensions: `date`, `campaignId`, `campaignName`, `adsetId`, `adsetName`, `adId`, `adName`, `impressions`, `clicks`, `spend`, `reach`, `conversions`, `conversion_value`
|
|
56
|
+
- Primary value is `spend`. Cardinality is the highest of the three insights resources - opt in via `resources: [..., "ad_insights"]` only when you need per-ad breakdowns.
|
|
57
|
+
|
|
58
|
+
## Example
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
import {
|
|
62
|
+
defineConfig,
|
|
63
|
+
defineDashboard,
|
|
64
|
+
defineMetric,
|
|
65
|
+
secret,
|
|
66
|
+
} from '@rawdash/core';
|
|
67
|
+
|
|
68
|
+
const metaAds = {
|
|
69
|
+
name: 'metaAds',
|
|
70
|
+
connectorId: 'meta-ads',
|
|
71
|
+
config: {
|
|
72
|
+
adAccountId: 'act_1234567890',
|
|
73
|
+
accessToken: secret('META_ACCESS_TOKEN'),
|
|
74
|
+
lookbackDays: 90,
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
export default defineConfig({
|
|
79
|
+
connectors: [metaAds],
|
|
80
|
+
dashboards: {
|
|
81
|
+
marketing: defineDashboard({
|
|
82
|
+
widgets: {
|
|
83
|
+
spend_30d: {
|
|
84
|
+
kind: 'stat',
|
|
85
|
+
title: 'Meta Ads spend (30d)',
|
|
86
|
+
window: '30d',
|
|
87
|
+
metric: defineMetric({
|
|
88
|
+
connector: metaAds,
|
|
89
|
+
shape: 'metric',
|
|
90
|
+
name: 'meta_campaign_insights',
|
|
91
|
+
field: 'spend',
|
|
92
|
+
fn: 'sum',
|
|
93
|
+
}),
|
|
94
|
+
},
|
|
95
|
+
daily_spend: {
|
|
96
|
+
kind: 'timeseries',
|
|
97
|
+
title: 'Daily Meta Ads spend',
|
|
98
|
+
window: '30d',
|
|
99
|
+
metric: defineMetric({
|
|
100
|
+
connector: metaAds,
|
|
101
|
+
shape: 'metric',
|
|
102
|
+
name: 'meta_campaign_insights',
|
|
103
|
+
field: 'spend',
|
|
104
|
+
fn: 'sum',
|
|
105
|
+
}),
|
|
106
|
+
},
|
|
107
|
+
},
|
|
108
|
+
}),
|
|
109
|
+
},
|
|
110
|
+
});
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Rate limits
|
|
114
|
+
|
|
115
|
+
Meta enforces per-app and per-ad-account budgets surfaced through the `X-Business-Use-Case-Usage` header. Sync at most every few hours per ad account; very large accounts may need a daily cadence.
|
|
116
|
+
|
|
117
|
+
## Limitations
|
|
118
|
+
|
|
119
|
+
- Insights are always fetched at daily granularity. Sub-daily breakdowns are not supported.
|
|
120
|
+
- Insights for the most recent 30 days are re-fetched on every incremental sync because Meta keeps attributing conversions after the event date.
|
|
121
|
+
- Creative-level breakdowns (publisher_platform, placement, demographics) are intentionally out of scope to keep the metric cardinality bounded.
|
|
122
|
+
|
|
123
|
+
## Links
|
|
124
|
+
|
|
125
|
+
- [Rawdash docs](https://rawdash.dev/docs/connectors/)
|
|
126
|
+
- [Meta API docs](https://developers.facebook.com/docs/marketing-api/insights)
|
|
127
|
+
- [GitHub](https://github.com/rawdash/rawdash)
|
|
128
|
+
|
|
129
|
+
## License
|
|
130
|
+
|
|
131
|
+
Apache-2.0
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
import { BaseConnector, ConnectorContext, SyncOptions, StorageHandle, SyncResult, ConnectorDoc } from '@rawdash/core';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
declare const configFields: z.ZodObject<{
|
|
5
|
+
adAccountId: z.ZodString;
|
|
6
|
+
accessToken: z.ZodObject<{
|
|
7
|
+
$secret: z.ZodString;
|
|
8
|
+
}, z.core.$strip>;
|
|
9
|
+
apiVersion: z.ZodOptional<z.ZodString>;
|
|
10
|
+
lookbackDays: z.ZodOptional<z.ZodNumber>;
|
|
11
|
+
resources: z.ZodOptional<z.ZodArray<z.ZodEnum<{
|
|
12
|
+
campaigns: "campaigns";
|
|
13
|
+
campaign_insights: "campaign_insights";
|
|
14
|
+
adset_insights: "adset_insights";
|
|
15
|
+
ad_insights: "ad_insights";
|
|
16
|
+
}>>>;
|
|
17
|
+
}, z.core.$strip>;
|
|
18
|
+
declare const doc: ConnectorDoc;
|
|
19
|
+
interface MetaAdsSettings {
|
|
20
|
+
adAccountId: string;
|
|
21
|
+
apiVersion?: string;
|
|
22
|
+
lookbackDays?: number;
|
|
23
|
+
resources?: readonly MetaAdsResource[];
|
|
24
|
+
}
|
|
25
|
+
declare const metaAdsCredentials: {
|
|
26
|
+
accessToken: {
|
|
27
|
+
description: string;
|
|
28
|
+
auth: "required";
|
|
29
|
+
};
|
|
30
|
+
};
|
|
31
|
+
type MetaAdsCredentials = typeof metaAdsCredentials;
|
|
32
|
+
declare const PHASE_ORDER: readonly ["campaigns", "campaign_insights", "adset_insights", "ad_insights"];
|
|
33
|
+
type MetaAdsPhase = (typeof PHASE_ORDER)[number];
|
|
34
|
+
type MetaAdsResource = MetaAdsPhase;
|
|
35
|
+
interface MetaActionEntry {
|
|
36
|
+
action_type?: string;
|
|
37
|
+
value?: string | number;
|
|
38
|
+
}
|
|
39
|
+
interface MetaCampaign {
|
|
40
|
+
id: string;
|
|
41
|
+
name?: string | null;
|
|
42
|
+
objective?: string | null;
|
|
43
|
+
status?: string | null;
|
|
44
|
+
effective_status?: string | null;
|
|
45
|
+
daily_budget?: string | number | null;
|
|
46
|
+
lifetime_budget?: string | number | null;
|
|
47
|
+
created_time?: string | null;
|
|
48
|
+
updated_time?: string | null;
|
|
49
|
+
}
|
|
50
|
+
interface MetaInsightsBase {
|
|
51
|
+
date_start: string;
|
|
52
|
+
date_stop?: string;
|
|
53
|
+
impressions?: string | number;
|
|
54
|
+
clicks?: string | number;
|
|
55
|
+
spend?: string | number;
|
|
56
|
+
reach?: string | number;
|
|
57
|
+
actions?: MetaActionEntry[];
|
|
58
|
+
action_values?: MetaActionEntry[];
|
|
59
|
+
}
|
|
60
|
+
interface MetaCampaignInsight extends MetaInsightsBase {
|
|
61
|
+
campaign_id: string;
|
|
62
|
+
campaign_name?: string | null;
|
|
63
|
+
}
|
|
64
|
+
interface MetaAdsetInsight extends MetaCampaignInsight {
|
|
65
|
+
adset_id: string;
|
|
66
|
+
adset_name?: string | null;
|
|
67
|
+
}
|
|
68
|
+
interface MetaAdInsight extends MetaAdsetInsight {
|
|
69
|
+
ad_id: string;
|
|
70
|
+
ad_name?: string | null;
|
|
71
|
+
}
|
|
72
|
+
declare function campaignToEntity(row: MetaCampaign): {
|
|
73
|
+
type: string;
|
|
74
|
+
id: string;
|
|
75
|
+
attributes: Record<string, string | number | null>;
|
|
76
|
+
updated_at: number;
|
|
77
|
+
};
|
|
78
|
+
declare function insightRowToMetricSample(row: MetaCampaignInsight | MetaAdsetInsight | MetaAdInsight, phase: 'campaign_insights' | 'adset_insights' | 'ad_insights'): {
|
|
79
|
+
name: string;
|
|
80
|
+
ts: number;
|
|
81
|
+
value: number;
|
|
82
|
+
attributes: Record<string, string | number | null>;
|
|
83
|
+
};
|
|
84
|
+
declare class MetaAdsConnector extends BaseConnector<MetaAdsSettings, MetaAdsCredentials> {
|
|
85
|
+
static readonly id = "meta-ads";
|
|
86
|
+
static readonly resources: {
|
|
87
|
+
readonly meta_campaign: {
|
|
88
|
+
readonly shape: "entity";
|
|
89
|
+
readonly description: "Meta ad campaigns with name, objective, status, and budget. Upserted by id; one row per campaign in the ad account.";
|
|
90
|
+
readonly endpoint: "GET /{ad_account_id}/campaigns";
|
|
91
|
+
readonly responses: {
|
|
92
|
+
readonly campaigns: z.ZodArray<z.ZodObject<{
|
|
93
|
+
id: z.ZodString;
|
|
94
|
+
name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
95
|
+
objective: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
96
|
+
status: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
97
|
+
effective_status: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
98
|
+
daily_budget: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
|
|
99
|
+
lifetime_budget: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
|
|
100
|
+
created_time: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
101
|
+
updated_time: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
102
|
+
}, z.core.$strip>>;
|
|
103
|
+
};
|
|
104
|
+
};
|
|
105
|
+
readonly meta_campaign_insights: {
|
|
106
|
+
readonly shape: "metric";
|
|
107
|
+
readonly description: "Daily campaign-level Meta Ads insights - spend (primary value), impressions, clicks, reach, conversions, and conversion value bucketed by campaign.";
|
|
108
|
+
readonly endpoint: "GET /{ad_account_id}/insights?level=campaign&time_increment=1";
|
|
109
|
+
readonly unit: "spend";
|
|
110
|
+
readonly granularity: "day";
|
|
111
|
+
readonly notes: "Primary value is `spend`. `conversions` is the sum of every entry in the upstream `actions` array; `conversion_value` is the sum of every entry in `action_values`.";
|
|
112
|
+
readonly dimensions: [{
|
|
113
|
+
readonly name: "date";
|
|
114
|
+
readonly description: "Calendar day of the metric sample (UTC).";
|
|
115
|
+
}, {
|
|
116
|
+
readonly name: "campaignId";
|
|
117
|
+
readonly description: "Meta campaign id.";
|
|
118
|
+
}, {
|
|
119
|
+
readonly name: "campaignName";
|
|
120
|
+
readonly description: "Meta campaign name.";
|
|
121
|
+
}, {
|
|
122
|
+
readonly name: "impressions";
|
|
123
|
+
readonly description: "Total impressions on the day.";
|
|
124
|
+
}, {
|
|
125
|
+
readonly name: "clicks";
|
|
126
|
+
readonly description: "Total clicks on the day.";
|
|
127
|
+
}, {
|
|
128
|
+
readonly name: "spend";
|
|
129
|
+
readonly description: "Total spend (account currency).";
|
|
130
|
+
}, {
|
|
131
|
+
readonly name: "reach";
|
|
132
|
+
readonly description: "Unique reach on the day.";
|
|
133
|
+
}, {
|
|
134
|
+
readonly name: "conversions";
|
|
135
|
+
readonly description: "Total attributed actions.";
|
|
136
|
+
}, {
|
|
137
|
+
readonly name: "conversion_value";
|
|
138
|
+
readonly description: "Total attributed action value (account currency).";
|
|
139
|
+
}];
|
|
140
|
+
readonly responses: {
|
|
141
|
+
readonly campaign_insights: z.ZodArray<z.ZodObject<{
|
|
142
|
+
campaign_id: z.ZodString;
|
|
143
|
+
campaign_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
144
|
+
date_start: z.ZodString;
|
|
145
|
+
date_stop: z.ZodOptional<z.ZodString>;
|
|
146
|
+
impressions: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
147
|
+
clicks: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
148
|
+
spend: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
149
|
+
reach: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
150
|
+
actions: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
151
|
+
action_type: z.ZodOptional<z.ZodString>;
|
|
152
|
+
value: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
153
|
+
}, z.core.$strip>>>;
|
|
154
|
+
action_values: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
155
|
+
action_type: z.ZodOptional<z.ZodString>;
|
|
156
|
+
value: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
157
|
+
}, z.core.$strip>>>;
|
|
158
|
+
}, z.core.$strip>>;
|
|
159
|
+
};
|
|
160
|
+
};
|
|
161
|
+
readonly meta_adset_insights: {
|
|
162
|
+
readonly shape: "metric";
|
|
163
|
+
readonly description: "Daily adset-level Meta Ads insights - same fields as the campaign roll-up, bucketed by adset.";
|
|
164
|
+
readonly endpoint: "GET /{ad_account_id}/insights?level=adset&time_increment=1";
|
|
165
|
+
readonly unit: "spend";
|
|
166
|
+
readonly granularity: "day";
|
|
167
|
+
readonly notes: "Primary value is `spend`. Includes campaign_id/campaign_name so adset rows are easy to roll up to their parent campaign.";
|
|
168
|
+
readonly dimensions: [{
|
|
169
|
+
readonly name: "date";
|
|
170
|
+
readonly description: "Calendar day of the metric sample (UTC).";
|
|
171
|
+
}, {
|
|
172
|
+
readonly name: "campaignId";
|
|
173
|
+
readonly description: "Parent campaign id.";
|
|
174
|
+
}, {
|
|
175
|
+
readonly name: "campaignName";
|
|
176
|
+
readonly description: "Parent campaign name.";
|
|
177
|
+
}, {
|
|
178
|
+
readonly name: "adsetId";
|
|
179
|
+
readonly description: "Meta adset id.";
|
|
180
|
+
}, {
|
|
181
|
+
readonly name: "adsetName";
|
|
182
|
+
readonly description: "Meta adset name.";
|
|
183
|
+
}, {
|
|
184
|
+
readonly name: "impressions";
|
|
185
|
+
readonly description: "Total impressions on the day.";
|
|
186
|
+
}, {
|
|
187
|
+
readonly name: "clicks";
|
|
188
|
+
readonly description: "Total clicks on the day.";
|
|
189
|
+
}, {
|
|
190
|
+
readonly name: "spend";
|
|
191
|
+
readonly description: "Total spend (account currency).";
|
|
192
|
+
}, {
|
|
193
|
+
readonly name: "reach";
|
|
194
|
+
readonly description: "Unique reach on the day.";
|
|
195
|
+
}, {
|
|
196
|
+
readonly name: "conversions";
|
|
197
|
+
readonly description: "Total attributed actions.";
|
|
198
|
+
}, {
|
|
199
|
+
readonly name: "conversion_value";
|
|
200
|
+
readonly description: "Total attributed action value (account currency).";
|
|
201
|
+
}];
|
|
202
|
+
readonly responses: {
|
|
203
|
+
readonly adset_insights: z.ZodArray<z.ZodObject<{
|
|
204
|
+
campaign_id: z.ZodString;
|
|
205
|
+
campaign_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
206
|
+
adset_id: z.ZodString;
|
|
207
|
+
adset_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
208
|
+
date_start: z.ZodString;
|
|
209
|
+
date_stop: z.ZodOptional<z.ZodString>;
|
|
210
|
+
impressions: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
211
|
+
clicks: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
212
|
+
spend: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
213
|
+
reach: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
214
|
+
actions: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
215
|
+
action_type: z.ZodOptional<z.ZodString>;
|
|
216
|
+
value: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
217
|
+
}, z.core.$strip>>>;
|
|
218
|
+
action_values: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
219
|
+
action_type: z.ZodOptional<z.ZodString>;
|
|
220
|
+
value: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
221
|
+
}, z.core.$strip>>>;
|
|
222
|
+
}, z.core.$strip>>;
|
|
223
|
+
};
|
|
224
|
+
};
|
|
225
|
+
readonly meta_ad_insights: {
|
|
226
|
+
readonly shape: "metric";
|
|
227
|
+
readonly description: "Daily ad-level Meta Ads insights - same fields as the adset roll-up, bucketed by ad.";
|
|
228
|
+
readonly endpoint: "GET /{ad_account_id}/insights?level=ad&time_increment=1";
|
|
229
|
+
readonly unit: "spend";
|
|
230
|
+
readonly granularity: "day";
|
|
231
|
+
readonly notes: "Primary value is `spend`. Cardinality is the highest of the three insights resources - opt in via `resources: [..., \"ad_insights\"]` only when you need per-ad breakdowns.";
|
|
232
|
+
readonly dimensions: [{
|
|
233
|
+
readonly name: "date";
|
|
234
|
+
readonly description: "Calendar day of the metric sample (UTC).";
|
|
235
|
+
}, {
|
|
236
|
+
readonly name: "campaignId";
|
|
237
|
+
readonly description: "Parent campaign id.";
|
|
238
|
+
}, {
|
|
239
|
+
readonly name: "campaignName";
|
|
240
|
+
readonly description: "Parent campaign name.";
|
|
241
|
+
}, {
|
|
242
|
+
readonly name: "adsetId";
|
|
243
|
+
readonly description: "Parent adset id.";
|
|
244
|
+
}, {
|
|
245
|
+
readonly name: "adsetName";
|
|
246
|
+
readonly description: "Parent adset name.";
|
|
247
|
+
}, {
|
|
248
|
+
readonly name: "adId";
|
|
249
|
+
readonly description: "Meta ad id.";
|
|
250
|
+
}, {
|
|
251
|
+
readonly name: "adName";
|
|
252
|
+
readonly description: "Meta ad name.";
|
|
253
|
+
}, {
|
|
254
|
+
readonly name: "impressions";
|
|
255
|
+
readonly description: "Total impressions on the day.";
|
|
256
|
+
}, {
|
|
257
|
+
readonly name: "clicks";
|
|
258
|
+
readonly description: "Total clicks on the day.";
|
|
259
|
+
}, {
|
|
260
|
+
readonly name: "spend";
|
|
261
|
+
readonly description: "Total spend (account currency).";
|
|
262
|
+
}, {
|
|
263
|
+
readonly name: "reach";
|
|
264
|
+
readonly description: "Unique reach on the day.";
|
|
265
|
+
}, {
|
|
266
|
+
readonly name: "conversions";
|
|
267
|
+
readonly description: "Total attributed actions.";
|
|
268
|
+
}, {
|
|
269
|
+
readonly name: "conversion_value";
|
|
270
|
+
readonly description: "Total attributed action value (account currency).";
|
|
271
|
+
}];
|
|
272
|
+
readonly responses: {
|
|
273
|
+
readonly ad_insights: z.ZodArray<z.ZodObject<{
|
|
274
|
+
campaign_id: z.ZodString;
|
|
275
|
+
campaign_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
276
|
+
adset_id: z.ZodString;
|
|
277
|
+
adset_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
278
|
+
ad_id: z.ZodString;
|
|
279
|
+
ad_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
280
|
+
date_start: z.ZodString;
|
|
281
|
+
date_stop: z.ZodOptional<z.ZodString>;
|
|
282
|
+
impressions: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
283
|
+
clicks: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
284
|
+
spend: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
285
|
+
reach: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
286
|
+
actions: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
287
|
+
action_type: z.ZodOptional<z.ZodString>;
|
|
288
|
+
value: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
289
|
+
}, z.core.$strip>>>;
|
|
290
|
+
action_values: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
291
|
+
action_type: z.ZodOptional<z.ZodString>;
|
|
292
|
+
value: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
293
|
+
}, z.core.$strip>>>;
|
|
294
|
+
}, z.core.$strip>>;
|
|
295
|
+
};
|
|
296
|
+
};
|
|
297
|
+
};
|
|
298
|
+
static readonly schemas: {
|
|
299
|
+
readonly campaigns: z.ZodArray<z.ZodObject<{
|
|
300
|
+
id: z.ZodString;
|
|
301
|
+
name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
302
|
+
objective: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
303
|
+
status: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
304
|
+
effective_status: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
305
|
+
daily_budget: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
|
|
306
|
+
lifetime_budget: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
|
|
307
|
+
created_time: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
308
|
+
updated_time: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
309
|
+
}, z.core.$strip>>;
|
|
310
|
+
} & {
|
|
311
|
+
readonly campaign_insights: z.ZodArray<z.ZodObject<{
|
|
312
|
+
campaign_id: z.ZodString;
|
|
313
|
+
campaign_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
314
|
+
date_start: z.ZodString;
|
|
315
|
+
date_stop: z.ZodOptional<z.ZodString>;
|
|
316
|
+
impressions: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
317
|
+
clicks: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
318
|
+
spend: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
319
|
+
reach: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
320
|
+
actions: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
321
|
+
action_type: z.ZodOptional<z.ZodString>;
|
|
322
|
+
value: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
323
|
+
}, z.core.$strip>>>;
|
|
324
|
+
action_values: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
325
|
+
action_type: z.ZodOptional<z.ZodString>;
|
|
326
|
+
value: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
327
|
+
}, z.core.$strip>>>;
|
|
328
|
+
}, z.core.$strip>>;
|
|
329
|
+
} & {
|
|
330
|
+
readonly adset_insights: z.ZodArray<z.ZodObject<{
|
|
331
|
+
campaign_id: z.ZodString;
|
|
332
|
+
campaign_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
333
|
+
adset_id: z.ZodString;
|
|
334
|
+
adset_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
335
|
+
date_start: z.ZodString;
|
|
336
|
+
date_stop: z.ZodOptional<z.ZodString>;
|
|
337
|
+
impressions: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
338
|
+
clicks: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
339
|
+
spend: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
340
|
+
reach: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
341
|
+
actions: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
342
|
+
action_type: z.ZodOptional<z.ZodString>;
|
|
343
|
+
value: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
344
|
+
}, z.core.$strip>>>;
|
|
345
|
+
action_values: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
346
|
+
action_type: z.ZodOptional<z.ZodString>;
|
|
347
|
+
value: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
348
|
+
}, z.core.$strip>>>;
|
|
349
|
+
}, z.core.$strip>>;
|
|
350
|
+
} & {
|
|
351
|
+
readonly ad_insights: z.ZodArray<z.ZodObject<{
|
|
352
|
+
campaign_id: z.ZodString;
|
|
353
|
+
campaign_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
354
|
+
adset_id: z.ZodString;
|
|
355
|
+
adset_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
356
|
+
ad_id: z.ZodString;
|
|
357
|
+
ad_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
358
|
+
date_start: z.ZodString;
|
|
359
|
+
date_stop: z.ZodOptional<z.ZodString>;
|
|
360
|
+
impressions: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
361
|
+
clicks: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
362
|
+
spend: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
363
|
+
reach: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
364
|
+
actions: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
365
|
+
action_type: z.ZodOptional<z.ZodString>;
|
|
366
|
+
value: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
367
|
+
}, z.core.$strip>>>;
|
|
368
|
+
action_values: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
369
|
+
action_type: z.ZodOptional<z.ZodString>;
|
|
370
|
+
value: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
371
|
+
}, z.core.$strip>>>;
|
|
372
|
+
}, z.core.$strip>>;
|
|
373
|
+
} & Readonly<Record<string, z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>>>;
|
|
374
|
+
static create(input: unknown, ctx?: ConnectorContext): MetaAdsConnector;
|
|
375
|
+
readonly id = "meta-ads";
|
|
376
|
+
readonly credentials: {
|
|
377
|
+
accessToken: {
|
|
378
|
+
description: string;
|
|
379
|
+
auth: "required";
|
|
380
|
+
};
|
|
381
|
+
};
|
|
382
|
+
private buildHeaders;
|
|
383
|
+
private apiVersion;
|
|
384
|
+
private accountBase;
|
|
385
|
+
private fetchCampaignsPage;
|
|
386
|
+
private fetchInsightsPage;
|
|
387
|
+
private writeCampaigns;
|
|
388
|
+
private writeInsights;
|
|
389
|
+
private clearScopeOnFirstPage;
|
|
390
|
+
sync(options: SyncOptions, storage: StorageHandle, signal?: AbortSignal): Promise<SyncResult>;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
export { type MetaActionEntry, type MetaAdInsight, MetaAdsConnector, type MetaAdsResource, type MetaAdsSettings, type MetaAdsetInsight, type MetaCampaign, type MetaCampaignInsight, campaignToEntity, configFields, MetaAdsConnector as default, doc, insightRowToMetricSample };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,553 @@
|
|
|
1
|
+
// ../../connector-shared/dist/index.js
|
|
2
|
+
var HTTP_CLIENT_VERSION = "0.0.0";
|
|
3
|
+
var DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;
|
|
4
|
+
function connectorUserAgent(connectorId) {
|
|
5
|
+
return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
// src/meta-ads.ts
|
|
9
|
+
import {
|
|
10
|
+
BaseConnector,
|
|
11
|
+
defineConfigFields,
|
|
12
|
+
defineConnectorDoc,
|
|
13
|
+
defineResources,
|
|
14
|
+
makeChunkedCursorGuard,
|
|
15
|
+
paginateChunked,
|
|
16
|
+
schemasFromResources,
|
|
17
|
+
selectActivePhases
|
|
18
|
+
} from "@rawdash/core";
|
|
19
|
+
import { z } from "zod";
|
|
20
|
+
var configFields = defineConfigFields(
|
|
21
|
+
z.object({
|
|
22
|
+
adAccountId: z.string().trim().regex(
|
|
23
|
+
/^act_\d+$/,
|
|
24
|
+
"Ad account ID must look like `act_<digits>` (e.g. `act_1234567890`)"
|
|
25
|
+
).meta({
|
|
26
|
+
label: "Ad account ID",
|
|
27
|
+
description: "Meta Marketing API ad account ID. Find it in Ads Manager \u2192 Settings \u2192 Account info; it always starts with `act_`.",
|
|
28
|
+
placeholder: "act_1234567890"
|
|
29
|
+
}),
|
|
30
|
+
accessToken: z.object({ $secret: z.string() }).meta({
|
|
31
|
+
label: "System user access token",
|
|
32
|
+
description: "Long-lived System User access token from Meta Business Manager with `ads_read` (and, for newer accounts, `read_insights`) scopes on the chosen ad account.",
|
|
33
|
+
placeholder: "EAAB...",
|
|
34
|
+
secret: true
|
|
35
|
+
}),
|
|
36
|
+
apiVersion: z.string().regex(/^v\d+\.\d+$/, "API version must look like `v21.0`").optional().meta({
|
|
37
|
+
label: "Graph API version",
|
|
38
|
+
description: "Pin a specific Meta Graph API version (e.g. `v21.0`). Defaults to `v21.0`.",
|
|
39
|
+
placeholder: "v21.0"
|
|
40
|
+
}),
|
|
41
|
+
lookbackDays: z.number().int().positive().optional().meta({
|
|
42
|
+
label: "Lookback days (full sync)",
|
|
43
|
+
description: "How many calendar days of insights to fetch on a full sync. Defaults to 90.",
|
|
44
|
+
placeholder: "90"
|
|
45
|
+
}),
|
|
46
|
+
resources: z.array(
|
|
47
|
+
z.enum([
|
|
48
|
+
"campaigns",
|
|
49
|
+
"campaign_insights",
|
|
50
|
+
"adset_insights",
|
|
51
|
+
"ad_insights"
|
|
52
|
+
])
|
|
53
|
+
).nonempty().optional().meta({
|
|
54
|
+
label: "Resources",
|
|
55
|
+
description: "Which Meta resources to sync. Omit to sync all. Ad-level insights are the most expensive - leave them out if you only need campaign or adset rollups."
|
|
56
|
+
})
|
|
57
|
+
})
|
|
58
|
+
);
|
|
59
|
+
var doc = defineConnectorDoc({
|
|
60
|
+
displayName: "Meta Ads",
|
|
61
|
+
category: "marketing",
|
|
62
|
+
brandColor: "#0866FF",
|
|
63
|
+
tagline: "Sync Meta (Facebook + Instagram) ad campaigns plus daily campaign, adset, and ad-level insights - spend, impressions, clicks, reach, conversions, and conversion value.",
|
|
64
|
+
vendor: {
|
|
65
|
+
name: "Meta",
|
|
66
|
+
apiDocs: "https://developers.facebook.com/docs/marketing-api/insights",
|
|
67
|
+
website: "https://business.facebook.com"
|
|
68
|
+
},
|
|
69
|
+
auth: {
|
|
70
|
+
summary: "A long-lived System User access token from Meta Business Manager, scoped with `ads_read` (and `read_insights` on newer accounts) for the target ad account.",
|
|
71
|
+
setup: [
|
|
72
|
+
"In Meta Business Manager \u2192 Business Settings \u2192 Users \u2192 System Users, create a System User (or reuse an existing one) and assign it to the ad account with at least the Advertiser role.",
|
|
73
|
+
"Generate a System User access token for the System User; pick `ads_read` and (where available) `read_insights` as the scopes. Choose the longest available expiry - System User tokens can be made effectively non-expiring.",
|
|
74
|
+
"Find the ad account ID in Ads Manager \u2192 Settings \u2192 Account info; it always starts with `act_`.",
|
|
75
|
+
'Store the token as a secret and reference it from the connector config as `accessToken: secret("META_ACCESS_TOKEN")` alongside `adAccountId: "act_<id>"`.'
|
|
76
|
+
]
|
|
77
|
+
},
|
|
78
|
+
rateLimit: "Meta enforces per-app and per-ad-account budgets surfaced through the `X-Business-Use-Case-Usage` header. Sync at most every few hours per ad account; very large accounts may need a daily cadence.",
|
|
79
|
+
limitations: [
|
|
80
|
+
"Insights are always fetched at daily granularity. Sub-daily breakdowns are not supported.",
|
|
81
|
+
"Insights for the most recent 30 days are re-fetched on every incremental sync because Meta keeps attributing conversions after the event date.",
|
|
82
|
+
"Creative-level breakdowns (publisher_platform, placement, demographics) are intentionally out of scope to keep the metric cardinality bounded."
|
|
83
|
+
]
|
|
84
|
+
});
|
|
85
|
+
var metaAdsCredentials = {
|
|
86
|
+
accessToken: {
|
|
87
|
+
description: "Meta System User access token",
|
|
88
|
+
auth: "required"
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
var PHASE_ORDER = [
|
|
92
|
+
"campaigns",
|
|
93
|
+
"campaign_insights",
|
|
94
|
+
"adset_insights",
|
|
95
|
+
"ad_insights"
|
|
96
|
+
];
|
|
97
|
+
var isMetaAdsSyncCursor = makeChunkedCursorGuard(PHASE_ORDER);
|
|
98
|
+
var DEFAULT_API_VERSION = "v21.0";
|
|
99
|
+
var BASE_URL = "https://graph.facebook.com";
|
|
100
|
+
var PAGE_LIMIT = 100;
|
|
101
|
+
var MS_PER_DAY = 24 * 60 * 60 * 1e3;
|
|
102
|
+
var DEFAULT_LOOKBACK_DAYS = 90;
|
|
103
|
+
var INCREMENTAL_LOOKBACK_DAYS = 30;
|
|
104
|
+
var INSIGHTS_PHASES = /* @__PURE__ */ new Set([
|
|
105
|
+
"campaign_insights",
|
|
106
|
+
"adset_insights",
|
|
107
|
+
"ad_insights"
|
|
108
|
+
]);
|
|
109
|
+
var PHASE_TO_LEVEL = {
|
|
110
|
+
campaign_insights: "campaign",
|
|
111
|
+
adset_insights: "adset",
|
|
112
|
+
ad_insights: "ad"
|
|
113
|
+
};
|
|
114
|
+
var METRIC_NAME = {
|
|
115
|
+
campaigns: "meta_campaign",
|
|
116
|
+
campaign_insights: "meta_campaign_insights",
|
|
117
|
+
adset_insights: "meta_adset_insights",
|
|
118
|
+
ad_insights: "meta_ad_insights"
|
|
119
|
+
};
|
|
120
|
+
var CAMPAIGN_ENTITY_TYPE = "meta_campaign";
|
|
121
|
+
function toMetaDate(date) {
|
|
122
|
+
const y = date.getUTCFullYear();
|
|
123
|
+
const m = String(date.getUTCMonth() + 1).padStart(2, "0");
|
|
124
|
+
const d = String(date.getUTCDate()).padStart(2, "0");
|
|
125
|
+
return `${y}-${m}-${d}`;
|
|
126
|
+
}
|
|
127
|
+
function metaDateToMs(metaDate) {
|
|
128
|
+
const [y, m, d] = metaDate.split("-").map((part) => Number(part));
|
|
129
|
+
if (!Number.isFinite(y) || !Number.isFinite(m) || !Number.isFinite(d) || y === void 0 || m === void 0 || d === void 0) {
|
|
130
|
+
return 0;
|
|
131
|
+
}
|
|
132
|
+
return Date.UTC(y, m - 1, d);
|
|
133
|
+
}
|
|
134
|
+
function getDateRange(options, lookbackDays) {
|
|
135
|
+
const now = Date.now();
|
|
136
|
+
const until = toMetaDate(new Date(now));
|
|
137
|
+
if (options.mode === "latest" && options.since) {
|
|
138
|
+
const startMs2 = now - (INCREMENTAL_LOOKBACK_DAYS - 1) * MS_PER_DAY;
|
|
139
|
+
return { since: toMetaDate(new Date(startMs2)), until };
|
|
140
|
+
}
|
|
141
|
+
if (options.since) {
|
|
142
|
+
const sinceMs = new Date(options.since).getTime();
|
|
143
|
+
if (Number.isFinite(sinceMs)) {
|
|
144
|
+
const days = Math.max(1, Math.ceil((now - sinceMs) / MS_PER_DAY));
|
|
145
|
+
const cappedDays = Math.min(days, lookbackDays);
|
|
146
|
+
const startMs2 = now - (cappedDays - 1) * MS_PER_DAY;
|
|
147
|
+
return { since: toMetaDate(new Date(startMs2)), until };
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const startMs = now - (lookbackDays - 1) * MS_PER_DAY;
|
|
151
|
+
return { since: toMetaDate(new Date(startMs)), until };
|
|
152
|
+
}
|
|
153
|
+
function parseNumber(value) {
|
|
154
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
155
|
+
return value;
|
|
156
|
+
}
|
|
157
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
158
|
+
const n = Number(value);
|
|
159
|
+
return Number.isFinite(n) ? n : 0;
|
|
160
|
+
}
|
|
161
|
+
return 0;
|
|
162
|
+
}
|
|
163
|
+
function parseOptionalNumber(value) {
|
|
164
|
+
if (value === null || value === void 0) {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
168
|
+
return value;
|
|
169
|
+
}
|
|
170
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
171
|
+
const n = Number(value);
|
|
172
|
+
return Number.isFinite(n) ? n : null;
|
|
173
|
+
}
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
function sumActionValues(entries) {
|
|
177
|
+
if (!entries) {
|
|
178
|
+
return 0;
|
|
179
|
+
}
|
|
180
|
+
let total = 0;
|
|
181
|
+
for (const entry of entries) {
|
|
182
|
+
total += parseNumber(entry.value);
|
|
183
|
+
}
|
|
184
|
+
return total;
|
|
185
|
+
}
|
|
186
|
+
var actionEntrySchema = z.object({
|
|
187
|
+
action_type: z.string().optional(),
|
|
188
|
+
value: z.union([z.string(), z.number()]).optional()
|
|
189
|
+
});
|
|
190
|
+
var campaignSchema = z.object({
|
|
191
|
+
id: z.string().min(1),
|
|
192
|
+
name: z.string().nullish(),
|
|
193
|
+
objective: z.string().nullish(),
|
|
194
|
+
status: z.string().nullish(),
|
|
195
|
+
effective_status: z.string().nullish(),
|
|
196
|
+
daily_budget: z.union([z.string(), z.number()]).nullish(),
|
|
197
|
+
lifetime_budget: z.union([z.string(), z.number()]).nullish(),
|
|
198
|
+
created_time: z.string().nullish(),
|
|
199
|
+
updated_time: z.string().nullish()
|
|
200
|
+
});
|
|
201
|
+
var insightsBaseShape = {
|
|
202
|
+
date_start: z.string(),
|
|
203
|
+
date_stop: z.string().optional(),
|
|
204
|
+
impressions: z.union([z.string(), z.number()]).optional(),
|
|
205
|
+
clicks: z.union([z.string(), z.number()]).optional(),
|
|
206
|
+
spend: z.union([z.string(), z.number()]).optional(),
|
|
207
|
+
reach: z.union([z.string(), z.number()]).optional(),
|
|
208
|
+
actions: z.array(actionEntrySchema).optional(),
|
|
209
|
+
action_values: z.array(actionEntrySchema).optional()
|
|
210
|
+
};
|
|
211
|
+
var campaignInsightSchema = z.object({
|
|
212
|
+
...insightsBaseShape,
|
|
213
|
+
campaign_id: z.string().min(1),
|
|
214
|
+
campaign_name: z.string().nullish()
|
|
215
|
+
});
|
|
216
|
+
var adsetInsightSchema = z.object({
|
|
217
|
+
...insightsBaseShape,
|
|
218
|
+
campaign_id: z.string().min(1),
|
|
219
|
+
campaign_name: z.string().nullish(),
|
|
220
|
+
adset_id: z.string().min(1),
|
|
221
|
+
adset_name: z.string().nullish()
|
|
222
|
+
});
|
|
223
|
+
var adInsightSchema = z.object({
|
|
224
|
+
...insightsBaseShape,
|
|
225
|
+
campaign_id: z.string().min(1),
|
|
226
|
+
campaign_name: z.string().nullish(),
|
|
227
|
+
adset_id: z.string().min(1),
|
|
228
|
+
adset_name: z.string().nullish(),
|
|
229
|
+
ad_id: z.string().min(1),
|
|
230
|
+
ad_name: z.string().nullish()
|
|
231
|
+
});
|
|
232
|
+
var campaignsSchema = z.array(campaignSchema);
|
|
233
|
+
var campaignInsightsSchema = z.array(campaignInsightSchema);
|
|
234
|
+
var adsetInsightsSchema = z.array(adsetInsightSchema);
|
|
235
|
+
var adInsightsSchema = z.array(adInsightSchema);
|
|
236
|
+
var metaAdsResources = defineResources({
|
|
237
|
+
meta_campaign: {
|
|
238
|
+
shape: "entity",
|
|
239
|
+
description: "Meta ad campaigns with name, objective, status, and budget. Upserted by id; one row per campaign in the ad account.",
|
|
240
|
+
endpoint: "GET /{ad_account_id}/campaigns",
|
|
241
|
+
responses: { campaigns: campaignsSchema }
|
|
242
|
+
},
|
|
243
|
+
meta_campaign_insights: {
|
|
244
|
+
shape: "metric",
|
|
245
|
+
description: "Daily campaign-level Meta Ads insights - spend (primary value), impressions, clicks, reach, conversions, and conversion value bucketed by campaign.",
|
|
246
|
+
endpoint: "GET /{ad_account_id}/insights?level=campaign&time_increment=1",
|
|
247
|
+
unit: "spend",
|
|
248
|
+
granularity: "day",
|
|
249
|
+
notes: "Primary value is `spend`. `conversions` is the sum of every entry in the upstream `actions` array; `conversion_value` is the sum of every entry in `action_values`.",
|
|
250
|
+
dimensions: [
|
|
251
|
+
{ name: "date", description: "Calendar day of the metric sample (UTC)." },
|
|
252
|
+
{ name: "campaignId", description: "Meta campaign id." },
|
|
253
|
+
{ name: "campaignName", description: "Meta campaign name." },
|
|
254
|
+
{ name: "impressions", description: "Total impressions on the day." },
|
|
255
|
+
{ name: "clicks", description: "Total clicks on the day." },
|
|
256
|
+
{ name: "spend", description: "Total spend (account currency)." },
|
|
257
|
+
{ name: "reach", description: "Unique reach on the day." },
|
|
258
|
+
{ name: "conversions", description: "Total attributed actions." },
|
|
259
|
+
{
|
|
260
|
+
name: "conversion_value",
|
|
261
|
+
description: "Total attributed action value (account currency)."
|
|
262
|
+
}
|
|
263
|
+
],
|
|
264
|
+
responses: { campaign_insights: campaignInsightsSchema }
|
|
265
|
+
},
|
|
266
|
+
meta_adset_insights: {
|
|
267
|
+
shape: "metric",
|
|
268
|
+
description: "Daily adset-level Meta Ads insights - same fields as the campaign roll-up, bucketed by adset.",
|
|
269
|
+
endpoint: "GET /{ad_account_id}/insights?level=adset&time_increment=1",
|
|
270
|
+
unit: "spend",
|
|
271
|
+
granularity: "day",
|
|
272
|
+
notes: "Primary value is `spend`. Includes campaign_id/campaign_name so adset rows are easy to roll up to their parent campaign.",
|
|
273
|
+
dimensions: [
|
|
274
|
+
{ name: "date", description: "Calendar day of the metric sample (UTC)." },
|
|
275
|
+
{ name: "campaignId", description: "Parent campaign id." },
|
|
276
|
+
{ name: "campaignName", description: "Parent campaign name." },
|
|
277
|
+
{ name: "adsetId", description: "Meta adset id." },
|
|
278
|
+
{ name: "adsetName", description: "Meta adset name." },
|
|
279
|
+
{ name: "impressions", description: "Total impressions on the day." },
|
|
280
|
+
{ name: "clicks", description: "Total clicks on the day." },
|
|
281
|
+
{ name: "spend", description: "Total spend (account currency)." },
|
|
282
|
+
{ name: "reach", description: "Unique reach on the day." },
|
|
283
|
+
{ name: "conversions", description: "Total attributed actions." },
|
|
284
|
+
{
|
|
285
|
+
name: "conversion_value",
|
|
286
|
+
description: "Total attributed action value (account currency)."
|
|
287
|
+
}
|
|
288
|
+
],
|
|
289
|
+
responses: { adset_insights: adsetInsightsSchema }
|
|
290
|
+
},
|
|
291
|
+
meta_ad_insights: {
|
|
292
|
+
shape: "metric",
|
|
293
|
+
description: "Daily ad-level Meta Ads insights - same fields as the adset roll-up, bucketed by ad.",
|
|
294
|
+
endpoint: "GET /{ad_account_id}/insights?level=ad&time_increment=1",
|
|
295
|
+
unit: "spend",
|
|
296
|
+
granularity: "day",
|
|
297
|
+
notes: 'Primary value is `spend`. Cardinality is the highest of the three insights resources - opt in via `resources: [..., "ad_insights"]` only when you need per-ad breakdowns.',
|
|
298
|
+
dimensions: [
|
|
299
|
+
{ name: "date", description: "Calendar day of the metric sample (UTC)." },
|
|
300
|
+
{ name: "campaignId", description: "Parent campaign id." },
|
|
301
|
+
{ name: "campaignName", description: "Parent campaign name." },
|
|
302
|
+
{ name: "adsetId", description: "Parent adset id." },
|
|
303
|
+
{ name: "adsetName", description: "Parent adset name." },
|
|
304
|
+
{ name: "adId", description: "Meta ad id." },
|
|
305
|
+
{ name: "adName", description: "Meta ad name." },
|
|
306
|
+
{ name: "impressions", description: "Total impressions on the day." },
|
|
307
|
+
{ name: "clicks", description: "Total clicks on the day." },
|
|
308
|
+
{ name: "spend", description: "Total spend (account currency)." },
|
|
309
|
+
{ name: "reach", description: "Unique reach on the day." },
|
|
310
|
+
{ name: "conversions", description: "Total attributed actions." },
|
|
311
|
+
{
|
|
312
|
+
name: "conversion_value",
|
|
313
|
+
description: "Total attributed action value (account currency)."
|
|
314
|
+
}
|
|
315
|
+
],
|
|
316
|
+
responses: { ad_insights: adInsightsSchema }
|
|
317
|
+
}
|
|
318
|
+
});
|
|
319
|
+
function campaignToEntity(row) {
|
|
320
|
+
const updatedAt = row.updated_time ? new Date(row.updated_time).getTime() : row.created_time ? new Date(row.created_time).getTime() : 0;
|
|
321
|
+
return {
|
|
322
|
+
type: CAMPAIGN_ENTITY_TYPE,
|
|
323
|
+
id: row.id,
|
|
324
|
+
attributes: {
|
|
325
|
+
name: row.name ?? null,
|
|
326
|
+
objective: row.objective ?? null,
|
|
327
|
+
status: row.status ?? null,
|
|
328
|
+
effectiveStatus: row.effective_status ?? null,
|
|
329
|
+
dailyBudget: parseOptionalNumber(row.daily_budget),
|
|
330
|
+
lifetimeBudget: parseOptionalNumber(row.lifetime_budget),
|
|
331
|
+
createdAt: row.created_time ? new Date(row.created_time).getTime() : null
|
|
332
|
+
},
|
|
333
|
+
updated_at: Number.isFinite(updatedAt) ? updatedAt : 0
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
function buildInsightAttributes(row) {
|
|
337
|
+
const impressions = parseNumber(row.impressions);
|
|
338
|
+
const clicks = parseNumber(row.clicks);
|
|
339
|
+
const spend = parseNumber(row.spend);
|
|
340
|
+
const reach = parseNumber(row.reach);
|
|
341
|
+
const conversions = (row.actions ?? []).length ? sumActionValues(row.actions) : 0;
|
|
342
|
+
const conversionValue = sumActionValues(row.action_values);
|
|
343
|
+
return {
|
|
344
|
+
date: row.date_start,
|
|
345
|
+
impressions,
|
|
346
|
+
clicks,
|
|
347
|
+
spend,
|
|
348
|
+
reach,
|
|
349
|
+
conversions,
|
|
350
|
+
conversion_value: conversionValue
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
function insightRowToMetricSample(row, phase) {
|
|
354
|
+
const attributes = buildInsightAttributes(row);
|
|
355
|
+
attributes["campaignId"] = row.campaign_id;
|
|
356
|
+
attributes["campaignName"] = row.campaign_name ?? null;
|
|
357
|
+
if (phase !== "campaign_insights") {
|
|
358
|
+
const ar = row;
|
|
359
|
+
attributes["adsetId"] = ar.adset_id;
|
|
360
|
+
attributes["adsetName"] = ar.adset_name ?? null;
|
|
361
|
+
}
|
|
362
|
+
if (phase === "ad_insights") {
|
|
363
|
+
const ar = row;
|
|
364
|
+
attributes["adId"] = ar.ad_id;
|
|
365
|
+
attributes["adName"] = ar.ad_name ?? null;
|
|
366
|
+
}
|
|
367
|
+
return {
|
|
368
|
+
name: METRIC_NAME[phase],
|
|
369
|
+
ts: metaDateToMs(row.date_start),
|
|
370
|
+
value: parseNumber(row.spend),
|
|
371
|
+
attributes
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
var CAMPAIGN_FIELDS = [
|
|
375
|
+
"id",
|
|
376
|
+
"name",
|
|
377
|
+
"objective",
|
|
378
|
+
"status",
|
|
379
|
+
"effective_status",
|
|
380
|
+
"daily_budget",
|
|
381
|
+
"lifetime_budget",
|
|
382
|
+
"created_time",
|
|
383
|
+
"updated_time"
|
|
384
|
+
].join(",");
|
|
385
|
+
var COMMON_INSIGHT_FIELDS = [
|
|
386
|
+
"date_start",
|
|
387
|
+
"date_stop",
|
|
388
|
+
"campaign_id",
|
|
389
|
+
"campaign_name",
|
|
390
|
+
"impressions",
|
|
391
|
+
"clicks",
|
|
392
|
+
"spend",
|
|
393
|
+
"reach",
|
|
394
|
+
"actions",
|
|
395
|
+
"action_values"
|
|
396
|
+
];
|
|
397
|
+
var INSIGHT_FIELDS = {
|
|
398
|
+
campaign_insights: COMMON_INSIGHT_FIELDS.join(","),
|
|
399
|
+
adset_insights: [...COMMON_INSIGHT_FIELDS, "adset_id", "adset_name"].join(
|
|
400
|
+
","
|
|
401
|
+
),
|
|
402
|
+
ad_insights: [
|
|
403
|
+
...COMMON_INSIGHT_FIELDS,
|
|
404
|
+
"adset_id",
|
|
405
|
+
"adset_name",
|
|
406
|
+
"ad_id",
|
|
407
|
+
"ad_name"
|
|
408
|
+
].join(",")
|
|
409
|
+
};
|
|
410
|
+
var MetaAdsConnector = class _MetaAdsConnector extends BaseConnector {
|
|
411
|
+
static id = "meta-ads";
|
|
412
|
+
static resources = metaAdsResources;
|
|
413
|
+
static schemas = schemasFromResources(metaAdsResources);
|
|
414
|
+
static create(input, ctx) {
|
|
415
|
+
const parsed = configFields.parse(input);
|
|
416
|
+
return new _MetaAdsConnector(
|
|
417
|
+
{
|
|
418
|
+
adAccountId: parsed.adAccountId,
|
|
419
|
+
apiVersion: parsed.apiVersion,
|
|
420
|
+
lookbackDays: parsed.lookbackDays,
|
|
421
|
+
resources: parsed.resources
|
|
422
|
+
},
|
|
423
|
+
{ accessToken: parsed.accessToken },
|
|
424
|
+
ctx
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
id = "meta-ads";
|
|
428
|
+
credentials = metaAdsCredentials;
|
|
429
|
+
buildHeaders() {
|
|
430
|
+
return {
|
|
431
|
+
Authorization: `Bearer ${this.creds.accessToken}`,
|
|
432
|
+
"User-Agent": connectorUserAgent("meta-ads")
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
apiVersion() {
|
|
436
|
+
return this.settings.apiVersion ?? DEFAULT_API_VERSION;
|
|
437
|
+
}
|
|
438
|
+
accountBase() {
|
|
439
|
+
return `${BASE_URL}/${this.apiVersion()}/${this.settings.adAccountId}`;
|
|
440
|
+
}
|
|
441
|
+
async fetchCampaignsPage(after, signal) {
|
|
442
|
+
const url = new URL(`${this.accountBase()}/campaigns`);
|
|
443
|
+
url.searchParams.set("fields", CAMPAIGN_FIELDS);
|
|
444
|
+
url.searchParams.set("limit", String(PAGE_LIMIT));
|
|
445
|
+
if (after) {
|
|
446
|
+
url.searchParams.set("after", after);
|
|
447
|
+
}
|
|
448
|
+
const res = await this.get(
|
|
449
|
+
url.toString(),
|
|
450
|
+
{
|
|
451
|
+
resource: "campaigns",
|
|
452
|
+
headers: this.buildHeaders(),
|
|
453
|
+
signal
|
|
454
|
+
}
|
|
455
|
+
);
|
|
456
|
+
return {
|
|
457
|
+
items: res.body.data ?? [],
|
|
458
|
+
next: res.body.paging?.cursors?.after ?? null
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
async fetchInsightsPage(phase, dateRange, after, signal) {
|
|
462
|
+
const url = new URL(`${this.accountBase()}/insights`);
|
|
463
|
+
url.searchParams.set("level", PHASE_TO_LEVEL[phase]);
|
|
464
|
+
url.searchParams.set("time_increment", "1");
|
|
465
|
+
url.searchParams.set("fields", INSIGHT_FIELDS[phase]);
|
|
466
|
+
url.searchParams.set(
|
|
467
|
+
"time_range",
|
|
468
|
+
JSON.stringify({ since: dateRange.since, until: dateRange.until })
|
|
469
|
+
);
|
|
470
|
+
url.searchParams.set("limit", String(PAGE_LIMIT));
|
|
471
|
+
if (after) {
|
|
472
|
+
url.searchParams.set("after", after);
|
|
473
|
+
}
|
|
474
|
+
const res = await this.get(url.toString(), {
|
|
475
|
+
resource: phase,
|
|
476
|
+
headers: this.buildHeaders(),
|
|
477
|
+
signal
|
|
478
|
+
});
|
|
479
|
+
return {
|
|
480
|
+
items: res.body.data ?? [],
|
|
481
|
+
next: res.body.paging?.cursors?.after ?? null
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
async writeCampaigns(storage, items) {
|
|
485
|
+
for (const row of items) {
|
|
486
|
+
await storage.entity(campaignToEntity(row));
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
async writeInsights(storage, phase, items) {
|
|
490
|
+
for (const row of items) {
|
|
491
|
+
await storage.metric(insightRowToMetricSample(row, phase));
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
async clearScopeOnFirstPage(storage, phase, isFull) {
|
|
495
|
+
if (INSIGHTS_PHASES.has(phase)) {
|
|
496
|
+
await storage.metrics([], { names: [METRIC_NAME[phase]] });
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
if (!isFull) {
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
await storage.entities([], { types: [CAMPAIGN_ENTITY_TYPE] });
|
|
503
|
+
}
|
|
504
|
+
async sync(options, storage, signal) {
|
|
505
|
+
const cursor = isMetaAdsSyncCursor(options.cursor) ? options.cursor : void 0;
|
|
506
|
+
const isFull = options.mode === "full";
|
|
507
|
+
const lookbackDays = this.settings.lookbackDays ?? DEFAULT_LOOKBACK_DAYS;
|
|
508
|
+
const dateRange = getDateRange(options, lookbackDays);
|
|
509
|
+
const phases = selectActivePhases(
|
|
510
|
+
(r) => r,
|
|
511
|
+
PHASE_ORDER,
|
|
512
|
+
this.settings.resources
|
|
513
|
+
);
|
|
514
|
+
return paginateChunked({
|
|
515
|
+
phases,
|
|
516
|
+
cursor,
|
|
517
|
+
signal,
|
|
518
|
+
logger: this.logger,
|
|
519
|
+
fetchPage: async (phase, page, sig) => {
|
|
520
|
+
if (phase === "campaigns") {
|
|
521
|
+
return this.fetchCampaignsPage(page, sig);
|
|
522
|
+
}
|
|
523
|
+
return this.fetchInsightsPage(phase, dateRange, page, sig);
|
|
524
|
+
},
|
|
525
|
+
writeBatch: async (phase, items, page) => {
|
|
526
|
+
if (page === null) {
|
|
527
|
+
await this.clearScopeOnFirstPage(storage, phase, isFull);
|
|
528
|
+
}
|
|
529
|
+
if (phase === "campaigns") {
|
|
530
|
+
await this.writeCampaigns(storage, items);
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
await this.writeInsights(
|
|
534
|
+
storage,
|
|
535
|
+
phase,
|
|
536
|
+
items
|
|
537
|
+
);
|
|
538
|
+
}
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
};
|
|
542
|
+
|
|
543
|
+
// src/index.ts
|
|
544
|
+
var index_default = MetaAdsConnector;
|
|
545
|
+
export {
|
|
546
|
+
MetaAdsConnector,
|
|
547
|
+
campaignToEntity,
|
|
548
|
+
configFields,
|
|
549
|
+
index_default as default,
|
|
550
|
+
doc,
|
|
551
|
+
insightRowToMetricSample
|
|
552
|
+
};
|
|
553
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../connector-shared/src/errors.ts","../../../connector-shared/src/retry.ts","../../../connector-shared/src/version.ts","../../../connector-shared/src/request.ts","../../../connector-shared/src/rate-limit.ts","../../../connector-shared/src/sanitize.ts","../../../connector-shared/src/epoch.ts","../../../connector-shared/src/pagination.ts","../../../connector-shared/src/logger.ts","../src/meta-ads.ts","../src/index.ts"],"sourcesContent":["import type { HttpResponse } from './types';\n\nexport type HttpErrorKind =\n | 'transient'\n | 'rate_limit'\n | 'auth'\n | 'upstream_bug'\n | 'client_bug';\n\nexport abstract class HttpClientError extends Error {\n abstract readonly kind: HttpErrorKind;\n readonly response?: HttpResponse;\n\n constructor(message: string, response?: HttpResponse) {\n super(message);\n this.name = new.target.name;\n this.response = response;\n }\n}\n\nexport class TransientError extends HttpClientError {\n readonly kind = 'transient' as const;\n}\n\nexport class RateLimitError extends HttpClientError {\n readonly kind = 'rate_limit' as const;\n readonly retryAfter?: Date;\n\n constructor(message: string, response?: HttpResponse, retryAfter?: Date) {\n super(message, response);\n this.retryAfter = retryAfter;\n }\n}\n\nexport class AuthError extends HttpClientError {\n readonly kind = 'auth' as const;\n}\n\nexport class UpstreamBugError extends HttpClientError {\n readonly kind = 'upstream_bug' as const;\n}\n\nexport class ClientBugError extends HttpClientError {\n readonly kind = 'client_bug' as const;\n}\n\nexport function classifyStatus(status: number): HttpErrorKind {\n if (status === 429) {\n return 'rate_limit';\n }\n if (status === 401 || status === 403) {\n return 'auth';\n }\n if (status === 408) {\n return 'transient';\n }\n if (status >= 500) {\n return 'upstream_bug';\n }\n if (status >= 400) {\n return 'client_bug';\n }\n return 'client_bug';\n}\n\nexport function errorForStatus(\n message: string,\n response: HttpResponse,\n retryAfter?: Date,\n): HttpClientError {\n const kind = classifyStatus(response.status);\n switch (kind) {\n case 'rate_limit':\n return new RateLimitError(message, response, retryAfter);\n case 'auth':\n return new AuthError(message, response);\n case 'transient':\n return new TransientError(message, response);\n case 'upstream_bug':\n return new UpstreamBugError(message, response);\n case 'client_bug':\n return new ClientBugError(message, response);\n }\n}\n","import { HttpClientError, RateLimitError, TransientError } from './errors';\n\nexport interface RetryPolicy {\n maxAttempts?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n retryOn?: (status: number | null, err?: Error) => boolean;\n}\n\nexport const defaultRetryOn = (status: number | null, err?: Error): boolean => {\n if (err instanceof RateLimitError) {\n return true;\n }\n if (err instanceof TransientError) {\n return true;\n }\n if (status === null) {\n return err instanceof Error && !(err instanceof HttpClientError);\n }\n if (status === 408 || status === 429) {\n return true;\n }\n if (status >= 500) {\n return true;\n }\n return false;\n};\n\nexport function backoffDelayMs(\n attempt: number,\n policy: Required<Pick<RetryPolicy, 'initialDelayMs' | 'maxDelayMs'>>,\n): number {\n const base = policy.initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, policy.maxDelayMs);\n}\n\nexport function parseRetryAfter(\n headerValue: string | null,\n now: Date = new Date(),\n): Date | undefined {\n if (!headerValue) {\n return undefined;\n }\n const trimmed = headerValue.trim();\n if (/^\\d+$/.test(trimmed)) {\n return new Date(now.getTime() + Number(trimmed) * 1000);\n }\n const parsed = Date.parse(trimmed);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return new Date(parsed);\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(signal.reason ?? new Error('Aborted'));\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal!.reason ?? new Error('Aborted'));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","export const HTTP_CLIENT_VERSION = '0.0.0';\n\nexport const DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n\nexport function connectorUserAgent(connectorId: string): string {\n return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n}\n","import {\n AuthError,\n ClientBugError,\n HttpClientError,\n RateLimitError,\n TransientError,\n UpstreamBugError,\n errorForStatus,\n} from './errors';\nimport { defaultRetryOn, parseRetryAfter, sleep } from './retry';\nimport type { FetchLike, HttpMethod, HttpRequest, HttpResponse } from './types';\nimport { DEFAULT_USER_AGENT } from './version';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_INITIAL_DELAY_MS = 1000;\nconst DEFAULT_MAX_DELAY_MS = 60_000;\nconst OBSERVER_TIMEOUT_MS = 250;\n\nexport interface RequestObservation {\n url: string;\n method: HttpMethod;\n status: number;\n resource: string;\n requestId: string;\n body: unknown;\n}\n\nexport type RequestObserver = (\n event: RequestObservation,\n) => void | Promise<void>;\n\nexport interface RequestOptions {\n fetch?: FetchLike;\n observer?: RequestObserver;\n resource: string;\n requestId?: string;\n}\n\nasync function notifyObserver(\n observer: RequestObserver,\n event: RequestObservation,\n): Promise<void> {\n let result: void | Promise<void>;\n try {\n result = observer(event);\n } catch (err) {\n console.warn('[connector-shared] request observer threw:', err);\n return;\n }\n if (!(result instanceof Promise)) {\n return;\n }\n const guarded = result.catch((err) => {\n console.warn('[connector-shared] request observer rejected:', err);\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, OBSERVER_TIMEOUT_MS);\n });\n try {\n await Promise.race([guarded, timeout]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n\nfunction newRequestId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction mergeHeaders(\n defaults: Record<string, string>,\n overrides: Record<string, string> | undefined,\n): Record<string, string> {\n const merged: Record<string, string> = {};\n for (const [k, v] of Object.entries(defaults)) {\n merged[k.toLowerCase()] = v;\n }\n if (overrides) {\n for (const [k, v] of Object.entries(overrides)) {\n merged[k.toLowerCase()] = v;\n }\n }\n return merged;\n}\n\nfunction linkTimeoutSignal(\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; cancel: () => void } {\n const controller = new AbortController();\n const onParentAbort = () => {\n controller.abort(parent?.reason);\n };\n if (parent) {\n if (parent.aborted) {\n controller.abort(parent.reason);\n } else {\n parent.addEventListener('abort', onParentAbort, { once: true });\n }\n }\n const timer = setTimeout(() => {\n controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n return {\n signal: controller.signal,\n cancel: () => {\n clearTimeout(timer);\n if (parent) {\n parent.removeEventListener('abort', onParentAbort);\n }\n },\n };\n}\n\nasync function readBody(res: Response, parseJson: boolean): Promise<unknown> {\n if (res.status === 204 || res.status === 205) {\n return null;\n }\n const contentType = res.headers.get('content-type') ?? '';\n if (parseJson && contentType.includes('application/json')) {\n const text = await res.text();\n if (text.length === 0) {\n return null;\n }\n return JSON.parse(text);\n }\n return res.text();\n}\n\nexport async function request<T = unknown>(\n req: HttpRequest,\n options: RequestOptions,\n): Promise<HttpResponse<T>> {\n const fetchImpl: FetchLike = options.fetch ?? (globalThis.fetch as FetchLike);\n const retry = req.retry ?? {};\n const maxAttempts = retry.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const initialDelayMs = retry.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n const maxDelayMs = retry.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n const retryOn = retry.retryOn ?? defaultRetryOn;\n const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const parseJson = req.parseJson ?? true;\n\n const headers = mergeHeaders(\n {\n 'User-Agent': DEFAULT_USER_AGENT,\n Accept: 'application/json',\n },\n req.headers,\n );\n\n let lastErr: Error | undefined;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n req.signal?.throwIfAborted();\n\n const { signal, cancel } = linkTimeoutSignal(req.signal, timeoutMs);\n let res: Response;\n try {\n res = await fetchImpl(req.url, {\n method: req.method ?? 'GET',\n headers,\n body: req.body as RequestInit['body'],\n signal,\n });\n } catch (err) {\n cancel();\n if (req.signal?.aborted) {\n throw req.signal.reason ?? err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n lastErr = error;\n if (attempt < maxAttempts - 1 && retryOn(null, error)) {\n const delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n await sleep(delay, req.signal);\n continue;\n }\n throw new TransientError(error.message);\n }\n cancel();\n\n const body = await readBody(res, parseJson);\n const httpResponse: HttpResponse<T> = {\n status: res.status,\n headers: res.headers,\n body: body as T,\n };\n if (req.rateLimit) {\n const state = req.rateLimit.parse(res.headers);\n if (state) {\n httpResponse.rateLimitState = state;\n }\n }\n\n if (options.observer) {\n await notifyObserver(options.observer, {\n url: req.url,\n method: req.method ?? 'GET',\n status: res.status,\n resource: options.resource,\n requestId: options.requestId ?? newRequestId(),\n body,\n });\n }\n\n if (res.ok) {\n return httpResponse;\n }\n\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n const message = `HTTP ${res.status} ${res.statusText} for ${req.method ?? 'GET'} ${req.url}`;\n const err = errorForStatus(message, httpResponse, retryAfter);\n\n if (\n attempt < maxAttempts - 1 &&\n retryOn(res.status, err) &&\n !(err instanceof AuthError) &&\n !(err instanceof ClientBugError)\n ) {\n lastErr = err;\n let delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n if (err instanceof RateLimitError && retryAfter) {\n const wait = retryAfter.getTime() - Date.now();\n if (wait > 0) {\n delay = Math.min(wait, maxDelayMs);\n }\n }\n await sleep(delay, req.signal);\n continue;\n }\n\n throw err;\n }\n\n throw lastErr ?? new UpstreamBugError('Exhausted retry attempts');\n}\n\nfunction computeDelay(\n attempt: number,\n initialDelayMs: number,\n maxDelayMs: number,\n): number {\n const base = initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, maxDelayMs);\n}\n\nexport { HttpClientError };\n","export interface RateLimitState {\n remaining: number;\n resetAt: Date;\n}\n\nexport interface RateLimitPolicy {\n parse(headers: Headers): RateLimitState | null;\n}\n\nexport interface StandardRateLimitPolicyConfig {\n remainingHeader: string;\n resetHeader: string;\n resetUnit: 's' | 'ms';\n resetFallbackMs?: number;\n}\n\nexport function standardRateLimitPolicy(\n config: StandardRateLimitPolicyConfig,\n): RateLimitPolicy {\n const { remainingHeader, resetHeader, resetUnit, resetFallbackMs } = config;\n const multiplier = resetUnit === 's' ? 1000 : 1;\n return {\n parse(h) {\n const remainingRaw = h.get(remainingHeader);\n if (remainingRaw === null || remainingRaw.trim() === '') {\n return null;\n }\n const remaining = Number(remainingRaw);\n if (!Number.isFinite(remaining)) {\n return null;\n }\n const resetRaw = h.get(resetHeader);\n if (resetRaw === null) {\n if (resetFallbackMs === undefined) {\n return null;\n }\n return {\n remaining,\n resetAt: new Date(Date.now() + resetFallbackMs),\n };\n }\n if (resetRaw.trim() === '') {\n return null;\n }\n const reset = Number(resetRaw);\n if (!Number.isFinite(reset) || reset < 0) {\n return null;\n }\n const resetMs = reset * multiplier;\n if (!Number.isFinite(resetMs)) {\n return null;\n }\n return { remaining, resetAt: new Date(resetMs) };\n },\n };\n}\n","export interface SanitizeAllowedUrlOptions {\n url: string | null;\n host: string;\n pathname: string;\n protocol?: 'https:' | 'http:';\n}\n\nexport function sanitizeAllowedUrl(\n options: SanitizeAllowedUrlOptions,\n): string | null {\n const { url, host, pathname, protocol = 'https:' } = options;\n if (url === null) {\n return null;\n }\n try {\n const u = new URL(url);\n if (u.protocol !== protocol || u.host !== host || u.pathname !== pathname) {\n return null;\n }\n return u.toString();\n } catch {\n return null;\n }\n}\n","export type EpochUnit = 'ms' | 's' | 'iso';\n\nexport function parseEpoch(\n value: number | string | null | undefined,\n unit: EpochUnit,\n): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (unit === 'iso') {\n if (typeof value !== 'string') {\n return null;\n }\n const ms = new Date(value).getTime();\n return Number.isFinite(ms) ? ms : null;\n }\n if (typeof value === 'string' && value.trim() === '') {\n return null;\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n)) {\n return null;\n }\n const result = unit === 's' ? n * 1000 : n;\n return Number.isFinite(result) ? result : null;\n}\n","import { request } from './request';\nimport type { HttpRequest } from './types';\n\nexport function parseLinkHeader(header: string | null): Record<string, string> {\n if (!header) {\n return {};\n }\n const result: Record<string, string> = {};\n for (const part of header.split(',')) {\n const match = part.match(/<([^>]+)>\\s*;\\s*rel=\"([^\"]+)\"/);\n if (match) {\n result[match[2]!] = match[1]!;\n }\n }\n return result;\n}\n\nexport async function* paginateLink<T>(\n initial: HttpRequest,\n parse: (body: unknown) => T[],\n options: { resource: string },\n): AsyncIterable<T> {\n let next: string | null = initial.url;\n while (next) {\n const res: Awaited<ReturnType<typeof request>> = await request(\n {\n ...initial,\n url: next,\n },\n { resource: options.resource },\n );\n for (const item of parse(res.body)) {\n yield item;\n }\n const links = parseLinkHeader(res.headers.get('link'));\n next = links['next'] ?? null;\n }\n}\n\nexport async function* paginateCursor<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; nextCursor: string | null },\n buildNext: (req: HttpRequest, cursor: string) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let req: HttpRequest = initial;\n while (true) {\n const res = await request(req, { resource: options.resource });\n const { items, nextCursor } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!nextCursor) {\n return;\n }\n req = buildNext(req, nextCursor);\n }\n}\n\nexport async function* paginatePage<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; hasMore: boolean },\n buildPage: (req: HttpRequest, page: number) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let page = 1;\n while (true) {\n const req = page === 1 ? initial : buildPage(initial, page);\n const res = await request(req, { resource: options.resource });\n const { items, hasMore } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!hasMore || items.length === 0) {\n return;\n }\n page++;\n }\n}\n","export type LogFields = Record<string, unknown>;\n\nexport interface ConnectorLogger {\n info(event: string, fields?: LogFields): void;\n warn(event: string, fields?: LogFields): void;\n}\n\nexport interface ConnectorLoggerOptions {\n scope: string;\n}\n\nconst MAX_VALUE_LEN = 120;\n\nfunction truncate(s: string, max = MAX_VALUE_LEN): string {\n if (s.length <= max) {\n return s;\n }\n return `${s.slice(0, max - 1)}…`;\n}\n\nfunction formatValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return '';\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (typeof value === 'string') {\n const t = truncate(value);\n if (/[\\s\"=]/.test(t)) {\n return JSON.stringify(t);\n }\n return t;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n json = undefined;\n }\n return truncate(json ?? String(value));\n}\n\nexport function formatLogFields(fields?: LogFields): string {\n if (!fields) {\n return '';\n }\n const parts: string[] = [];\n for (const [k, v] of Object.entries(fields)) {\n if (v === undefined) {\n continue;\n }\n parts.push(`${k}=${formatValue(v)}`);\n }\n return parts.length > 0 ? ` ${parts.join(' ')}` : '';\n}\n\nexport function formatLogLine(\n scope: string,\n event: string,\n fields?: LogFields,\n): string {\n return `[${scope}] ${event}${formatLogFields(fields)}`;\n}\n\nexport function createDefaultConnectorLogger(\n opts: ConnectorLoggerOptions,\n): ConnectorLogger {\n return {\n info(event, fields) {\n console.info(formatLogLine(opts.scope, event, fields));\n },\n warn(event, fields) {\n console.warn(formatLogLine(opts.scope, event, fields));\n },\n };\n}\n\nconst NOOP_LOGGER: ConnectorLogger = {\n info() {},\n warn() {},\n};\n\nexport function noopConnectorLogger(): ConnectorLogger {\n return NOOP_LOGGER;\n}\n","import { connectorUserAgent } from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ConnectorContext,\n type ConnectorDoc,\n type CredentialsSchema,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n defineConnectorDoc,\n defineResources,\n makeChunkedCursorGuard,\n paginateChunked,\n schemasFromResources,\n selectActivePhases,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\nexport const configFields = defineConfigFields(\n z.object({\n adAccountId: z\n .string()\n .trim()\n .regex(\n /^act_\\d+$/,\n 'Ad account ID must look like `act_<digits>` (e.g. `act_1234567890`)',\n )\n .meta({\n label: 'Ad account ID',\n description:\n 'Meta Marketing API ad account ID. Find it in Ads Manager → Settings → Account info; it always starts with `act_`.',\n placeholder: 'act_1234567890',\n }),\n accessToken: z.object({ $secret: z.string() }).meta({\n label: 'System user access token',\n description:\n 'Long-lived System User access token from Meta Business Manager with `ads_read` (and, for newer accounts, `read_insights`) scopes on the chosen ad account.',\n placeholder: 'EAAB...',\n secret: true,\n }),\n apiVersion: z\n .string()\n .regex(/^v\\d+\\.\\d+$/, 'API version must look like `v21.0`')\n .optional()\n .meta({\n label: 'Graph API version',\n description:\n 'Pin a specific Meta Graph API version (e.g. `v21.0`). Defaults to `v21.0`.',\n placeholder: 'v21.0',\n }),\n lookbackDays: z.number().int().positive().optional().meta({\n label: 'Lookback days (full sync)',\n description:\n 'How many calendar days of insights to fetch on a full sync. Defaults to 90.',\n placeholder: '90',\n }),\n resources: z\n .array(\n z.enum([\n 'campaigns',\n 'campaign_insights',\n 'adset_insights',\n 'ad_insights',\n ]),\n )\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which Meta resources to sync. Omit to sync all. Ad-level insights are the most expensive - leave them out if you only need campaign or adset rollups.',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'Meta Ads',\n category: 'marketing',\n brandColor: '#0866FF',\n tagline:\n 'Sync Meta (Facebook + Instagram) ad campaigns plus daily campaign, adset, and ad-level insights - spend, impressions, clicks, reach, conversions, and conversion value.',\n vendor: {\n name: 'Meta',\n apiDocs: 'https://developers.facebook.com/docs/marketing-api/insights',\n website: 'https://business.facebook.com',\n },\n auth: {\n summary:\n 'A long-lived System User access token from Meta Business Manager, scoped with `ads_read` (and `read_insights` on newer accounts) for the target ad account.',\n setup: [\n 'In Meta Business Manager → Business Settings → Users → System Users, create a System User (or reuse an existing one) and assign it to the ad account with at least the Advertiser role.',\n 'Generate a System User access token for the System User; pick `ads_read` and (where available) `read_insights` as the scopes. Choose the longest available expiry - System User tokens can be made effectively non-expiring.',\n 'Find the ad account ID in Ads Manager → Settings → Account info; it always starts with `act_`.',\n 'Store the token as a secret and reference it from the connector config as `accessToken: secret(\"META_ACCESS_TOKEN\")` alongside `adAccountId: \"act_<id>\"`.',\n ],\n },\n rateLimit:\n 'Meta enforces per-app and per-ad-account budgets surfaced through the `X-Business-Use-Case-Usage` header. Sync at most every few hours per ad account; very large accounts may need a daily cadence.',\n limitations: [\n 'Insights are always fetched at daily granularity. Sub-daily breakdowns are not supported.',\n 'Insights for the most recent 30 days are re-fetched on every incremental sync because Meta keeps attributing conversions after the event date.',\n 'Creative-level breakdowns (publisher_platform, placement, demographics) are intentionally out of scope to keep the metric cardinality bounded.',\n ],\n});\n\n// ---------------------------------------------------------------------------\n// Settings / credentials\n// ---------------------------------------------------------------------------\n\nexport interface MetaAdsSettings {\n adAccountId: string;\n apiVersion?: string;\n lookbackDays?: number;\n resources?: readonly MetaAdsResource[];\n}\n\nconst metaAdsCredentials = {\n accessToken: {\n description: 'Meta System User access token',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype MetaAdsCredentials = typeof metaAdsCredentials;\n\n// ---------------------------------------------------------------------------\n// Phases + cursor\n// ---------------------------------------------------------------------------\n\nconst PHASE_ORDER = [\n 'campaigns',\n 'campaign_insights',\n 'adset_insights',\n 'ad_insights',\n] as const;\n\ntype MetaAdsPhase = (typeof PHASE_ORDER)[number];\n\nexport type MetaAdsResource = MetaAdsPhase;\n\nconst isMetaAdsSyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\nconst DEFAULT_API_VERSION = 'v21.0';\nconst BASE_URL = 'https://graph.facebook.com';\nconst PAGE_LIMIT = 100;\n\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\nconst DEFAULT_LOOKBACK_DAYS = 90;\n// Meta keeps attributing conversions for several days after the event; on\n// incremental syncs always re-pull the last 30 days so late attribution\n// rewrites stale rows.\nconst INCREMENTAL_LOOKBACK_DAYS = 30;\n\nconst INSIGHTS_PHASES: ReadonlySet<MetaAdsPhase> = new Set([\n 'campaign_insights',\n 'adset_insights',\n 'ad_insights',\n]);\n\nconst PHASE_TO_LEVEL: Record<\n 'campaign_insights' | 'adset_insights' | 'ad_insights',\n 'campaign' | 'adset' | 'ad'\n> = {\n campaign_insights: 'campaign',\n adset_insights: 'adset',\n ad_insights: 'ad',\n};\n\nconst METRIC_NAME: Record<MetaAdsPhase, string> = {\n campaigns: 'meta_campaign',\n campaign_insights: 'meta_campaign_insights',\n adset_insights: 'meta_adset_insights',\n ad_insights: 'meta_ad_insights',\n};\n\nconst CAMPAIGN_ENTITY_TYPE = 'meta_campaign';\n\n// ---------------------------------------------------------------------------\n// Date helpers\n// ---------------------------------------------------------------------------\n\nfunction toMetaDate(date: Date): string {\n const y = date.getUTCFullYear();\n const m = String(date.getUTCMonth() + 1).padStart(2, '0');\n const d = String(date.getUTCDate()).padStart(2, '0');\n return `${y}-${m}-${d}`;\n}\n\nfunction metaDateToMs(metaDate: string): number {\n // Meta insights dates arrive as 'YYYY-MM-DD'\n const [y, m, d] = metaDate.split('-').map((part) => Number(part));\n if (\n !Number.isFinite(y) ||\n !Number.isFinite(m) ||\n !Number.isFinite(d) ||\n y === undefined ||\n m === undefined ||\n d === undefined\n ) {\n return 0;\n }\n return Date.UTC(y, m - 1, d);\n}\n\ninterface MetaDateRange {\n since: string;\n until: string;\n}\n\nfunction getDateRange(\n options: SyncOptions,\n lookbackDays: number,\n): MetaDateRange {\n const now = Date.now();\n const until = toMetaDate(new Date(now));\n if (options.mode === 'latest' && options.since) {\n const startMs = now - (INCREMENTAL_LOOKBACK_DAYS - 1) * MS_PER_DAY;\n return { since: toMetaDate(new Date(startMs)), until };\n }\n if (options.since) {\n const sinceMs = new Date(options.since).getTime();\n if (Number.isFinite(sinceMs)) {\n const days = Math.max(1, Math.ceil((now - sinceMs) / MS_PER_DAY));\n const cappedDays = Math.min(days, lookbackDays);\n const startMs = now - (cappedDays - 1) * MS_PER_DAY;\n return { since: toMetaDate(new Date(startMs)), until };\n }\n }\n const startMs = now - (lookbackDays - 1) * MS_PER_DAY;\n return { since: toMetaDate(new Date(startMs)), until };\n}\n\n// ---------------------------------------------------------------------------\n// Value helpers\n// ---------------------------------------------------------------------------\n\nfunction parseNumber(value: unknown): number {\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value;\n }\n if (typeof value === 'string' && value.trim() !== '') {\n const n = Number(value);\n return Number.isFinite(n) ? n : 0;\n }\n return 0;\n}\n\nfunction parseOptionalNumber(value: unknown): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value;\n }\n if (typeof value === 'string' && value.trim() !== '') {\n const n = Number(value);\n return Number.isFinite(n) ? n : null;\n }\n return null;\n}\n\nfunction sumActionValues(\n entries: ReadonlyArray<{ value?: unknown }> | undefined,\n): number {\n if (!entries) {\n return 0;\n }\n let total = 0;\n for (const entry of entries) {\n total += parseNumber(entry.value);\n }\n return total;\n}\n\n// ---------------------------------------------------------------------------\n// Schemas - describe the per-resource API response shape consumed by request()\n// ---------------------------------------------------------------------------\n\nconst actionEntrySchema = z.object({\n action_type: z.string().optional(),\n value: z.union([z.string(), z.number()]).optional(),\n});\n\nconst campaignSchema = z.object({\n id: z.string().min(1),\n name: z.string().nullish(),\n objective: z.string().nullish(),\n status: z.string().nullish(),\n effective_status: z.string().nullish(),\n daily_budget: z.union([z.string(), z.number()]).nullish(),\n lifetime_budget: z.union([z.string(), z.number()]).nullish(),\n created_time: z.string().nullish(),\n updated_time: z.string().nullish(),\n});\n\nconst insightsBaseShape = {\n date_start: z.string(),\n date_stop: z.string().optional(),\n impressions: z.union([z.string(), z.number()]).optional(),\n clicks: z.union([z.string(), z.number()]).optional(),\n spend: z.union([z.string(), z.number()]).optional(),\n reach: z.union([z.string(), z.number()]).optional(),\n actions: z.array(actionEntrySchema).optional(),\n action_values: z.array(actionEntrySchema).optional(),\n};\n\nconst campaignInsightSchema = z.object({\n ...insightsBaseShape,\n campaign_id: z.string().min(1),\n campaign_name: z.string().nullish(),\n});\n\nconst adsetInsightSchema = z.object({\n ...insightsBaseShape,\n campaign_id: z.string().min(1),\n campaign_name: z.string().nullish(),\n adset_id: z.string().min(1),\n adset_name: z.string().nullish(),\n});\n\nconst adInsightSchema = z.object({\n ...insightsBaseShape,\n campaign_id: z.string().min(1),\n campaign_name: z.string().nullish(),\n adset_id: z.string().min(1),\n adset_name: z.string().nullish(),\n ad_id: z.string().min(1),\n ad_name: z.string().nullish(),\n});\n\nconst campaignsSchema = z.array(campaignSchema);\nconst campaignInsightsSchema = z.array(campaignInsightSchema);\nconst adsetInsightsSchema = z.array(adsetInsightSchema);\nconst adInsightsSchema = z.array(adInsightSchema);\n\nconst metaAdsResources = defineResources({\n meta_campaign: {\n shape: 'entity',\n description:\n 'Meta ad campaigns with name, objective, status, and budget. Upserted by id; one row per campaign in the ad account.',\n endpoint: 'GET /{ad_account_id}/campaigns',\n responses: { campaigns: campaignsSchema },\n },\n meta_campaign_insights: {\n shape: 'metric',\n description:\n 'Daily campaign-level Meta Ads insights - spend (primary value), impressions, clicks, reach, conversions, and conversion value bucketed by campaign.',\n endpoint: 'GET /{ad_account_id}/insights?level=campaign&time_increment=1',\n unit: 'spend',\n granularity: 'day',\n notes:\n 'Primary value is `spend`. `conversions` is the sum of every entry in the upstream `actions` array; `conversion_value` is the sum of every entry in `action_values`.',\n dimensions: [\n { name: 'date', description: 'Calendar day of the metric sample (UTC).' },\n { name: 'campaignId', description: 'Meta campaign id.' },\n { name: 'campaignName', description: 'Meta campaign name.' },\n { name: 'impressions', description: 'Total impressions on the day.' },\n { name: 'clicks', description: 'Total clicks on the day.' },\n { name: 'spend', description: 'Total spend (account currency).' },\n { name: 'reach', description: 'Unique reach on the day.' },\n { name: 'conversions', description: 'Total attributed actions.' },\n {\n name: 'conversion_value',\n description: 'Total attributed action value (account currency).',\n },\n ],\n responses: { campaign_insights: campaignInsightsSchema },\n },\n meta_adset_insights: {\n shape: 'metric',\n description:\n 'Daily adset-level Meta Ads insights - same fields as the campaign roll-up, bucketed by adset.',\n endpoint: 'GET /{ad_account_id}/insights?level=adset&time_increment=1',\n unit: 'spend',\n granularity: 'day',\n notes:\n 'Primary value is `spend`. Includes campaign_id/campaign_name so adset rows are easy to roll up to their parent campaign.',\n dimensions: [\n { name: 'date', description: 'Calendar day of the metric sample (UTC).' },\n { name: 'campaignId', description: 'Parent campaign id.' },\n { name: 'campaignName', description: 'Parent campaign name.' },\n { name: 'adsetId', description: 'Meta adset id.' },\n { name: 'adsetName', description: 'Meta adset name.' },\n { name: 'impressions', description: 'Total impressions on the day.' },\n { name: 'clicks', description: 'Total clicks on the day.' },\n { name: 'spend', description: 'Total spend (account currency).' },\n { name: 'reach', description: 'Unique reach on the day.' },\n { name: 'conversions', description: 'Total attributed actions.' },\n {\n name: 'conversion_value',\n description: 'Total attributed action value (account currency).',\n },\n ],\n responses: { adset_insights: adsetInsightsSchema },\n },\n meta_ad_insights: {\n shape: 'metric',\n description:\n 'Daily ad-level Meta Ads insights - same fields as the adset roll-up, bucketed by ad.',\n endpoint: 'GET /{ad_account_id}/insights?level=ad&time_increment=1',\n unit: 'spend',\n granularity: 'day',\n notes:\n 'Primary value is `spend`. Cardinality is the highest of the three insights resources - opt in via `resources: [..., \"ad_insights\"]` only when you need per-ad breakdowns.',\n dimensions: [\n { name: 'date', description: 'Calendar day of the metric sample (UTC).' },\n { name: 'campaignId', description: 'Parent campaign id.' },\n { name: 'campaignName', description: 'Parent campaign name.' },\n { name: 'adsetId', description: 'Parent adset id.' },\n { name: 'adsetName', description: 'Parent adset name.' },\n { name: 'adId', description: 'Meta ad id.' },\n { name: 'adName', description: 'Meta ad name.' },\n { name: 'impressions', description: 'Total impressions on the day.' },\n { name: 'clicks', description: 'Total clicks on the day.' },\n { name: 'spend', description: 'Total spend (account currency).' },\n { name: 'reach', description: 'Unique reach on the day.' },\n { name: 'conversions', description: 'Total attributed actions.' },\n {\n name: 'conversion_value',\n description: 'Total attributed action value (account currency).',\n },\n ],\n responses: { ad_insights: adInsightsSchema },\n },\n});\n\n// ---------------------------------------------------------------------------\n// API response types\n// ---------------------------------------------------------------------------\n\nexport interface MetaActionEntry {\n action_type?: string;\n value?: string | number;\n}\n\nexport interface MetaCampaign {\n id: string;\n name?: string | null;\n objective?: string | null;\n status?: string | null;\n effective_status?: string | null;\n daily_budget?: string | number | null;\n lifetime_budget?: string | number | null;\n created_time?: string | null;\n updated_time?: string | null;\n}\n\ninterface MetaInsightsBase {\n date_start: string;\n date_stop?: string;\n impressions?: string | number;\n clicks?: string | number;\n spend?: string | number;\n reach?: string | number;\n actions?: MetaActionEntry[];\n action_values?: MetaActionEntry[];\n}\n\nexport interface MetaCampaignInsight extends MetaInsightsBase {\n campaign_id: string;\n campaign_name?: string | null;\n}\n\nexport interface MetaAdsetInsight extends MetaCampaignInsight {\n adset_id: string;\n adset_name?: string | null;\n}\n\nexport interface MetaAdInsight extends MetaAdsetInsight {\n ad_id: string;\n ad_name?: string | null;\n}\n\ninterface MetaPagedResponse<T> {\n data?: T[];\n paging?: {\n cursors?: { after?: string; before?: string };\n next?: string;\n };\n}\n\n// ---------------------------------------------------------------------------\n// Row conversion helpers\n// ---------------------------------------------------------------------------\n\nexport function campaignToEntity(row: MetaCampaign): {\n type: string;\n id: string;\n attributes: Record<string, string | number | null>;\n updated_at: number;\n} {\n const updatedAt = row.updated_time\n ? new Date(row.updated_time).getTime()\n : row.created_time\n ? new Date(row.created_time).getTime()\n : 0;\n return {\n type: CAMPAIGN_ENTITY_TYPE,\n id: row.id,\n attributes: {\n name: row.name ?? null,\n objective: row.objective ?? null,\n status: row.status ?? null,\n effectiveStatus: row.effective_status ?? null,\n dailyBudget: parseOptionalNumber(row.daily_budget),\n lifetimeBudget: parseOptionalNumber(row.lifetime_budget),\n createdAt: row.created_time ? new Date(row.created_time).getTime() : null,\n },\n updated_at: Number.isFinite(updatedAt) ? updatedAt : 0,\n };\n}\n\nfunction buildInsightAttributes(\n row: MetaInsightsBase,\n): Record<string, string | number | null> {\n const impressions = parseNumber(row.impressions);\n const clicks = parseNumber(row.clicks);\n const spend = parseNumber(row.spend);\n const reach = parseNumber(row.reach);\n const conversions = (row.actions ?? []).length\n ? sumActionValues(row.actions)\n : 0;\n const conversionValue = sumActionValues(row.action_values);\n return {\n date: row.date_start,\n impressions,\n clicks,\n spend,\n reach,\n conversions,\n conversion_value: conversionValue,\n };\n}\n\nexport function insightRowToMetricSample(\n row: MetaCampaignInsight | MetaAdsetInsight | MetaAdInsight,\n phase: 'campaign_insights' | 'adset_insights' | 'ad_insights',\n): {\n name: string;\n ts: number;\n value: number;\n attributes: Record<string, string | number | null>;\n} {\n const attributes = buildInsightAttributes(row);\n attributes['campaignId'] = row.campaign_id;\n attributes['campaignName'] = row.campaign_name ?? null;\n if (phase !== 'campaign_insights') {\n const ar = row as MetaAdsetInsight;\n attributes['adsetId'] = ar.adset_id;\n attributes['adsetName'] = ar.adset_name ?? null;\n }\n if (phase === 'ad_insights') {\n const ar = row as MetaAdInsight;\n attributes['adId'] = ar.ad_id;\n attributes['adName'] = ar.ad_name ?? null;\n }\n return {\n name: METRIC_NAME[phase],\n ts: metaDateToMs(row.date_start),\n value: parseNumber(row.spend),\n attributes,\n };\n}\n\n// ---------------------------------------------------------------------------\n// MetaAdsConnector\n// ---------------------------------------------------------------------------\n\nconst CAMPAIGN_FIELDS = [\n 'id',\n 'name',\n 'objective',\n 'status',\n 'effective_status',\n 'daily_budget',\n 'lifetime_budget',\n 'created_time',\n 'updated_time',\n].join(',');\n\nconst COMMON_INSIGHT_FIELDS = [\n 'date_start',\n 'date_stop',\n 'campaign_id',\n 'campaign_name',\n 'impressions',\n 'clicks',\n 'spend',\n 'reach',\n 'actions',\n 'action_values',\n];\n\nconst INSIGHT_FIELDS: Record<\n 'campaign_insights' | 'adset_insights' | 'ad_insights',\n string\n> = {\n campaign_insights: COMMON_INSIGHT_FIELDS.join(','),\n adset_insights: [...COMMON_INSIGHT_FIELDS, 'adset_id', 'adset_name'].join(\n ',',\n ),\n ad_insights: [\n ...COMMON_INSIGHT_FIELDS,\n 'adset_id',\n 'adset_name',\n 'ad_id',\n 'ad_name',\n ].join(','),\n};\n\nexport class MetaAdsConnector extends BaseConnector<\n MetaAdsSettings,\n MetaAdsCredentials\n> {\n static readonly id = 'meta-ads';\n\n static readonly resources = metaAdsResources;\n\n static readonly schemas = schemasFromResources(metaAdsResources);\n\n static create(input: unknown, ctx?: ConnectorContext): MetaAdsConnector {\n const parsed = configFields.parse(input);\n return new MetaAdsConnector(\n {\n adAccountId: parsed.adAccountId,\n apiVersion: parsed.apiVersion,\n lookbackDays: parsed.lookbackDays,\n resources: parsed.resources,\n },\n { accessToken: parsed.accessToken },\n ctx,\n );\n }\n\n readonly id = 'meta-ads';\n override readonly credentials = metaAdsCredentials;\n\n private buildHeaders(): Record<string, string> {\n return {\n Authorization: `Bearer ${this.creds.accessToken}`,\n 'User-Agent': connectorUserAgent('meta-ads'),\n };\n }\n\n private apiVersion(): string {\n return this.settings.apiVersion ?? DEFAULT_API_VERSION;\n }\n\n private accountBase(): string {\n return `${BASE_URL}/${this.apiVersion()}/${this.settings.adAccountId}`;\n }\n\n private async fetchCampaignsPage(\n after: string | null,\n signal: AbortSignal | undefined,\n ): Promise<{ items: unknown[]; next: string | null }> {\n const url = new URL(`${this.accountBase()}/campaigns`);\n url.searchParams.set('fields', CAMPAIGN_FIELDS);\n url.searchParams.set('limit', String(PAGE_LIMIT));\n if (after) {\n url.searchParams.set('after', after);\n }\n const res = await this.get<MetaPagedResponse<MetaCampaign>>(\n url.toString(),\n {\n resource: 'campaigns',\n headers: this.buildHeaders(),\n signal,\n },\n );\n return {\n items: res.body.data ?? [],\n next: res.body.paging?.cursors?.after ?? null,\n };\n }\n\n private async fetchInsightsPage(\n phase: 'campaign_insights' | 'adset_insights' | 'ad_insights',\n dateRange: MetaDateRange,\n after: string | null,\n signal: AbortSignal | undefined,\n ): Promise<{ items: unknown[]; next: string | null }> {\n const url = new URL(`${this.accountBase()}/insights`);\n url.searchParams.set('level', PHASE_TO_LEVEL[phase]);\n url.searchParams.set('time_increment', '1');\n url.searchParams.set('fields', INSIGHT_FIELDS[phase]);\n url.searchParams.set(\n 'time_range',\n JSON.stringify({ since: dateRange.since, until: dateRange.until }),\n );\n url.searchParams.set('limit', String(PAGE_LIMIT));\n if (after) {\n url.searchParams.set('after', after);\n }\n const res = await this.get<MetaPagedResponse<unknown>>(url.toString(), {\n resource: phase,\n headers: this.buildHeaders(),\n signal,\n });\n return {\n items: res.body.data ?? [],\n next: res.body.paging?.cursors?.after ?? null,\n };\n }\n\n private async writeCampaigns(\n storage: StorageHandle,\n items: MetaCampaign[],\n ): Promise<void> {\n for (const row of items) {\n await storage.entity(campaignToEntity(row));\n }\n }\n\n private async writeInsights(\n storage: StorageHandle,\n phase: 'campaign_insights' | 'adset_insights' | 'ad_insights',\n items: Array<MetaCampaignInsight | MetaAdsetInsight | MetaAdInsight>,\n ): Promise<void> {\n for (const row of items) {\n await storage.metric(insightRowToMetricSample(row, phase));\n }\n }\n\n private async clearScopeOnFirstPage(\n storage: StorageHandle,\n phase: MetaAdsPhase,\n isFull: boolean,\n ): Promise<void> {\n if (INSIGHTS_PHASES.has(phase)) {\n // Insights are append-only with no upsert key, so every sync (full or\n // incremental) rewrites the whole metric scope for the configured window.\n await storage.metrics([], { names: [METRIC_NAME[phase]] });\n return;\n }\n if (!isFull) {\n return;\n }\n await storage.entities([], { types: [CAMPAIGN_ENTITY_TYPE] });\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor = isMetaAdsSyncCursor(options.cursor)\n ? options.cursor\n : undefined;\n const isFull = options.mode === 'full';\n const lookbackDays = this.settings.lookbackDays ?? DEFAULT_LOOKBACK_DAYS;\n // Recompute on every tick. A resume across midnight will shift `until` by\n // a day, which is fine: the metric scope is fully replaced each phase.\n const dateRange = getDateRange(options, lookbackDays);\n\n const phases = selectActivePhases<MetaAdsResource, MetaAdsPhase>(\n (r) => r,\n PHASE_ORDER,\n this.settings.resources,\n );\n\n return paginateChunked<MetaAdsPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (phase, page, sig) => {\n if (phase === 'campaigns') {\n return this.fetchCampaignsPage(page, sig);\n }\n return this.fetchInsightsPage(phase, dateRange, page, sig);\n },\n writeBatch: async (phase, items, page) => {\n if (page === null) {\n await this.clearScopeOnFirstPage(storage, phase, isFull);\n }\n if (phase === 'campaigns') {\n await this.writeCampaigns(storage, items as MetaCampaign[]);\n return;\n }\n await this.writeInsights(\n storage,\n phase,\n items as Array<\n MetaCampaignInsight | MetaAdsetInsight | MetaAdInsight\n >,\n );\n },\n });\n }\n}\n","import { MetaAdsConnector } from './meta-ads';\n\nexport {\n campaignToEntity,\n configFields,\n doc,\n insightRowToMetricSample,\n MetaAdsConnector,\n} from './meta-ads';\nexport type {\n MetaAdsResource,\n MetaAdsSettings,\n MetaActionEntry,\n MetaAdInsight,\n MetaAdsetInsight,\n MetaCampaign,\n MetaCampaignInsight,\n} from './meta-ads';\nexport default MetaAdsConnector;\n"],"mappings":";AEAO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,IAAI,mBAAmB;AAChE;;;AOLA;AAAA,EACE;AAAA,EAOA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS;AAEX,IAAM,eAAe;AAAA,EAC1B,EAAE,OAAO;AAAA,IACP,aAAa,EACV,OAAO,EACP,KAAK,EACL;AAAA,MACC;AAAA,MACA;AAAA,IACF,EACC,KAAK;AAAA,MACJ,OAAO;AAAA,MACP,aACE;AAAA,MACF,aAAa;AAAA,IACf,CAAC;AAAA,IACH,aAAa,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK;AAAA,MAClD,OAAO;AAAA,MACP,aACE;AAAA,MACF,aAAa;AAAA,MACb,QAAQ;AAAA,IACV,CAAC;AAAA,IACD,YAAY,EACT,OAAO,EACP,MAAM,eAAe,oCAAoC,EACzD,SAAS,EACT,KAAK;AAAA,MACJ,OAAO;AAAA,MACP,aACE;AAAA,MACF,aAAa;AAAA,IACf,CAAC;AAAA,IACH,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS,EAAE,KAAK;AAAA,MACxD,OAAO;AAAA,MACP,aACE;AAAA,MACF,aAAa;AAAA,IACf,CAAC;AAAA,IACD,WAAW,EACR;AAAA,MACC,EAAE,KAAK;AAAA,QACL;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,CAAC;AAAA,IACH,EACC,SAAS,EACT,SAAS,EACT,KAAK;AAAA,MACJ,O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,eAAe,KAAK,SAAS,gBAAgB;AAGnD,UAAM,YAAY,aAAa,SAAS,YAAY;AAEpD,UAAM,SAAS;AAAA,MACb,CAAC,MAAM;AAAA,MACP;AAAA,MACA,KAAK,SAAS;AAAA,IAChB;AAEA,WAAO,gBAAsC;AAAA,MAC3C;AAAA,MACA;AAAA,MACA;AAAA,MACA,QAAQ,KAAK;AAAA,MACb,WAAW,OAAO,OAAO,MAAM,QAAQ;AACrC,YAAI,UAAU,aAAa;AACzB,iBAAO,KAAK,mBAAmB,MAAM,GAAG;AAAA,QAC1C;AACA,eAAO,KAAK,kBAAkB,OAAO,WAAW,MAAM,GAAG;AAAA,MAC3D;AAAA,MACA,YAAY,OAAO,OAAO,OAAO,SAAS;AACxC,YAAI,SAAS,MAAM;AACjB,gBAAM,KAAK,sBAAsB,SAAS,OAAO,MAAM;AAAA,QACzD;AACA,YAAI,UAAU,aAAa;AACzB,gBAAM,KAAK,eAAe,SAAS,KAAuB;AAC1D;AAAA,QACF;AACA,cAAM,KAAK;AAAA,UACT;AAAA,UACA;AAAA,UACA;AAAA,QAGF;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;;;ACrwBA,IAAO,gBAAQ;","names":["startMs"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@rawdash/connector-meta-ads",
|
|
3
|
+
"version": "0.16.0",
|
|
4
|
+
"description": "Rawdash connector for Meta (Facebook + Instagram) Ads — campaigns and daily campaign/adset/ad insights",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/rawdash/rawdash.git",
|
|
10
|
+
"directory": "packages/connectors/meta-ads"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"dist",
|
|
14
|
+
"README.md",
|
|
15
|
+
"LICENSE"
|
|
16
|
+
],
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"@rawdash/source": "./src/index.ts",
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"import": "./dist/index.js"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "tsup",
|
|
26
|
+
"typecheck": "tsc --noEmit",
|
|
27
|
+
"lint": "eslint src",
|
|
28
|
+
"test": "vitest run"
|
|
29
|
+
},
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"@rawdash/core": "workspace:*",
|
|
32
|
+
"zod": "^4.4.3"
|
|
33
|
+
},
|
|
34
|
+
"devDependencies": {
|
|
35
|
+
"@rawdash/connector-shared": "workspace:*",
|
|
36
|
+
"@rawdash/connector-test-utils": "workspace:*",
|
|
37
|
+
"fast-check": "^4.8.0",
|
|
38
|
+
"tsup": "^8.0.0",
|
|
39
|
+
"typescript": "^5.7.2",
|
|
40
|
+
"vitest": "^4.1.4"
|
|
41
|
+
}
|
|
42
|
+
}
|