@rawdash/connector-google-ads 0.16.0 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/dist/index.d.ts +224 -1
- package/dist/index.js +6 -3
- package/dist/index.js.map +1 -1
- package/package.json +14 -13
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/dist/index.d.ts
CHANGED
|
@@ -129,6 +129,228 @@ type CampaignRow = z.infer<typeof campaignRowSchema>;
|
|
|
129
129
|
type CampaignMetricRow = z.infer<typeof campaignMetricRowSchema>;
|
|
130
130
|
type AdGroupMetricRow = z.infer<typeof adGroupMetricRowSchema>;
|
|
131
131
|
type KeywordMetricRow = z.infer<typeof keywordMetricRowSchema>;
|
|
132
|
+
declare const googleAdsResources: {
|
|
133
|
+
readonly google_ads_campaign: {
|
|
134
|
+
readonly shape: "entity";
|
|
135
|
+
readonly description: "Google Ads campaigns with id, name, status, bidding strategy type, and start / end dates.";
|
|
136
|
+
readonly endpoint: "POST /v18/customers/{customerId}/googleAds:search";
|
|
137
|
+
readonly fields: [{
|
|
138
|
+
readonly name: "id";
|
|
139
|
+
readonly description: "Numeric Google Ads campaign id.";
|
|
140
|
+
}, {
|
|
141
|
+
readonly name: "name";
|
|
142
|
+
readonly description: "Campaign display name.";
|
|
143
|
+
}, {
|
|
144
|
+
readonly name: "status";
|
|
145
|
+
readonly description: "Campaign status (ENABLED, PAUSED, REMOVED, UNKNOWN, UNSPECIFIED).";
|
|
146
|
+
}, {
|
|
147
|
+
readonly name: "biddingStrategyType";
|
|
148
|
+
readonly description: "Bidding strategy in use (e.g. MAXIMIZE_CONVERSIONS, MANUAL_CPC).";
|
|
149
|
+
}, {
|
|
150
|
+
readonly name: "startDate";
|
|
151
|
+
readonly description: "Campaign start date (YYYY-MM-DD).";
|
|
152
|
+
}, {
|
|
153
|
+
readonly name: "endDate";
|
|
154
|
+
readonly description: "Campaign end date (YYYY-MM-DD), if set.";
|
|
155
|
+
}];
|
|
156
|
+
readonly responses: {
|
|
157
|
+
readonly oauth_token: z.ZodObject<{
|
|
158
|
+
access_token: z.ZodString;
|
|
159
|
+
expires_in: z.ZodOptional<z.ZodNumber>;
|
|
160
|
+
}, z.core.$strip>;
|
|
161
|
+
readonly campaigns: z.ZodArray<z.ZodObject<{
|
|
162
|
+
campaign: z.ZodObject<{
|
|
163
|
+
id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
|
|
164
|
+
name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
165
|
+
status: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
166
|
+
biddingStrategyType: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
167
|
+
startDate: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
168
|
+
endDate: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
169
|
+
resourceName: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
170
|
+
}, z.core.$strip>;
|
|
171
|
+
}, z.core.$strip>>;
|
|
172
|
+
};
|
|
173
|
+
};
|
|
174
|
+
readonly google_ads_campaign_metrics: {
|
|
175
|
+
readonly shape: "metric";
|
|
176
|
+
readonly description: "Daily campaign performance - impressions, clicks, cost, conversions, and conversion value per (date, campaignId).";
|
|
177
|
+
readonly endpoint: "POST /v18/customers/{customerId}/googleAds:search";
|
|
178
|
+
readonly unit: "cost";
|
|
179
|
+
readonly granularity: "day";
|
|
180
|
+
readonly dimensions: [{
|
|
181
|
+
readonly name: "date";
|
|
182
|
+
readonly description: "Calendar day of the metric sample.";
|
|
183
|
+
}, {
|
|
184
|
+
readonly name: "campaignId";
|
|
185
|
+
readonly description: "Numeric Google Ads campaign id.";
|
|
186
|
+
}, {
|
|
187
|
+
readonly name: "campaignName";
|
|
188
|
+
readonly description: "Campaign display name at sync time.";
|
|
189
|
+
}, {
|
|
190
|
+
readonly name: "impressions";
|
|
191
|
+
readonly description: "Ad impressions served on the day.";
|
|
192
|
+
}, {
|
|
193
|
+
readonly name: "clicks";
|
|
194
|
+
readonly description: "Clicks recorded on the day.";
|
|
195
|
+
}, {
|
|
196
|
+
readonly name: "cost";
|
|
197
|
+
readonly description: "Cost in account currency units (cost_micros ÷ 1,000,000).";
|
|
198
|
+
}, {
|
|
199
|
+
readonly name: "costMicros";
|
|
200
|
+
readonly description: "Raw cost in micros, as returned by the API.";
|
|
201
|
+
}, {
|
|
202
|
+
readonly name: "conversions";
|
|
203
|
+
readonly description: "Counted conversions attributed to the day.";
|
|
204
|
+
}, {
|
|
205
|
+
readonly name: "conversionsValue";
|
|
206
|
+
readonly description: "Total value of conversions for the day.";
|
|
207
|
+
}];
|
|
208
|
+
readonly notes: "Sample value is `cost` (account currency units). All other fields are mirrored in attributes for filtering and ratio metrics (CPA = cost / conversions, ROAS = conversionsValue / cost).";
|
|
209
|
+
readonly responses: {
|
|
210
|
+
readonly campaign_metrics: z.ZodArray<z.ZodObject<{
|
|
211
|
+
segments: z.ZodObject<{
|
|
212
|
+
date: z.ZodString;
|
|
213
|
+
}, z.core.$strip>;
|
|
214
|
+
campaign: z.ZodObject<{
|
|
215
|
+
id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
|
|
216
|
+
name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
217
|
+
resourceName: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
218
|
+
}, z.core.$strip>;
|
|
219
|
+
metrics: z.ZodObject<{
|
|
220
|
+
impressions: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
|
|
221
|
+
clicks: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
|
|
222
|
+
costMicros: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
|
|
223
|
+
conversions: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
224
|
+
conversionsValue: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
225
|
+
historicalQualityScore: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
|
|
226
|
+
}, z.core.$strip>;
|
|
227
|
+
}, z.core.$strip>>;
|
|
228
|
+
};
|
|
229
|
+
};
|
|
230
|
+
readonly google_ads_ad_group_metrics: {
|
|
231
|
+
readonly shape: "metric";
|
|
232
|
+
readonly description: "Daily ad-group performance - impressions, clicks, cost, and conversions per (date, adGroupId).";
|
|
233
|
+
readonly endpoint: "POST /v18/customers/{customerId}/googleAds:search";
|
|
234
|
+
readonly unit: "cost";
|
|
235
|
+
readonly granularity: "day";
|
|
236
|
+
readonly dimensions: [{
|
|
237
|
+
readonly name: "date";
|
|
238
|
+
readonly description: "Calendar day of the metric sample.";
|
|
239
|
+
}, {
|
|
240
|
+
readonly name: "adGroupId";
|
|
241
|
+
readonly description: "Numeric Google Ads ad-group id.";
|
|
242
|
+
}, {
|
|
243
|
+
readonly name: "adGroupName";
|
|
244
|
+
readonly description: "Ad-group display name at sync time.";
|
|
245
|
+
}, {
|
|
246
|
+
readonly name: "campaignId";
|
|
247
|
+
readonly description: "Parent campaign id.";
|
|
248
|
+
}, {
|
|
249
|
+
readonly name: "impressions";
|
|
250
|
+
readonly description: "Ad impressions served on the day.";
|
|
251
|
+
}, {
|
|
252
|
+
readonly name: "clicks";
|
|
253
|
+
readonly description: "Clicks recorded on the day.";
|
|
254
|
+
}, {
|
|
255
|
+
readonly name: "cost";
|
|
256
|
+
readonly description: "Cost in account currency units.";
|
|
257
|
+
}, {
|
|
258
|
+
readonly name: "costMicros";
|
|
259
|
+
readonly description: "Raw cost in micros, as returned by the API.";
|
|
260
|
+
}, {
|
|
261
|
+
readonly name: "conversions";
|
|
262
|
+
readonly description: "Counted conversions attributed to the day.";
|
|
263
|
+
}];
|
|
264
|
+
readonly responses: {
|
|
265
|
+
readonly ad_group_metrics: z.ZodArray<z.ZodObject<{
|
|
266
|
+
segments: z.ZodObject<{
|
|
267
|
+
date: z.ZodString;
|
|
268
|
+
}, z.core.$strip>;
|
|
269
|
+
campaign: z.ZodOptional<z.ZodNullable<z.ZodObject<{
|
|
270
|
+
id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
|
|
271
|
+
}, z.core.$strip>>>;
|
|
272
|
+
adGroup: z.ZodObject<{
|
|
273
|
+
id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
|
|
274
|
+
name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
275
|
+
resourceName: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
276
|
+
}, z.core.$strip>;
|
|
277
|
+
metrics: z.ZodObject<{
|
|
278
|
+
impressions: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
|
|
279
|
+
clicks: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
|
|
280
|
+
costMicros: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
|
|
281
|
+
conversions: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
282
|
+
conversionsValue: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
283
|
+
historicalQualityScore: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
|
|
284
|
+
}, z.core.$strip>;
|
|
285
|
+
}, z.core.$strip>>;
|
|
286
|
+
};
|
|
287
|
+
};
|
|
288
|
+
readonly google_ads_keyword_metrics: {
|
|
289
|
+
readonly shape: "metric";
|
|
290
|
+
readonly description: "Daily keyword performance - impressions, clicks, cost, and historical quality score per (date, criterionId).";
|
|
291
|
+
readonly endpoint: "POST /v18/customers/{customerId}/googleAds:search";
|
|
292
|
+
readonly unit: "cost";
|
|
293
|
+
readonly granularity: "day";
|
|
294
|
+
readonly dimensions: [{
|
|
295
|
+
readonly name: "date";
|
|
296
|
+
readonly description: "Calendar day of the metric sample.";
|
|
297
|
+
}, {
|
|
298
|
+
readonly name: "criterionId";
|
|
299
|
+
readonly description: "Numeric keyword (ad-group criterion) id.";
|
|
300
|
+
}, {
|
|
301
|
+
readonly name: "keywordText";
|
|
302
|
+
readonly description: "Keyword text.";
|
|
303
|
+
}, {
|
|
304
|
+
readonly name: "matchType";
|
|
305
|
+
readonly description: "Match type (EXACT, PHRASE, BROAD, …).";
|
|
306
|
+
}, {
|
|
307
|
+
readonly name: "adGroupId";
|
|
308
|
+
readonly description: "Parent ad-group id.";
|
|
309
|
+
}, {
|
|
310
|
+
readonly name: "impressions";
|
|
311
|
+
readonly description: "Ad impressions served on the day.";
|
|
312
|
+
}, {
|
|
313
|
+
readonly name: "clicks";
|
|
314
|
+
readonly description: "Clicks recorded on the day.";
|
|
315
|
+
}, {
|
|
316
|
+
readonly name: "cost";
|
|
317
|
+
readonly description: "Cost in account currency units.";
|
|
318
|
+
}, {
|
|
319
|
+
readonly name: "costMicros";
|
|
320
|
+
readonly description: "Raw cost in micros, as returned by the API.";
|
|
321
|
+
}, {
|
|
322
|
+
readonly name: "qualityScore";
|
|
323
|
+
readonly description: "Historical quality score for the day (1-10), null when no impressions.";
|
|
324
|
+
}];
|
|
325
|
+
readonly notes: "Driven by `keyword_view`; the cost / impression columns roll up to the criterion-day pair.";
|
|
326
|
+
readonly responses: {
|
|
327
|
+
readonly keyword_metrics: z.ZodArray<z.ZodObject<{
|
|
328
|
+
segments: z.ZodObject<{
|
|
329
|
+
date: z.ZodString;
|
|
330
|
+
}, z.core.$strip>;
|
|
331
|
+
adGroup: z.ZodOptional<z.ZodNullable<z.ZodObject<{
|
|
332
|
+
id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
|
|
333
|
+
}, z.core.$strip>>>;
|
|
334
|
+
adGroupCriterion: z.ZodObject<{
|
|
335
|
+
criterionId: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
|
|
336
|
+
keyword: z.ZodOptional<z.ZodNullable<z.ZodObject<{
|
|
337
|
+
text: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
338
|
+
matchType: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
339
|
+
}, z.core.$strip>>>;
|
|
340
|
+
resourceName: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
341
|
+
}, z.core.$strip>;
|
|
342
|
+
metrics: z.ZodObject<{
|
|
343
|
+
impressions: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
|
|
344
|
+
clicks: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
|
|
345
|
+
costMicros: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
|
|
346
|
+
conversions: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
347
|
+
conversionsValue: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
348
|
+
historicalQualityScore: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
|
|
349
|
+
}, z.core.$strip>;
|
|
350
|
+
}, z.core.$strip>>;
|
|
351
|
+
};
|
|
352
|
+
};
|
|
353
|
+
};
|
|
132
354
|
interface DateRange {
|
|
133
355
|
startDate: string;
|
|
134
356
|
endDate: string;
|
|
@@ -158,6 +380,7 @@ declare function keywordMetricRowToSample(row: KeywordMetricRow): {
|
|
|
158
380
|
value: number;
|
|
159
381
|
attributes: Record<string, string | number | null>;
|
|
160
382
|
};
|
|
383
|
+
declare const id = "google-ads";
|
|
161
384
|
declare class GoogleAdsConnector extends BaseConnector<GoogleAdsSettings, GoogleAdsCredentials> {
|
|
162
385
|
static readonly id = "google-ads";
|
|
163
386
|
static readonly resources: {
|
|
@@ -495,4 +718,4 @@ declare class GoogleAdsConnector extends BaseConnector<GoogleAdsSettings, Google
|
|
|
495
718
|
sync(options: SyncOptions, storage: StorageHandle, signal?: AbortSignal): Promise<SyncResult>;
|
|
496
719
|
}
|
|
497
720
|
|
|
498
|
-
export { GoogleAdsConnector, type GoogleAdsResource, type GoogleAdsSettings, adGroupMetricRowToSample, campaignMetricRowToSample, campaignToEntity, configFields, GoogleAdsConnector as default, doc, getDateRange, keywordMetricRowToSample };
|
|
721
|
+
export { GoogleAdsConnector, type GoogleAdsResource, type GoogleAdsSettings, adGroupMetricRowToSample, campaignMetricRowToSample, campaignToEntity, configFields, GoogleAdsConnector as default, doc, getDateRange, id, keywordMetricRowToSample, googleAdsResources as resources };
|
package/dist/index.js
CHANGED
|
@@ -529,8 +529,9 @@ function keywordMetricRowToSample(row) {
|
|
|
529
529
|
}
|
|
530
530
|
};
|
|
531
531
|
}
|
|
532
|
+
var id = "google-ads";
|
|
532
533
|
var GoogleAdsConnector = class _GoogleAdsConnector extends BaseConnector {
|
|
533
|
-
static id =
|
|
534
|
+
static id = id;
|
|
534
535
|
static resources = googleAdsResources;
|
|
535
536
|
static schemas = schemasFromResources(googleAdsResources);
|
|
536
537
|
static create(input, ctx) {
|
|
@@ -551,7 +552,7 @@ var GoogleAdsConnector = class _GoogleAdsConnector extends BaseConnector {
|
|
|
551
552
|
ctx
|
|
552
553
|
);
|
|
553
554
|
}
|
|
554
|
-
id =
|
|
555
|
+
id = id;
|
|
555
556
|
credentials = googleAdsCredentials;
|
|
556
557
|
cachedToken = null;
|
|
557
558
|
async fetchAccessToken(signal) {
|
|
@@ -698,6 +699,8 @@ export {
|
|
|
698
699
|
index_default as default,
|
|
699
700
|
doc,
|
|
700
701
|
getDateRange,
|
|
701
|
-
|
|
702
|
+
id,
|
|
703
|
+
keywordMetricRowToSample,
|
|
704
|
+
googleAdsResources as resources
|
|
702
705
|
};
|
|
703
706
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +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/google-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\n// ---------------------------------------------------------------------------\n// configFields / doc\n// ---------------------------------------------------------------------------\n\nexport const configFields = defineConfigFields(\n z.object({\n customerId: z\n .string()\n .trim()\n .regex(\n /^\\d{10}$/,\n 'customerId must be the 10-digit Google Ads ID, digits only (no dashes)',\n )\n .meta({\n label: 'Customer ID',\n description:\n 'Google Ads customer ID for the account to sync, digits only (the dashed form 123-456-7890 with the dashes removed).',\n placeholder: '1234567890',\n }),\n loginCustomerId: z\n .string()\n .trim()\n .regex(\n /^\\d{10}$/,\n 'loginCustomerId must be a 10-digit Google Ads ID, digits only',\n )\n .optional()\n .meta({\n label: 'Login Customer ID (MCC)',\n description:\n 'Manager (MCC) account ID, digits only. Set this when the OAuth credential authenticates against an MCC that owns the customer account.',\n placeholder: '1234567890',\n }),\n clientId: z.string().min(1).meta({\n label: 'OAuth Client ID',\n description:\n 'OAuth 2.0 client ID from a Google Cloud project that has the Google Ads API enabled.',\n placeholder: '…apps.googleusercontent.com',\n }),\n clientSecret: z.object({ $secret: z.string() }).meta({\n label: 'OAuth Client Secret',\n description: 'OAuth 2.0 client secret paired with the client ID above.',\n secret: true,\n }),\n refreshToken: z.object({ $secret: z.string() }).meta({\n label: 'OAuth Refresh Token',\n description:\n 'Google OAuth 2.0 refresh token issued for the https://www.googleapis.com/auth/adwords scope.',\n secret: true,\n }),\n developerToken: z.object({ $secret: z.string() }).meta({\n label: 'Developer Token',\n description:\n 'Google Ads API developer token from the manager account that owns API access (Tools → API Center).',\n secret: true,\n }),\n lookbackDays: z.number().int().positive().optional().meta({\n label: 'Lookback days (full sync)',\n description:\n 'How many calendar days of metric history 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_metrics',\n 'ad_group_metrics',\n 'keyword_metrics',\n ]),\n )\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which Google Ads resources to sync. Omit to sync everything; pin a subset to avoid pulling keyword-level metrics on a quota-limited token.',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'Google Ads',\n category: 'marketing',\n brandColor: '#4285F4',\n tagline:\n 'Sync Google Ads campaigns plus daily campaign, ad-group, and keyword performance (impressions, clicks, cost, conversions) via GAQL.',\n vendor: {\n name: 'Google Ads',\n apiDocs: 'https://developers.google.com/google-ads/api/docs/start',\n website: 'https://ads.google.com',\n },\n auth: {\n summary:\n 'OAuth 2.0 refresh token against an account with read access to the Google Ads customer, plus a developer token from the manager account that owns API access.',\n setup: [\n 'Apply for Google Ads API access from your manager account (Tools → API Center). Copy the developer token - it lives on the manager, not the child account.',\n 'In Google Cloud Console, enable the Google Ads API on a project, create an OAuth 2.0 client ID, and complete the OAuth consent flow for the adwords scope to obtain a refresh token. The official walkthrough is at https://developers.google.com/google-ads/api/docs/oauth/overview.',\n 'Find the Google Ads customer ID at the top of the Ads UI (e.g. 123-456-7890) and store it without dashes (e.g. 1234567890).',\n 'If the OAuth credential authenticates against an MCC that owns the customer, set `loginCustomerId` to the MCC id (digits only). For a direct-access account, omit it.',\n 'Store the client secret, refresh token, and developer token as secrets, then reference them as `clientSecret: secret(\"GADS_CLIENT_SECRET\")`, `refreshToken: secret(\"GADS_REFRESH_TOKEN\")`, and `developerToken: secret(\"GADS_DEVELOPER_TOKEN\")`.',\n ],\n },\n rateLimit:\n 'Google Ads API basic-access tokens get a 15,000 operations / day quota per developer token; the connector treats 429 (RESOURCE_EXHAUSTED) as a transient error and the host backs off.',\n limitations: [\n 'Cost values are stored in account currency units (cost_micros ÷ 1,000,000); the original micro-precision integer is also exposed in attributes.',\n 'Keyword metrics use the historical (per-day) quality score from `metrics.historical_quality_score`; criteria with no impressions on a day will report a null quality score.',\n 'Incremental syncs trail the last 3 days because Google Ads can attribute conversions to a click up to 3 days after the event.',\n 'Audience-, asset-, and recommendation-level reporting are out of scope; this connector covers campaign / ad-group / keyword performance only.',\n ],\n});\n\n// ---------------------------------------------------------------------------\n// Settings / credentials\n// ---------------------------------------------------------------------------\n\nexport interface GoogleAdsSettings {\n customerId: string;\n loginCustomerId?: string;\n lookbackDays?: number;\n resources?: readonly GoogleAdsResource[];\n}\n\nconst googleAdsCredentials = {\n clientId: {\n description: 'Google OAuth 2.0 client ID (public, not a secret)',\n auth: 'required' as const,\n },\n clientSecret: {\n description: 'Google OAuth 2.0 client secret',\n auth: 'required' as const,\n },\n refreshToken: {\n description: 'Google OAuth 2.0 refresh token with the adwords scope',\n auth: 'required' as const,\n },\n developerToken: {\n description: 'Google Ads API developer token',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype GoogleAdsCredentials = typeof googleAdsCredentials;\n\n// ---------------------------------------------------------------------------\n// Sync phases + cursor\n// ---------------------------------------------------------------------------\n\nconst PHASE_ORDER = [\n 'campaigns',\n 'campaign_metrics',\n 'ad_group_metrics',\n 'keyword_metrics',\n] as const;\n\ntype GoogleAdsPhase = (typeof PHASE_ORDER)[number];\n\nexport type GoogleAdsResource = GoogleAdsPhase;\n\nconst isGoogleAdsSyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\nconst API_VERSION = 'v18';\nconst PAGE_SIZE = 10_000;\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\nconst DEFAULT_LOOKBACK_DAYS = 90;\nconst INCREMENTAL_LOOKBACK_DAYS = 3;\nconst MICROS_PER_UNIT = 1_000_000;\nconst TOKEN_URL = 'https://oauth2.googleapis.com/token';\n\nconst ENTITY_TYPE_CAMPAIGN = 'google_ads_campaign';\nconst METRIC_NAME: Record<GoogleAdsPhase, string> = {\n campaigns: ENTITY_TYPE_CAMPAIGN,\n campaign_metrics: 'google_ads_campaign_metrics',\n ad_group_metrics: 'google_ads_ad_group_metrics',\n keyword_metrics: 'google_ads_keyword_metrics',\n};\n\n// ---------------------------------------------------------------------------\n// Google Ads API response shapes (GAQL search)\n// ---------------------------------------------------------------------------\n\n// INT64 fields come back as JSON strings; everything else may be string|number\n// depending on the field. We coerce in the writers. Empty strings aren't a\n// valid representation of any numeric value upstream, so the schema rejects\n// them - that also keeps fast-check from generating zero-length entity ids.\nconst int64String = z.union([z.string().min(1), z.number()]);\n\nconst segmentsSchema = z.object({\n date: z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/),\n});\n\nconst dateString = z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/);\n\nconst campaignFieldsSchema = z.object({\n id: int64String,\n name: z.string().nullish(),\n status: z.string().nullish(),\n biddingStrategyType: z.string().nullish(),\n startDate: dateString.nullish(),\n endDate: dateString.nullish(),\n resourceName: z.string().nullish(),\n});\n\nconst metricsSchema = z.object({\n impressions: int64String.nullish(),\n clicks: int64String.nullish(),\n costMicros: int64String.nullish(),\n conversions: z.number().nullish(),\n conversionsValue: z.number().nullish(),\n historicalQualityScore: int64String.nullish(),\n});\n\nconst campaignRowSchema = z.object({\n campaign: campaignFieldsSchema,\n});\n\nconst campaignMetricRowSchema = z.object({\n segments: segmentsSchema,\n campaign: z.object({\n id: int64String,\n name: z.string().nullish(),\n resourceName: z.string().nullish(),\n }),\n metrics: metricsSchema,\n});\n\nconst adGroupMetricRowSchema = z.object({\n segments: segmentsSchema,\n campaign: z.object({ id: int64String }).nullish(),\n adGroup: z.object({\n id: int64String,\n name: z.string().nullish(),\n resourceName: z.string().nullish(),\n }),\n metrics: metricsSchema,\n});\n\nconst keywordMetricRowSchema = z.object({\n segments: segmentsSchema,\n adGroup: z.object({ id: int64String }).nullish(),\n adGroupCriterion: z.object({\n criterionId: int64String,\n keyword: z\n .object({\n text: z.string().nullish(),\n matchType: z.string().nullish(),\n })\n .nullish(),\n resourceName: z.string().nullish(),\n }),\n metrics: metricsSchema,\n});\n\nconst campaignsResponseSchema = z.array(campaignRowSchema);\nconst campaignMetricsResponseSchema = z.array(campaignMetricRowSchema);\nconst adGroupMetricsResponseSchema = z.array(adGroupMetricRowSchema);\nconst keywordMetricsResponseSchema = z.array(keywordMetricRowSchema);\n\ntype CampaignRow = z.infer<typeof campaignRowSchema>;\ntype CampaignMetricRow = z.infer<typeof campaignMetricRowSchema>;\ntype AdGroupMetricRow = z.infer<typeof adGroupMetricRowSchema>;\ntype KeywordMetricRow = z.infer<typeof keywordMetricRowSchema>;\n\nconst googleAdsResources = defineResources({\n [ENTITY_TYPE_CAMPAIGN]: {\n shape: 'entity',\n description:\n 'Google Ads campaigns with id, name, status, bidding strategy type, and start / end dates.',\n endpoint: 'POST /v18/customers/{customerId}/googleAds:search',\n fields: [\n { name: 'id', description: 'Numeric Google Ads campaign id.' },\n { name: 'name', description: 'Campaign display name.' },\n {\n name: 'status',\n description:\n 'Campaign status (ENABLED, PAUSED, REMOVED, UNKNOWN, UNSPECIFIED).',\n },\n {\n name: 'biddingStrategyType',\n description:\n 'Bidding strategy in use (e.g. MAXIMIZE_CONVERSIONS, MANUAL_CPC).',\n },\n { name: 'startDate', description: 'Campaign start date (YYYY-MM-DD).' },\n {\n name: 'endDate',\n description: 'Campaign end date (YYYY-MM-DD), if set.',\n },\n ],\n responses: {\n oauth_token: z.object({\n access_token: z.string().min(1),\n expires_in: z.number().int().positive().optional(),\n }),\n campaigns: campaignsResponseSchema,\n },\n },\n google_ads_campaign_metrics: {\n shape: 'metric',\n description:\n 'Daily campaign performance - impressions, clicks, cost, conversions, and conversion value per (date, campaignId).',\n endpoint: 'POST /v18/customers/{customerId}/googleAds:search',\n unit: 'cost',\n granularity: 'day',\n dimensions: [\n { name: 'date', description: 'Calendar day of the metric sample.' },\n { name: 'campaignId', description: 'Numeric Google Ads campaign id.' },\n {\n name: 'campaignName',\n description: 'Campaign display name at sync time.',\n },\n { name: 'impressions', description: 'Ad impressions served on the day.' },\n { name: 'clicks', description: 'Clicks recorded on the day.' },\n {\n name: 'cost',\n description:\n 'Cost in account currency units (cost_micros ÷ 1,000,000).',\n },\n {\n name: 'costMicros',\n description: 'Raw cost in micros, as returned by the API.',\n },\n {\n name: 'conversions',\n description: 'Counted conversions attributed to the day.',\n },\n {\n name: 'conversionsValue',\n description: 'Total value of conversions for the day.',\n },\n ],\n notes:\n 'Sample value is `cost` (account currency units). All other fields are mirrored in attributes for filtering and ratio metrics (CPA = cost / conversions, ROAS = conversionsValue / cost).',\n responses: { campaign_metrics: campaignMetricsResponseSchema },\n },\n google_ads_ad_group_metrics: {\n shape: 'metric',\n description:\n 'Daily ad-group performance - impressions, clicks, cost, and conversions per (date, adGroupId).',\n endpoint: 'POST /v18/customers/{customerId}/googleAds:search',\n unit: 'cost',\n granularity: 'day',\n dimensions: [\n { name: 'date', description: 'Calendar day of the metric sample.' },\n { name: 'adGroupId', description: 'Numeric Google Ads ad-group id.' },\n {\n name: 'adGroupName',\n description: 'Ad-group display name at sync time.',\n },\n { name: 'campaignId', description: 'Parent campaign id.' },\n { name: 'impressions', description: 'Ad impressions served on the day.' },\n { name: 'clicks', description: 'Clicks recorded on the day.' },\n { name: 'cost', description: 'Cost in account currency units.' },\n {\n name: 'costMicros',\n description: 'Raw cost in micros, as returned by the API.',\n },\n {\n name: 'conversions',\n description: 'Counted conversions attributed to the day.',\n },\n ],\n responses: { ad_group_metrics: adGroupMetricsResponseSchema },\n },\n google_ads_keyword_metrics: {\n shape: 'metric',\n description:\n 'Daily keyword performance - impressions, clicks, cost, and historical quality score per (date, criterionId).',\n endpoint: 'POST /v18/customers/{customerId}/googleAds:search',\n unit: 'cost',\n granularity: 'day',\n dimensions: [\n { name: 'date', description: 'Calendar day of the metric sample.' },\n {\n name: 'criterionId',\n description: 'Numeric keyword (ad-group criterion) id.',\n },\n { name: 'keywordText', description: 'Keyword text.' },\n {\n name: 'matchType',\n description: 'Match type (EXACT, PHRASE, BROAD, …).',\n },\n { name: 'adGroupId', description: 'Parent ad-group id.' },\n { name: 'impressions', description: 'Ad impressions served on the day.' },\n { name: 'clicks', description: 'Clicks recorded on the day.' },\n { name: 'cost', description: 'Cost in account currency units.' },\n {\n name: 'costMicros',\n description: 'Raw cost in micros, as returned by the API.',\n },\n {\n name: 'qualityScore',\n description:\n 'Historical quality score for the day (1-10), null when no impressions.',\n },\n ],\n notes:\n 'Driven by `keyword_view`; the cost / impression columns roll up to the criterion-day pair.',\n responses: { keyword_metrics: keywordMetricsResponseSchema },\n },\n});\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction toDateString(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\nconst DATE_RE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\nfunction dateStringToMs(yyyyMmDd: string): number {\n // Reject anything that doesn't match YYYY-MM-DD so a surprise upstream\n // value (e.g. an empty string or a malformed date) doesn't write NaN into\n // entity.updated_at / metric.ts.\n const m = DATE_RE.exec(yyyyMmDd);\n if (!m) {\n return 0;\n }\n const ms = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));\n return Number.isFinite(ms) ? ms : 0;\n}\n\ninterface DateRange {\n startDate: string;\n endDate: string;\n}\n\nexport function getDateRange(\n options: SyncOptions,\n lookbackDays: number,\n now: number = Date.now(),\n): DateRange {\n const endDate = toDateString(new Date(now));\n if (options.mode === 'latest') {\n const startMs = now - (INCREMENTAL_LOOKBACK_DAYS - 1) * MS_PER_DAY;\n return { startDate: toDateString(new Date(startMs)), endDate };\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 { startDate: toDateString(new Date(startMs)), endDate };\n }\n }\n const startMs = now - (lookbackDays - 1) * MS_PER_DAY;\n return { startDate: toDateString(new Date(startMs)), endDate };\n}\n\nfunction coerceInt(value: unknown): number {\n if (typeof value === 'number') {\n return Number.isFinite(value) ? value : 0;\n }\n if (typeof value === 'string' && value !== '') {\n const n = Number(value);\n return Number.isFinite(n) ? n : 0;\n }\n return 0;\n}\n\nfunction coerceIntOrNull(value: unknown): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n const n = coerceInt(value);\n return n;\n}\n\nfunction microsToUnits(micros: unknown): number {\n return coerceInt(micros) / MICROS_PER_UNIT;\n}\n\n// ---------------------------------------------------------------------------\n// GAQL queries - one per phase. Date ranges are interpolated, not parameterised\n// (GAQL has no bind variables); range bounds are server-side string literals.\n// ---------------------------------------------------------------------------\n\nfunction campaignsQuery(): string {\n return [\n 'SELECT',\n ' campaign.id,',\n ' campaign.name,',\n ' campaign.status,',\n ' campaign.bidding_strategy_type,',\n ' campaign.start_date,',\n ' campaign.end_date',\n 'FROM campaign',\n ].join(' ');\n}\n\nfunction campaignMetricsQuery(range: DateRange): string {\n return [\n 'SELECT',\n ' segments.date,',\n ' campaign.id,',\n ' campaign.name,',\n ' metrics.impressions,',\n ' metrics.clicks,',\n ' metrics.cost_micros,',\n ' metrics.conversions,',\n ' metrics.conversions_value',\n 'FROM campaign',\n `WHERE segments.date BETWEEN '${range.startDate}' AND '${range.endDate}'`,\n ].join(' ');\n}\n\nfunction adGroupMetricsQuery(range: DateRange): string {\n return [\n 'SELECT',\n ' segments.date,',\n ' campaign.id,',\n ' ad_group.id,',\n ' ad_group.name,',\n ' metrics.impressions,',\n ' metrics.clicks,',\n ' metrics.cost_micros,',\n ' metrics.conversions',\n 'FROM ad_group',\n `WHERE segments.date BETWEEN '${range.startDate}' AND '${range.endDate}'`,\n ].join(' ');\n}\n\nfunction keywordMetricsQuery(range: DateRange): string {\n return [\n 'SELECT',\n ' segments.date,',\n ' ad_group.id,',\n ' ad_group_criterion.criterion_id,',\n ' ad_group_criterion.keyword.text,',\n ' ad_group_criterion.keyword.match_type,',\n ' metrics.impressions,',\n ' metrics.clicks,',\n ' metrics.cost_micros,',\n ' metrics.historical_quality_score',\n 'FROM keyword_view',\n `WHERE segments.date BETWEEN '${range.startDate}' AND '${range.endDate}'`,\n ].join(' ');\n}\n\nfunction queryForPhase(phase: GoogleAdsPhase, range: DateRange): string {\n switch (phase) {\n case 'campaigns':\n return campaignsQuery();\n case 'campaign_metrics':\n return campaignMetricsQuery(range);\n case 'ad_group_metrics':\n return adGroupMetricsQuery(range);\n case 'keyword_metrics':\n return keywordMetricsQuery(range);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Row → storage write helpers\n// ---------------------------------------------------------------------------\n\nexport function campaignToEntity(row: CampaignRow): {\n type: string;\n id: string;\n attributes: Record<string, string | number | null>;\n updated_at: number;\n} {\n const c = row.campaign;\n // Campaign upstream has no updated_at field. Use the start_date as a stable\n // freshness signal so re-syncs of the same row don't churn updated_at; for\n // campaigns with no start_date (rare), fall back to 0 which still makes the\n // upsert idempotent.\n const startMs = c.startDate ? dateStringToMs(c.startDate) : 0;\n return {\n type: ENTITY_TYPE_CAMPAIGN,\n id: String(c.id),\n attributes: {\n name: c.name ?? null,\n status: c.status ?? null,\n biddingStrategyType: c.biddingStrategyType ?? null,\n startDate: c.startDate ?? null,\n endDate: c.endDate ?? null,\n resourceName: c.resourceName ?? null,\n },\n updated_at: startMs,\n };\n}\n\nexport function campaignMetricRowToSample(row: CampaignMetricRow): {\n name: string;\n ts: number;\n value: number;\n attributes: Record<string, string | number | null>;\n} {\n const m = row.metrics;\n const cost = microsToUnits(m.costMicros);\n return {\n name: METRIC_NAME.campaign_metrics,\n ts: dateStringToMs(row.segments.date),\n value: cost,\n attributes: {\n date: row.segments.date,\n campaignId: String(row.campaign.id),\n campaignName: row.campaign.name ?? null,\n impressions: coerceInt(m.impressions),\n clicks: coerceInt(m.clicks),\n cost,\n costMicros: coerceInt(m.costMicros),\n conversions: typeof m.conversions === 'number' ? m.conversions : 0,\n conversionsValue:\n typeof m.conversionsValue === 'number' ? m.conversionsValue : 0,\n },\n };\n}\n\nexport function adGroupMetricRowToSample(row: AdGroupMetricRow): {\n name: string;\n ts: number;\n value: number;\n attributes: Record<string, string | number | null>;\n} {\n const m = row.metrics;\n const cost = microsToUnits(m.costMicros);\n return {\n name: METRIC_NAME.ad_group_metrics,\n ts: dateStringToMs(row.segments.date),\n value: cost,\n attributes: {\n date: row.segments.date,\n adGroupId: String(row.adGroup.id),\n adGroupName: row.adGroup.name ?? null,\n campaignId: row.campaign?.id != null ? String(row.campaign.id) : null,\n impressions: coerceInt(m.impressions),\n clicks: coerceInt(m.clicks),\n cost,\n costMicros: coerceInt(m.costMicros),\n conversions: typeof m.conversions === 'number' ? m.conversions : 0,\n },\n };\n}\n\nexport function keywordMetricRowToSample(row: KeywordMetricRow): {\n name: string;\n ts: number;\n value: number;\n attributes: Record<string, string | number | null>;\n} {\n const m = row.metrics;\n const cost = microsToUnits(m.costMicros);\n return {\n name: METRIC_NAME.keyword_metrics,\n ts: dateStringToMs(row.segments.date),\n value: cost,\n attributes: {\n date: row.segments.date,\n criterionId: String(row.adGroupCriterion.criterionId),\n keywordText: row.adGroupCriterion.keyword?.text ?? null,\n matchType: row.adGroupCriterion.keyword?.matchType ?? null,\n adGroupId: row.adGroup?.id != null ? String(row.adGroup.id) : null,\n impressions: coerceInt(m.impressions),\n clicks: coerceInt(m.clicks),\n cost,\n costMicros: coerceInt(m.costMicros),\n qualityScore: coerceIntOrNull(m.historicalQualityScore),\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// GoogleAdsConnector\n// ---------------------------------------------------------------------------\n\ninterface TokenResponse {\n access_token: string;\n expires_in?: number;\n}\n\ninterface SearchResponse<TRow> {\n results?: TRow[];\n nextPageToken?: string;\n}\n\nexport class GoogleAdsConnector extends BaseConnector<\n GoogleAdsSettings,\n GoogleAdsCredentials\n> {\n static readonly id = 'google-ads';\n\n static readonly resources = googleAdsResources;\n\n static readonly schemas = schemasFromResources(googleAdsResources);\n\n static create(input: unknown, ctx?: ConnectorContext): GoogleAdsConnector {\n const parsed = configFields.parse(input);\n return new GoogleAdsConnector(\n {\n customerId: parsed.customerId,\n loginCustomerId: parsed.loginCustomerId,\n lookbackDays: parsed.lookbackDays,\n resources: parsed.resources,\n },\n {\n clientId: parsed.clientId,\n clientSecret: parsed.clientSecret,\n refreshToken: parsed.refreshToken,\n developerToken: parsed.developerToken,\n },\n ctx,\n );\n }\n\n readonly id = 'google-ads';\n override readonly credentials = googleAdsCredentials;\n\n private cachedToken: { token: string; expiresAt: number } | null = null;\n\n private async fetchAccessToken(\n signal: AbortSignal | undefined,\n ): Promise<{ token: string; expiresAt: number }> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: this.creds.clientId,\n client_secret: this.creds.clientSecret,\n refresh_token: this.creds.refreshToken,\n }).toString();\n const res = await this.post<TokenResponse>(TOKEN_URL, {\n resource: 'oauth_token',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body,\n signal,\n });\n const expiresIn = res.body.expires_in ?? 3600;\n return {\n token: res.body.access_token,\n // Refresh 60s before expiry so a long-running phase doesn't 401 on the\n // boundary.\n expiresAt: Date.now() + (expiresIn - 60) * 1000,\n };\n }\n\n private async getAccessToken(signal?: AbortSignal): Promise<string> {\n if (this.cachedToken && Date.now() < this.cachedToken.expiresAt) {\n return this.cachedToken.token;\n }\n this.cachedToken = await this.fetchAccessToken(signal);\n return this.cachedToken.token;\n }\n\n private buildHeaders(accessToken: string): Record<string, string> {\n const headers: Record<string, string> = {\n Authorization: `Bearer ${accessToken}`,\n 'Content-Type': 'application/json',\n 'developer-token': this.creds.developerToken,\n 'User-Agent': connectorUserAgent('google-ads'),\n };\n if (this.settings.loginCustomerId) {\n headers['login-customer-id'] = this.settings.loginCustomerId;\n }\n return headers;\n }\n\n private async searchPage<TRow>(\n phase: GoogleAdsPhase,\n range: DateRange,\n pageToken: string | null,\n signal?: AbortSignal,\n ): Promise<{ items: TRow[]; next: string | null }> {\n const token = await this.getAccessToken(signal);\n const url = `https://googleads.googleapis.com/${API_VERSION}/customers/${this.settings.customerId}/googleAds:search`;\n const body: Record<string, unknown> = {\n query: queryForPhase(phase, range),\n pageSize: PAGE_SIZE,\n };\n if (pageToken) {\n body.pageToken = pageToken;\n }\n const res = await this.post<SearchResponse<TRow>>(url, {\n resource: phase,\n headers: this.buildHeaders(token),\n body: JSON.stringify(body),\n signal,\n });\n return {\n items: res.body.results ?? [],\n next: res.body.nextPageToken ?? null,\n };\n }\n\n private async writePhase(\n phase: GoogleAdsPhase,\n items: unknown[],\n storage: StorageHandle,\n ): Promise<void> {\n switch (phase) {\n case 'campaigns': {\n for (const row of items as CampaignRow[]) {\n await storage.entity(campaignToEntity(row));\n }\n return;\n }\n case 'campaign_metrics': {\n const samples = (items as CampaignMetricRow[]).map(\n campaignMetricRowToSample,\n );\n await storage.metrics(samples, {\n names: [METRIC_NAME.campaign_metrics],\n });\n return;\n }\n case 'ad_group_metrics': {\n const samples = (items as AdGroupMetricRow[]).map(\n adGroupMetricRowToSample,\n );\n await storage.metrics(samples, {\n names: [METRIC_NAME.ad_group_metrics],\n });\n return;\n }\n case 'keyword_metrics': {\n const samples = (items as KeywordMetricRow[]).map(\n keywordMetricRowToSample,\n );\n await storage.metrics(samples, {\n names: [METRIC_NAME.keyword_metrics],\n });\n return;\n }\n }\n }\n\n private async clearScopeOnFirstPage(\n phase: GoogleAdsPhase,\n storage: StorageHandle,\n isFull: boolean,\n ): Promise<void> {\n if (phase === 'campaigns') {\n // Entities upsert by id, so only a full backfill needs to drop stale\n // rows; incremental ticks just overwrite the records they touch.\n if (isFull) {\n await storage.entities([], { types: [ENTITY_TYPE_CAMPAIGN] });\n }\n return;\n }\n // Metric phases always rewrite the requested date window - clearing by\n // name keeps writes idempotent across runs and prevents partial-page\n // failures from leaving orphaned samples.\n await storage.metrics([], { names: [METRIC_NAME[phase]] });\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const lookbackDays = this.settings.lookbackDays ?? DEFAULT_LOOKBACK_DAYS;\n const range = getDateRange(options, lookbackDays);\n const isFull = options.mode === 'full';\n\n const phases = selectActivePhases<GoogleAdsResource, GoogleAdsPhase>(\n (r) => r,\n PHASE_ORDER,\n this.settings.resources,\n );\n\n const cursor = isGoogleAdsSyncCursor(options.cursor)\n ? options.cursor\n : undefined;\n\n return paginateChunked<GoogleAdsPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: (phase, page, sig) =>\n this.searchPage<unknown>(phase, range, page, sig),\n writeBatch: async (phase, items, page) => {\n if (page === null) {\n await this.clearScopeOnFirstPage(phase, storage, isFull);\n }\n await this.writePhase(phase, items, storage);\n },\n });\n }\n}\n","import { GoogleAdsConnector } from './google-ads';\n\nexport {\n adGroupMetricRowToSample,\n campaignMetricRowToSample,\n campaignToEntity,\n configFields,\n doc,\n getDateRange,\n GoogleAdsConnector,\n keywordMetricRowToSample,\n} from './google-ads';\nexport type { GoogleAdsResource, GoogleAdsSettings } from './google-ads';\nexport default GoogleAdsConnector;\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;AAMX,IAAM,eAAe;AAAA,EAC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;AACD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAc,sBACZ,OACA,SACA,QACe;AACf,QAAI,UAAU,aAAa;AAGzB,UAAI,QAAQ;AACV,cAAM,QAAQ,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,oBAAoB,EAAE,CAAC;AAAA,MAC9D;AACA;AAAA,IACF;AAIA,UAAM,QAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC,YAAY,KAAK,CAAC,EAAE,CAAC;AAAA,EAC3D;AAAA,EAEA,MAAM,KACJ,SACA,SACA,QACqB;AACrB,UAAM,eAAe,KAAK,SAAS,gBAAgB;AACnD,UAAM,QAAQ,aAAa,SAAS,YAAY;AAChD,UAAM,SAAS,QAAQ,SAAS;AAEhC,UAAM,SAAS;AAAA,MACb,CAAC,MAAM;AAAA,MACP;AAAA,MACA,KAAK,SAAS;AAAA,IAChB;AAEA,UAAM,SAAS,sBAAsB,QAAQ,MAAM,IAC/C,QAAQ,SACR;AAEJ,WAAO,gBAAwC;AAAA,MAC7C;AAAA,MACA;AAAA,MACA;AAAA,MACA,QAAQ,KAAK;AAAA,MACb,WAAW,CAAC,OAAO,MAAM,QACvB,KAAK,WAAoB,OAAO,OAAO,MAAM,GAAG;AAAA,MAClD,YAAY,OAAO,OAAO,OAAO,SAAS;AACxC,YAAI,SAAS,MAAM;AACjB,gBAAM,KAAK,sBAAsB,OAAO,SAAS,MAAM;AAAA,QACzD;AACA,cAAM,KAAK,WAAW,OAAO,OAAO,OAAO;AAAA,MAC7C;AAAA,IACF,CAAC;AAAA,EACH;AACF;;;AC13BA,IAAO,gBAAQ;","names":["startMs"]}
|
|
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/google-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\n// ---------------------------------------------------------------------------\n// configFields / doc\n// ---------------------------------------------------------------------------\n\nexport const configFields = defineConfigFields(\n z.object({\n customerId: z\n .string()\n .trim()\n .regex(\n /^\\d{10}$/,\n 'customerId must be the 10-digit Google Ads ID, digits only (no dashes)',\n )\n .meta({\n label: 'Customer ID',\n description:\n 'Google Ads customer ID for the account to sync, digits only (the dashed form 123-456-7890 with the dashes removed).',\n placeholder: '1234567890',\n }),\n loginCustomerId: z\n .string()\n .trim()\n .regex(\n /^\\d{10}$/,\n 'loginCustomerId must be a 10-digit Google Ads ID, digits only',\n )\n .optional()\n .meta({\n label: 'Login Customer ID (MCC)',\n description:\n 'Manager (MCC) account ID, digits only. Set this when the OAuth credential authenticates against an MCC that owns the customer account.',\n placeholder: '1234567890',\n }),\n clientId: z.string().min(1).meta({\n label: 'OAuth Client ID',\n description:\n 'OAuth 2.0 client ID from a Google Cloud project that has the Google Ads API enabled.',\n placeholder: '…apps.googleusercontent.com',\n }),\n clientSecret: z.object({ $secret: z.string() }).meta({\n label: 'OAuth Client Secret',\n description: 'OAuth 2.0 client secret paired with the client ID above.',\n secret: true,\n }),\n refreshToken: z.object({ $secret: z.string() }).meta({\n label: 'OAuth Refresh Token',\n description:\n 'Google OAuth 2.0 refresh token issued for the https://www.googleapis.com/auth/adwords scope.',\n secret: true,\n }),\n developerToken: z.object({ $secret: z.string() }).meta({\n label: 'Developer Token',\n description:\n 'Google Ads API developer token from the manager account that owns API access (Tools → API Center).',\n secret: true,\n }),\n lookbackDays: z.number().int().positive().optional().meta({\n label: 'Lookback days (full sync)',\n description:\n 'How many calendar days of metric history 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_metrics',\n 'ad_group_metrics',\n 'keyword_metrics',\n ]),\n )\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which Google Ads resources to sync. Omit to sync everything; pin a subset to avoid pulling keyword-level metrics on a quota-limited token.',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'Google Ads',\n category: 'marketing',\n brandColor: '#4285F4',\n tagline:\n 'Sync Google Ads campaigns plus daily campaign, ad-group, and keyword performance (impressions, clicks, cost, conversions) via GAQL.',\n vendor: {\n name: 'Google Ads',\n apiDocs: 'https://developers.google.com/google-ads/api/docs/start',\n website: 'https://ads.google.com',\n },\n auth: {\n summary:\n 'OAuth 2.0 refresh token against an account with read access to the Google Ads customer, plus a developer token from the manager account that owns API access.',\n setup: [\n 'Apply for Google Ads API access from your manager account (Tools → API Center). Copy the developer token - it lives on the manager, not the child account.',\n 'In Google Cloud Console, enable the Google Ads API on a project, create an OAuth 2.0 client ID, and complete the OAuth consent flow for the adwords scope to obtain a refresh token. The official walkthrough is at https://developers.google.com/google-ads/api/docs/oauth/overview.',\n 'Find the Google Ads customer ID at the top of the Ads UI (e.g. 123-456-7890) and store it without dashes (e.g. 1234567890).',\n 'If the OAuth credential authenticates against an MCC that owns the customer, set `loginCustomerId` to the MCC id (digits only). For a direct-access account, omit it.',\n 'Store the client secret, refresh token, and developer token as secrets, then reference them as `clientSecret: secret(\"GADS_CLIENT_SECRET\")`, `refreshToken: secret(\"GADS_REFRESH_TOKEN\")`, and `developerToken: secret(\"GADS_DEVELOPER_TOKEN\")`.',\n ],\n },\n rateLimit:\n 'Google Ads API basic-access tokens get a 15,000 operations / day quota per developer token; the connector treats 429 (RESOURCE_EXHAUSTED) as a transient error and the host backs off.',\n limitations: [\n 'Cost values are stored in account currency units (cost_micros ÷ 1,000,000); the original micro-precision integer is also exposed in attributes.',\n 'Keyword metrics use the historical (per-day) quality score from `metrics.historical_quality_score`; criteria with no impressions on a day will report a null quality score.',\n 'Incremental syncs trail the last 3 days because Google Ads can attribute conversions to a click up to 3 days after the event.',\n 'Audience-, asset-, and recommendation-level reporting are out of scope; this connector covers campaign / ad-group / keyword performance only.',\n ],\n});\n\n// ---------------------------------------------------------------------------\n// Settings / credentials\n// ---------------------------------------------------------------------------\n\nexport interface GoogleAdsSettings {\n customerId: string;\n loginCustomerId?: string;\n lookbackDays?: number;\n resources?: readonly GoogleAdsResource[];\n}\n\nconst googleAdsCredentials = {\n clientId: {\n description: 'Google OAuth 2.0 client ID (public, not a secret)',\n auth: 'required' as const,\n },\n clientSecret: {\n description: 'Google OAuth 2.0 client secret',\n auth: 'required' as const,\n },\n refreshToken: {\n description: 'Google OAuth 2.0 refresh token with the adwords scope',\n auth: 'required' as const,\n },\n developerToken: {\n description: 'Google Ads API developer token',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype GoogleAdsCredentials = typeof googleAdsCredentials;\n\n// ---------------------------------------------------------------------------\n// Sync phases + cursor\n// ---------------------------------------------------------------------------\n\nconst PHASE_ORDER = [\n 'campaigns',\n 'campaign_metrics',\n 'ad_group_metrics',\n 'keyword_metrics',\n] as const;\n\ntype GoogleAdsPhase = (typeof PHASE_ORDER)[number];\n\nexport type GoogleAdsResource = GoogleAdsPhase;\n\nconst isGoogleAdsSyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\nconst API_VERSION = 'v18';\nconst PAGE_SIZE = 10_000;\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\nconst DEFAULT_LOOKBACK_DAYS = 90;\nconst INCREMENTAL_LOOKBACK_DAYS = 3;\nconst MICROS_PER_UNIT = 1_000_000;\nconst TOKEN_URL = 'https://oauth2.googleapis.com/token';\n\nconst ENTITY_TYPE_CAMPAIGN = 'google_ads_campaign';\nconst METRIC_NAME: Record<GoogleAdsPhase, string> = {\n campaigns: ENTITY_TYPE_CAMPAIGN,\n campaign_metrics: 'google_ads_campaign_metrics',\n ad_group_metrics: 'google_ads_ad_group_metrics',\n keyword_metrics: 'google_ads_keyword_metrics',\n};\n\n// ---------------------------------------------------------------------------\n// Google Ads API response shapes (GAQL search)\n// ---------------------------------------------------------------------------\n\n// INT64 fields come back as JSON strings; everything else may be string|number\n// depending on the field. We coerce in the writers. Empty strings aren't a\n// valid representation of any numeric value upstream, so the schema rejects\n// them - that also keeps fast-check from generating zero-length entity ids.\nconst int64String = z.union([z.string().min(1), z.number()]);\n\nconst segmentsSchema = z.object({\n date: z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/),\n});\n\nconst dateString = z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/);\n\nconst campaignFieldsSchema = z.object({\n id: int64String,\n name: z.string().nullish(),\n status: z.string().nullish(),\n biddingStrategyType: z.string().nullish(),\n startDate: dateString.nullish(),\n endDate: dateString.nullish(),\n resourceName: z.string().nullish(),\n});\n\nconst metricsSchema = z.object({\n impressions: int64String.nullish(),\n clicks: int64String.nullish(),\n costMicros: int64String.nullish(),\n conversions: z.number().nullish(),\n conversionsValue: z.number().nullish(),\n historicalQualityScore: int64String.nullish(),\n});\n\nconst campaignRowSchema = z.object({\n campaign: campaignFieldsSchema,\n});\n\nconst campaignMetricRowSchema = z.object({\n segments: segmentsSchema,\n campaign: z.object({\n id: int64String,\n name: z.string().nullish(),\n resourceName: z.string().nullish(),\n }),\n metrics: metricsSchema,\n});\n\nconst adGroupMetricRowSchema = z.object({\n segments: segmentsSchema,\n campaign: z.object({ id: int64String }).nullish(),\n adGroup: z.object({\n id: int64String,\n name: z.string().nullish(),\n resourceName: z.string().nullish(),\n }),\n metrics: metricsSchema,\n});\n\nconst keywordMetricRowSchema = z.object({\n segments: segmentsSchema,\n adGroup: z.object({ id: int64String }).nullish(),\n adGroupCriterion: z.object({\n criterionId: int64String,\n keyword: z\n .object({\n text: z.string().nullish(),\n matchType: z.string().nullish(),\n })\n .nullish(),\n resourceName: z.string().nullish(),\n }),\n metrics: metricsSchema,\n});\n\nconst campaignsResponseSchema = z.array(campaignRowSchema);\nconst campaignMetricsResponseSchema = z.array(campaignMetricRowSchema);\nconst adGroupMetricsResponseSchema = z.array(adGroupMetricRowSchema);\nconst keywordMetricsResponseSchema = z.array(keywordMetricRowSchema);\n\ntype CampaignRow = z.infer<typeof campaignRowSchema>;\ntype CampaignMetricRow = z.infer<typeof campaignMetricRowSchema>;\ntype AdGroupMetricRow = z.infer<typeof adGroupMetricRowSchema>;\ntype KeywordMetricRow = z.infer<typeof keywordMetricRowSchema>;\n\nexport const googleAdsResources = defineResources({\n [ENTITY_TYPE_CAMPAIGN]: {\n shape: 'entity',\n description:\n 'Google Ads campaigns with id, name, status, bidding strategy type, and start / end dates.',\n endpoint: 'POST /v18/customers/{customerId}/googleAds:search',\n fields: [\n { name: 'id', description: 'Numeric Google Ads campaign id.' },\n { name: 'name', description: 'Campaign display name.' },\n {\n name: 'status',\n description:\n 'Campaign status (ENABLED, PAUSED, REMOVED, UNKNOWN, UNSPECIFIED).',\n },\n {\n name: 'biddingStrategyType',\n description:\n 'Bidding strategy in use (e.g. MAXIMIZE_CONVERSIONS, MANUAL_CPC).',\n },\n { name: 'startDate', description: 'Campaign start date (YYYY-MM-DD).' },\n {\n name: 'endDate',\n description: 'Campaign end date (YYYY-MM-DD), if set.',\n },\n ],\n responses: {\n oauth_token: z.object({\n access_token: z.string().min(1),\n expires_in: z.number().int().positive().optional(),\n }),\n campaigns: campaignsResponseSchema,\n },\n },\n google_ads_campaign_metrics: {\n shape: 'metric',\n description:\n 'Daily campaign performance - impressions, clicks, cost, conversions, and conversion value per (date, campaignId).',\n endpoint: 'POST /v18/customers/{customerId}/googleAds:search',\n unit: 'cost',\n granularity: 'day',\n dimensions: [\n { name: 'date', description: 'Calendar day of the metric sample.' },\n { name: 'campaignId', description: 'Numeric Google Ads campaign id.' },\n {\n name: 'campaignName',\n description: 'Campaign display name at sync time.',\n },\n { name: 'impressions', description: 'Ad impressions served on the day.' },\n { name: 'clicks', description: 'Clicks recorded on the day.' },\n {\n name: 'cost',\n description:\n 'Cost in account currency units (cost_micros ÷ 1,000,000).',\n },\n {\n name: 'costMicros',\n description: 'Raw cost in micros, as returned by the API.',\n },\n {\n name: 'conversions',\n description: 'Counted conversions attributed to the day.',\n },\n {\n name: 'conversionsValue',\n description: 'Total value of conversions for the day.',\n },\n ],\n notes:\n 'Sample value is `cost` (account currency units). All other fields are mirrored in attributes for filtering and ratio metrics (CPA = cost / conversions, ROAS = conversionsValue / cost).',\n responses: { campaign_metrics: campaignMetricsResponseSchema },\n },\n google_ads_ad_group_metrics: {\n shape: 'metric',\n description:\n 'Daily ad-group performance - impressions, clicks, cost, and conversions per (date, adGroupId).',\n endpoint: 'POST /v18/customers/{customerId}/googleAds:search',\n unit: 'cost',\n granularity: 'day',\n dimensions: [\n { name: 'date', description: 'Calendar day of the metric sample.' },\n { name: 'adGroupId', description: 'Numeric Google Ads ad-group id.' },\n {\n name: 'adGroupName',\n description: 'Ad-group display name at sync time.',\n },\n { name: 'campaignId', description: 'Parent campaign id.' },\n { name: 'impressions', description: 'Ad impressions served on the day.' },\n { name: 'clicks', description: 'Clicks recorded on the day.' },\n { name: 'cost', description: 'Cost in account currency units.' },\n {\n name: 'costMicros',\n description: 'Raw cost in micros, as returned by the API.',\n },\n {\n name: 'conversions',\n description: 'Counted conversions attributed to the day.',\n },\n ],\n responses: { ad_group_metrics: adGroupMetricsResponseSchema },\n },\n google_ads_keyword_metrics: {\n shape: 'metric',\n description:\n 'Daily keyword performance - impressions, clicks, cost, and historical quality score per (date, criterionId).',\n endpoint: 'POST /v18/customers/{customerId}/googleAds:search',\n unit: 'cost',\n granularity: 'day',\n dimensions: [\n { name: 'date', description: 'Calendar day of the metric sample.' },\n {\n name: 'criterionId',\n description: 'Numeric keyword (ad-group criterion) id.',\n },\n { name: 'keywordText', description: 'Keyword text.' },\n {\n name: 'matchType',\n description: 'Match type (EXACT, PHRASE, BROAD, …).',\n },\n { name: 'adGroupId', description: 'Parent ad-group id.' },\n { name: 'impressions', description: 'Ad impressions served on the day.' },\n { name: 'clicks', description: 'Clicks recorded on the day.' },\n { name: 'cost', description: 'Cost in account currency units.' },\n {\n name: 'costMicros',\n description: 'Raw cost in micros, as returned by the API.',\n },\n {\n name: 'qualityScore',\n description:\n 'Historical quality score for the day (1-10), null when no impressions.',\n },\n ],\n notes:\n 'Driven by `keyword_view`; the cost / impression columns roll up to the criterion-day pair.',\n responses: { keyword_metrics: keywordMetricsResponseSchema },\n },\n});\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction toDateString(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\nconst DATE_RE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\nfunction dateStringToMs(yyyyMmDd: string): number {\n // Reject anything that doesn't match YYYY-MM-DD so a surprise upstream\n // value (e.g. an empty string or a malformed date) doesn't write NaN into\n // entity.updated_at / metric.ts.\n const m = DATE_RE.exec(yyyyMmDd);\n if (!m) {\n return 0;\n }\n const ms = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));\n return Number.isFinite(ms) ? ms : 0;\n}\n\ninterface DateRange {\n startDate: string;\n endDate: string;\n}\n\nexport function getDateRange(\n options: SyncOptions,\n lookbackDays: number,\n now: number = Date.now(),\n): DateRange {\n const endDate = toDateString(new Date(now));\n if (options.mode === 'latest') {\n const startMs = now - (INCREMENTAL_LOOKBACK_DAYS - 1) * MS_PER_DAY;\n return { startDate: toDateString(new Date(startMs)), endDate };\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 { startDate: toDateString(new Date(startMs)), endDate };\n }\n }\n const startMs = now - (lookbackDays - 1) * MS_PER_DAY;\n return { startDate: toDateString(new Date(startMs)), endDate };\n}\n\nfunction coerceInt(value: unknown): number {\n if (typeof value === 'number') {\n return Number.isFinite(value) ? value : 0;\n }\n if (typeof value === 'string' && value !== '') {\n const n = Number(value);\n return Number.isFinite(n) ? n : 0;\n }\n return 0;\n}\n\nfunction coerceIntOrNull(value: unknown): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n const n = coerceInt(value);\n return n;\n}\n\nfunction microsToUnits(micros: unknown): number {\n return coerceInt(micros) / MICROS_PER_UNIT;\n}\n\n// ---------------------------------------------------------------------------\n// GAQL queries - one per phase. Date ranges are interpolated, not parameterised\n// (GAQL has no bind variables); range bounds are server-side string literals.\n// ---------------------------------------------------------------------------\n\nfunction campaignsQuery(): string {\n return [\n 'SELECT',\n ' campaign.id,',\n ' campaign.name,',\n ' campaign.status,',\n ' campaign.bidding_strategy_type,',\n ' campaign.start_date,',\n ' campaign.end_date',\n 'FROM campaign',\n ].join(' ');\n}\n\nfunction campaignMetricsQuery(range: DateRange): string {\n return [\n 'SELECT',\n ' segments.date,',\n ' campaign.id,',\n ' campaign.name,',\n ' metrics.impressions,',\n ' metrics.clicks,',\n ' metrics.cost_micros,',\n ' metrics.conversions,',\n ' metrics.conversions_value',\n 'FROM campaign',\n `WHERE segments.date BETWEEN '${range.startDate}' AND '${range.endDate}'`,\n ].join(' ');\n}\n\nfunction adGroupMetricsQuery(range: DateRange): string {\n return [\n 'SELECT',\n ' segments.date,',\n ' campaign.id,',\n ' ad_group.id,',\n ' ad_group.name,',\n ' metrics.impressions,',\n ' metrics.clicks,',\n ' metrics.cost_micros,',\n ' metrics.conversions',\n 'FROM ad_group',\n `WHERE segments.date BETWEEN '${range.startDate}' AND '${range.endDate}'`,\n ].join(' ');\n}\n\nfunction keywordMetricsQuery(range: DateRange): string {\n return [\n 'SELECT',\n ' segments.date,',\n ' ad_group.id,',\n ' ad_group_criterion.criterion_id,',\n ' ad_group_criterion.keyword.text,',\n ' ad_group_criterion.keyword.match_type,',\n ' metrics.impressions,',\n ' metrics.clicks,',\n ' metrics.cost_micros,',\n ' metrics.historical_quality_score',\n 'FROM keyword_view',\n `WHERE segments.date BETWEEN '${range.startDate}' AND '${range.endDate}'`,\n ].join(' ');\n}\n\nfunction queryForPhase(phase: GoogleAdsPhase, range: DateRange): string {\n switch (phase) {\n case 'campaigns':\n return campaignsQuery();\n case 'campaign_metrics':\n return campaignMetricsQuery(range);\n case 'ad_group_metrics':\n return adGroupMetricsQuery(range);\n case 'keyword_metrics':\n return keywordMetricsQuery(range);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Row → storage write helpers\n// ---------------------------------------------------------------------------\n\nexport function campaignToEntity(row: CampaignRow): {\n type: string;\n id: string;\n attributes: Record<string, string | number | null>;\n updated_at: number;\n} {\n const c = row.campaign;\n // Campaign upstream has no updated_at field. Use the start_date as a stable\n // freshness signal so re-syncs of the same row don't churn updated_at; for\n // campaigns with no start_date (rare), fall back to 0 which still makes the\n // upsert idempotent.\n const startMs = c.startDate ? dateStringToMs(c.startDate) : 0;\n return {\n type: ENTITY_TYPE_CAMPAIGN,\n id: String(c.id),\n attributes: {\n name: c.name ?? null,\n status: c.status ?? null,\n biddingStrategyType: c.biddingStrategyType ?? null,\n startDate: c.startDate ?? null,\n endDate: c.endDate ?? null,\n resourceName: c.resourceName ?? null,\n },\n updated_at: startMs,\n };\n}\n\nexport function campaignMetricRowToSample(row: CampaignMetricRow): {\n name: string;\n ts: number;\n value: number;\n attributes: Record<string, string | number | null>;\n} {\n const m = row.metrics;\n const cost = microsToUnits(m.costMicros);\n return {\n name: METRIC_NAME.campaign_metrics,\n ts: dateStringToMs(row.segments.date),\n value: cost,\n attributes: {\n date: row.segments.date,\n campaignId: String(row.campaign.id),\n campaignName: row.campaign.name ?? null,\n impressions: coerceInt(m.impressions),\n clicks: coerceInt(m.clicks),\n cost,\n costMicros: coerceInt(m.costMicros),\n conversions: typeof m.conversions === 'number' ? m.conversions : 0,\n conversionsValue:\n typeof m.conversionsValue === 'number' ? m.conversionsValue : 0,\n },\n };\n}\n\nexport function adGroupMetricRowToSample(row: AdGroupMetricRow): {\n name: string;\n ts: number;\n value: number;\n attributes: Record<string, string | number | null>;\n} {\n const m = row.metrics;\n const cost = microsToUnits(m.costMicros);\n return {\n name: METRIC_NAME.ad_group_metrics,\n ts: dateStringToMs(row.segments.date),\n value: cost,\n attributes: {\n date: row.segments.date,\n adGroupId: String(row.adGroup.id),\n adGroupName: row.adGroup.name ?? null,\n campaignId: row.campaign?.id != null ? String(row.campaign.id) : null,\n impressions: coerceInt(m.impressions),\n clicks: coerceInt(m.clicks),\n cost,\n costMicros: coerceInt(m.costMicros),\n conversions: typeof m.conversions === 'number' ? m.conversions : 0,\n },\n };\n}\n\nexport function keywordMetricRowToSample(row: KeywordMetricRow): {\n name: string;\n ts: number;\n value: number;\n attributes: Record<string, string | number | null>;\n} {\n const m = row.metrics;\n const cost = microsToUnits(m.costMicros);\n return {\n name: METRIC_NAME.keyword_metrics,\n ts: dateStringToMs(row.segments.date),\n value: cost,\n attributes: {\n date: row.segments.date,\n criterionId: String(row.adGroupCriterion.criterionId),\n keywordText: row.adGroupCriterion.keyword?.text ?? null,\n matchType: row.adGroupCriterion.keyword?.matchType ?? null,\n adGroupId: row.adGroup?.id != null ? String(row.adGroup.id) : null,\n impressions: coerceInt(m.impressions),\n clicks: coerceInt(m.clicks),\n cost,\n costMicros: coerceInt(m.costMicros),\n qualityScore: coerceIntOrNull(m.historicalQualityScore),\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// GoogleAdsConnector\n// ---------------------------------------------------------------------------\n\ninterface TokenResponse {\n access_token: string;\n expires_in?: number;\n}\n\ninterface SearchResponse<TRow> {\n results?: TRow[];\n nextPageToken?: string;\n}\n\nexport const id = 'google-ads';\n\nexport class GoogleAdsConnector extends BaseConnector<\n GoogleAdsSettings,\n GoogleAdsCredentials\n> {\n static readonly id = id;\n\n static readonly resources = googleAdsResources;\n\n static readonly schemas = schemasFromResources(googleAdsResources);\n\n static create(input: unknown, ctx?: ConnectorContext): GoogleAdsConnector {\n const parsed = configFields.parse(input);\n return new GoogleAdsConnector(\n {\n customerId: parsed.customerId,\n loginCustomerId: parsed.loginCustomerId,\n lookbackDays: parsed.lookbackDays,\n resources: parsed.resources,\n },\n {\n clientId: parsed.clientId,\n clientSecret: parsed.clientSecret,\n refreshToken: parsed.refreshToken,\n developerToken: parsed.developerToken,\n },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = googleAdsCredentials;\n\n private cachedToken: { token: string; expiresAt: number } | null = null;\n\n private async fetchAccessToken(\n signal: AbortSignal | undefined,\n ): Promise<{ token: string; expiresAt: number }> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: this.creds.clientId,\n client_secret: this.creds.clientSecret,\n refresh_token: this.creds.refreshToken,\n }).toString();\n const res = await this.post<TokenResponse>(TOKEN_URL, {\n resource: 'oauth_token',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body,\n signal,\n });\n const expiresIn = res.body.expires_in ?? 3600;\n return {\n token: res.body.access_token,\n // Refresh 60s before expiry so a long-running phase doesn't 401 on the\n // boundary.\n expiresAt: Date.now() + (expiresIn - 60) * 1000,\n };\n }\n\n private async getAccessToken(signal?: AbortSignal): Promise<string> {\n if (this.cachedToken && Date.now() < this.cachedToken.expiresAt) {\n return this.cachedToken.token;\n }\n this.cachedToken = await this.fetchAccessToken(signal);\n return this.cachedToken.token;\n }\n\n private buildHeaders(accessToken: string): Record<string, string> {\n const headers: Record<string, string> = {\n Authorization: `Bearer ${accessToken}`,\n 'Content-Type': 'application/json',\n 'developer-token': this.creds.developerToken,\n 'User-Agent': connectorUserAgent('google-ads'),\n };\n if (this.settings.loginCustomerId) {\n headers['login-customer-id'] = this.settings.loginCustomerId;\n }\n return headers;\n }\n\n private async searchPage<TRow>(\n phase: GoogleAdsPhase,\n range: DateRange,\n pageToken: string | null,\n signal?: AbortSignal,\n ): Promise<{ items: TRow[]; next: string | null }> {\n const token = await this.getAccessToken(signal);\n const url = `https://googleads.googleapis.com/${API_VERSION}/customers/${this.settings.customerId}/googleAds:search`;\n const body: Record<string, unknown> = {\n query: queryForPhase(phase, range),\n pageSize: PAGE_SIZE,\n };\n if (pageToken) {\n body.pageToken = pageToken;\n }\n const res = await this.post<SearchResponse<TRow>>(url, {\n resource: phase,\n headers: this.buildHeaders(token),\n body: JSON.stringify(body),\n signal,\n });\n return {\n items: res.body.results ?? [],\n next: res.body.nextPageToken ?? null,\n };\n }\n\n private async writePhase(\n phase: GoogleAdsPhase,\n items: unknown[],\n storage: StorageHandle,\n ): Promise<void> {\n switch (phase) {\n case 'campaigns': {\n for (const row of items as CampaignRow[]) {\n await storage.entity(campaignToEntity(row));\n }\n return;\n }\n case 'campaign_metrics': {\n const samples = (items as CampaignMetricRow[]).map(\n campaignMetricRowToSample,\n );\n await storage.metrics(samples, {\n names: [METRIC_NAME.campaign_metrics],\n });\n return;\n }\n case 'ad_group_metrics': {\n const samples = (items as AdGroupMetricRow[]).map(\n adGroupMetricRowToSample,\n );\n await storage.metrics(samples, {\n names: [METRIC_NAME.ad_group_metrics],\n });\n return;\n }\n case 'keyword_metrics': {\n const samples = (items as KeywordMetricRow[]).map(\n keywordMetricRowToSample,\n );\n await storage.metrics(samples, {\n names: [METRIC_NAME.keyword_metrics],\n });\n return;\n }\n }\n }\n\n private async clearScopeOnFirstPage(\n phase: GoogleAdsPhase,\n storage: StorageHandle,\n isFull: boolean,\n ): Promise<void> {\n if (phase === 'campaigns') {\n // Entities upsert by id, so only a full backfill needs to drop stale\n // rows; incremental ticks just overwrite the records they touch.\n if (isFull) {\n await storage.entities([], { types: [ENTITY_TYPE_CAMPAIGN] });\n }\n return;\n }\n // Metric phases always rewrite the requested date window - clearing by\n // name keeps writes idempotent across runs and prevents partial-page\n // failures from leaving orphaned samples.\n await storage.metrics([], { names: [METRIC_NAME[phase]] });\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const lookbackDays = this.settings.lookbackDays ?? DEFAULT_LOOKBACK_DAYS;\n const range = getDateRange(options, lookbackDays);\n const isFull = options.mode === 'full';\n\n const phases = selectActivePhases<GoogleAdsResource, GoogleAdsPhase>(\n (r) => r,\n PHASE_ORDER,\n this.settings.resources,\n );\n\n const cursor = isGoogleAdsSyncCursor(options.cursor)\n ? options.cursor\n : undefined;\n\n return paginateChunked<GoogleAdsPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: (phase, page, sig) =>\n this.searchPage<unknown>(phase, range, page, sig),\n writeBatch: async (phase, items, page) => {\n if (page === null) {\n await this.clearScopeOnFirstPage(phase, storage, isFull);\n }\n await this.writePhase(phase, items, storage);\n },\n });\n }\n}\n","import { GoogleAdsConnector } from './google-ads';\n\nexport {\n adGroupMetricRowToSample,\n campaignMetricRowToSample,\n campaignToEntity,\n configFields,\n doc,\n getDateRange,\n GoogleAdsConnector,\n googleAdsResources as resources,\n id,\n keywordMetricRowToSample,\n} from './google-ads';\nexport type { GoogleAdsResource, GoogleAdsSettings } from './google-ads';\nexport default GoogleAdsConnector;\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;AAMX,IAAM,eAAe;AAAA,EAC1B,EAAE,OAAO;AAAA,IACP,YAAY,EACT,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,iBAAiB,EACd,OAAO,EACP,KAAK,EACL;AAAA,MACC;AAAA,MACA;AAAA,IACF,EACC,SAAS,EACT,KAAK;AAAA,MACJ,OAAO;AAAA,MACP,aACE;AAAA,MACF,aAAa;AAAA,IACf,CAAC;AAAA,IACH,UAAU,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,KAAK;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AAe,KAAK,SAAS,gBAAgB;AACnD,UAAM,QAAQ,aAAa,SAAS,YAAY;AAChD,UAAM,SAAS,QAAQ,SAAS;AAEhC,UAAM,SAAS;AAAA,MACb,CAAC,MAAM;AAAA,MACP;AAAA,MACA,KAAK,SAAS;AAAA,IAChB;AAEA,UAAM,SAAS,sBAAsB,QAAQ,MAAM,IAC/C,QAAQ,SACR;AAEJ,WAAO,gBAAwC;AAAA,MAC7C;AAAA,MACA;AAAA,MACA;AAAA,MACA,QAAQ,KAAK;AAAA,MACb,WAAW,CAAC,OAAO,MAAM,QACvB,KAAK,WAAoB,OAAO,OAAO,MAAM,GAAG;AAAA,MAClD,YAAY,OAAO,OAAO,OAAO,SAAS;AACxC,YAAI,SAAS,MAAM;AACjB,gBAAM,KAAK,sBAAsB,OAAO,SAAS,MAAM;AAAA,QACzD;AACA,cAAM,KAAK,WAAW,OAAO,OAAO,OAAO;AAAA,MAC7C;AAAA,IACF,CAAC;AAAA,EACH;AACF;;;AC13BA,IAAO,gBAAQ;","names":["startMs"]}
|
package/package.json
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rawdash/connector-google-ads",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.18.0",
|
|
4
4
|
"description": "Rawdash connector for Google Ads — syncs campaigns plus daily campaign / ad-group / keyword performance metrics into the six-shape storage model",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
7
8
|
"repository": {
|
|
8
9
|
"type": "git",
|
|
9
10
|
"url": "https://github.com/rawdash/rawdash.git",
|
|
@@ -21,22 +22,22 @@
|
|
|
21
22
|
"import": "./dist/index.js"
|
|
22
23
|
}
|
|
23
24
|
},
|
|
24
|
-
"scripts": {
|
|
25
|
-
"build": "tsup",
|
|
26
|
-
"typecheck": "tsc --noEmit",
|
|
27
|
-
"lint": "eslint src",
|
|
28
|
-
"test": "vitest run"
|
|
29
|
-
},
|
|
30
25
|
"dependencies": {
|
|
31
|
-
"
|
|
32
|
-
"
|
|
26
|
+
"zod": "^4.4.3",
|
|
27
|
+
"@rawdash/core": "0.18.0"
|
|
33
28
|
},
|
|
34
29
|
"devDependencies": {
|
|
35
|
-
"@rawdash/connector-shared": "workspace:*",
|
|
36
|
-
"@rawdash/connector-test-utils": "workspace:*",
|
|
37
30
|
"fast-check": "^4.8.0",
|
|
38
31
|
"tsup": "^8.0.0",
|
|
39
32
|
"typescript": "^5.7.2",
|
|
40
|
-
"vitest": "^4.1.4"
|
|
33
|
+
"vitest": "^4.1.4",
|
|
34
|
+
"@rawdash/connector-shared": "0.3.0",
|
|
35
|
+
"@rawdash/connector-test-utils": "0.0.5"
|
|
36
|
+
},
|
|
37
|
+
"scripts": {
|
|
38
|
+
"build": "tsup",
|
|
39
|
+
"typecheck": "tsc --noEmit",
|
|
40
|
+
"lint": "eslint src",
|
|
41
|
+
"test": "vitest run"
|
|
41
42
|
}
|
|
42
|
-
}
|
|
43
|
+
}
|