@squadbase/vite-server 0.1.2 → 0.1.3-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/cli/index.js +13609 -3797
  2. package/dist/connectors/airtable-oauth.js +12 -4
  3. package/dist/connectors/amplitude.js +335 -32
  4. package/dist/connectors/asana.d.ts +5 -0
  5. package/dist/connectors/asana.js +661 -0
  6. package/dist/connectors/attio.js +304 -36
  7. package/dist/connectors/customerio.d.ts +5 -0
  8. package/dist/connectors/customerio.js +633 -0
  9. package/dist/connectors/gmail-oauth.d.ts +5 -0
  10. package/dist/connectors/gmail-oauth.js +639 -0
  11. package/dist/connectors/google-ads-oauth.js +14 -8
  12. package/dist/connectors/google-ads.d.ts +5 -0
  13. package/dist/connectors/google-ads.js +784 -0
  14. package/dist/connectors/google-analytics-oauth.js +16 -8
  15. package/dist/connectors/google-sheets-oauth.js +12 -4
  16. package/dist/connectors/google-sheets.d.ts +5 -0
  17. package/dist/connectors/google-sheets.js +598 -0
  18. package/dist/connectors/hubspot-oauth.js +12 -4
  19. package/dist/connectors/hubspot.d.ts +5 -0
  20. package/dist/connectors/hubspot.js +550 -0
  21. package/dist/connectors/intercom-oauth.d.ts +5 -0
  22. package/dist/connectors/intercom-oauth.js +510 -0
  23. package/dist/connectors/intercom.d.ts +5 -0
  24. package/dist/connectors/intercom.js +627 -0
  25. package/dist/connectors/jira-api-key.d.ts +5 -0
  26. package/dist/connectors/jira-api-key.js +523 -0
  27. package/dist/connectors/kintone-api-token.js +16 -20
  28. package/dist/connectors/linkedin-ads-oauth.d.ts +5 -0
  29. package/dist/connectors/linkedin-ads-oauth.js +774 -0
  30. package/dist/connectors/linkedin-ads.d.ts +5 -0
  31. package/dist/connectors/linkedin-ads.js +782 -0
  32. package/dist/connectors/mailchimp-oauth.d.ts +5 -0
  33. package/dist/connectors/mailchimp-oauth.js +539 -0
  34. package/dist/connectors/mailchimp.d.ts +5 -0
  35. package/dist/connectors/mailchimp.js +646 -0
  36. package/dist/connectors/shopify-oauth.js +12 -4
  37. package/dist/connectors/shopify.js +500 -80
  38. package/dist/connectors/stripe-oauth.js +12 -4
  39. package/dist/connectors/zendesk-oauth.d.ts +5 -0
  40. package/dist/connectors/zendesk-oauth.js +505 -0
  41. package/dist/connectors/zendesk.d.ts +5 -0
  42. package/dist/connectors/zendesk.js +631 -0
  43. package/dist/index.js +13594 -3782
  44. package/dist/main.js +13596 -3784
  45. package/dist/vite-plugin.js +13596 -3784
  46. package/package.json +46 -2
@@ -0,0 +1,784 @@
1
+ // ../connectors/src/parameter-definition.ts
2
+ var ParameterDefinition = class {
3
+ slug;
4
+ name;
5
+ description;
6
+ envVarBaseKey;
7
+ type;
8
+ secret;
9
+ required;
10
+ constructor(config) {
11
+ this.slug = config.slug;
12
+ this.name = config.name;
13
+ this.description = config.description;
14
+ this.envVarBaseKey = config.envVarBaseKey;
15
+ this.type = config.type;
16
+ this.secret = config.secret;
17
+ this.required = config.required;
18
+ }
19
+ /**
20
+ * Get the parameter value from a ConnectorConnectionObject.
21
+ */
22
+ getValue(connection2) {
23
+ const param = connection2.parameters.find(
24
+ (p) => p.parameterSlug === this.slug
25
+ );
26
+ if (!param || param.value == null) {
27
+ throw new Error(
28
+ `Parameter "${this.slug}" not found or has no value in connection "${connection2.id}"`
29
+ );
30
+ }
31
+ return param.value;
32
+ }
33
+ /**
34
+ * Try to get the parameter value. Returns undefined if not found (for optional params).
35
+ */
36
+ tryGetValue(connection2) {
37
+ const param = connection2.parameters.find(
38
+ (p) => p.parameterSlug === this.slug
39
+ );
40
+ if (!param || param.value == null) return void 0;
41
+ return param.value;
42
+ }
43
+ };
44
+
45
+ // ../connectors/src/connectors/google-ads/sdk/index.ts
46
+ import * as crypto from "crypto";
47
+
48
+ // ../connectors/src/connectors/google-ads/parameters.ts
49
+ var parameters = {
50
+ serviceAccountKeyJsonBase64: new ParameterDefinition({
51
+ slug: "service-account-key-json-base64",
52
+ name: "Google Cloud Service Account JSON",
53
+ description: "The service account JSON key used to authenticate with Google Cloud Platform. Ensure that the service account has the necessary permissions to access Google Ads.",
54
+ envVarBaseKey: "GOOGLE_ADS_SERVICE_ACCOUNT_JSON_BASE64",
55
+ type: "base64EncodedJson",
56
+ secret: true,
57
+ required: true
58
+ }),
59
+ developerToken: new ParameterDefinition({
60
+ slug: "developer-token",
61
+ name: "Google Ads Developer Token",
62
+ description: "The developer token for accessing the Google Ads API. Required for all API requests.",
63
+ envVarBaseKey: "GOOGLE_ADS_DEVELOPER_TOKEN",
64
+ type: "text",
65
+ secret: true,
66
+ required: true
67
+ }),
68
+ customerId: new ParameterDefinition({
69
+ slug: "customer-id",
70
+ name: "Google Ads Customer ID",
71
+ description: "The Google Ads customer ID (e.g., 123-456-7890 or 1234567890). Can be found in the top-right corner of your Google Ads account.",
72
+ envVarBaseKey: "GOOGLE_ADS_CUSTOMER_ID",
73
+ type: "text",
74
+ secret: false,
75
+ required: false
76
+ }),
77
+ loginCustomerId: new ParameterDefinition({
78
+ slug: "login-customer-id",
79
+ name: "Login Customer ID (MCC)",
80
+ description: "The manager account (MCC) customer ID used for login. Required when accessing client accounts through a manager account. If not set, the customer ID is used.",
81
+ envVarBaseKey: "GOOGLE_ADS_LOGIN_CUSTOMER_ID",
82
+ type: "text",
83
+ secret: false,
84
+ required: false
85
+ })
86
+ };
87
+
88
+ // ../connectors/src/connectors/google-ads/sdk/index.ts
89
+ var TOKEN_URL = "https://oauth2.googleapis.com/token";
90
+ var BASE_URL = "https://googleads.googleapis.com/v18/";
91
+ var SCOPE = "https://www.googleapis.com/auth/adwords";
92
+ function base64url(input) {
93
+ const buf = typeof input === "string" ? Buffer.from(input) : input;
94
+ return buf.toString("base64url");
95
+ }
96
+ function buildJwt(clientEmail, privateKey, nowSec) {
97
+ const header = base64url(JSON.stringify({ alg: "RS256", typ: "JWT" }));
98
+ const payload = base64url(
99
+ JSON.stringify({
100
+ iss: clientEmail,
101
+ scope: SCOPE,
102
+ aud: TOKEN_URL,
103
+ iat: nowSec,
104
+ exp: nowSec + 3600
105
+ })
106
+ );
107
+ const signingInput = `${header}.${payload}`;
108
+ const sign = crypto.createSign("RSA-SHA256");
109
+ sign.update(signingInput);
110
+ sign.end();
111
+ const signature = base64url(sign.sign(privateKey));
112
+ return `${signingInput}.${signature}`;
113
+ }
114
+ function createClient(params) {
115
+ const serviceAccountKeyJsonBase64 = params[parameters.serviceAccountKeyJsonBase64.slug];
116
+ const developerToken = params[parameters.developerToken.slug];
117
+ const rawCustomerId = params[parameters.customerId.slug];
118
+ const defaultCustomerId = rawCustomerId?.replace(/-/g, "") ?? "";
119
+ const rawLoginCustomerId = params[parameters.loginCustomerId.slug];
120
+ const loginCustomerId = rawLoginCustomerId?.replace(/-/g, "") ?? "";
121
+ if (!serviceAccountKeyJsonBase64 || !developerToken) {
122
+ const required = [
123
+ parameters.serviceAccountKeyJsonBase64.slug,
124
+ parameters.developerToken.slug
125
+ ];
126
+ const missing = required.filter((s) => !params[s]);
127
+ throw new Error(
128
+ `google-ads: missing required parameters: ${missing.join(", ")}`
129
+ );
130
+ }
131
+ let serviceAccountKey;
132
+ try {
133
+ const decoded = Buffer.from(
134
+ serviceAccountKeyJsonBase64,
135
+ "base64"
136
+ ).toString("utf-8");
137
+ serviceAccountKey = JSON.parse(decoded);
138
+ } catch {
139
+ throw new Error(
140
+ "google-ads: failed to decode service account key JSON from base64"
141
+ );
142
+ }
143
+ if (!serviceAccountKey.client_email || !serviceAccountKey.private_key) {
144
+ throw new Error(
145
+ "google-ads: service account key JSON must contain client_email and private_key"
146
+ );
147
+ }
148
+ let cachedToken = null;
149
+ let tokenExpiresAt = 0;
150
+ async function getAccessToken() {
151
+ const nowSec = Math.floor(Date.now() / 1e3);
152
+ if (cachedToken && nowSec < tokenExpiresAt - 60) {
153
+ return cachedToken;
154
+ }
155
+ const jwt = buildJwt(
156
+ serviceAccountKey.client_email,
157
+ serviceAccountKey.private_key,
158
+ nowSec
159
+ );
160
+ const response = await fetch(TOKEN_URL, {
161
+ method: "POST",
162
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
163
+ body: new URLSearchParams({
164
+ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
165
+ assertion: jwt
166
+ })
167
+ });
168
+ if (!response.ok) {
169
+ const text = await response.text();
170
+ throw new Error(
171
+ `google-ads: token exchange failed (${response.status}): ${text}`
172
+ );
173
+ }
174
+ const data = await response.json();
175
+ cachedToken = data.access_token;
176
+ tokenExpiresAt = nowSec + data.expires_in;
177
+ return cachedToken;
178
+ }
179
+ function resolveCustomerId(override) {
180
+ const id = override?.replace(/-/g, "") ?? defaultCustomerId;
181
+ if (!id) {
182
+ throw new Error(
183
+ "google-ads: customerId is required. Either configure a default or pass it explicitly."
184
+ );
185
+ }
186
+ return id;
187
+ }
188
+ function getLoginCustomerId() {
189
+ return loginCustomerId || defaultCustomerId;
190
+ }
191
+ return {
192
+ async request(path2, init) {
193
+ const accessToken = await getAccessToken();
194
+ const resolvedPath = defaultCustomerId ? path2.replace(/\{customerId\}/g, defaultCustomerId) : path2;
195
+ const url = `${BASE_URL}${resolvedPath}`;
196
+ const headers = new Headers(init?.headers);
197
+ headers.set("Authorization", `Bearer ${accessToken}`);
198
+ headers.set("developer-token", developerToken);
199
+ const lid = getLoginCustomerId();
200
+ if (lid) {
201
+ headers.set("login-customer-id", lid);
202
+ }
203
+ return fetch(url, { ...init, headers });
204
+ },
205
+ async search(query, customerId) {
206
+ const cid = resolveCustomerId(customerId);
207
+ const accessToken = await getAccessToken();
208
+ const url = `${BASE_URL}customers/${cid}/googleAds:searchStream`;
209
+ const headers = new Headers();
210
+ headers.set("Content-Type", "application/json");
211
+ headers.set("Authorization", `Bearer ${accessToken}`);
212
+ headers.set("developer-token", developerToken);
213
+ const lid = loginCustomerId || cid;
214
+ headers.set("login-customer-id", lid);
215
+ const response = await fetch(url, {
216
+ method: "POST",
217
+ headers,
218
+ body: JSON.stringify({ query })
219
+ });
220
+ if (!response.ok) {
221
+ const body = await response.text();
222
+ throw new Error(
223
+ `google-ads: search failed (${response.status}): ${body}`
224
+ );
225
+ }
226
+ const data = await response.json();
227
+ return data.flatMap((chunk) => chunk.results ?? []);
228
+ },
229
+ async listAccessibleCustomers() {
230
+ const accessToken = await getAccessToken();
231
+ const url = `${BASE_URL}customers:listAccessibleCustomers`;
232
+ const headers = new Headers();
233
+ headers.set("Authorization", `Bearer ${accessToken}`);
234
+ headers.set("developer-token", developerToken);
235
+ const response = await fetch(url, { method: "GET", headers });
236
+ if (!response.ok) {
237
+ const body = await response.text();
238
+ throw new Error(
239
+ `google-ads: listAccessibleCustomers failed (${response.status}): ${body}`
240
+ );
241
+ }
242
+ const data = await response.json();
243
+ return (data.resourceNames ?? []).map(
244
+ (rn) => rn.replace(/^customers\//, "")
245
+ );
246
+ }
247
+ };
248
+ }
249
+
250
+ // ../connectors/src/connector-onboarding.ts
251
+ var ConnectorOnboarding = class {
252
+ /** Phase 1: Connection setup instructions (optional — some connectors don't need this) */
253
+ connectionSetupInstructions;
254
+ /** Phase 2: Data overview instructions */
255
+ dataOverviewInstructions;
256
+ constructor(config) {
257
+ this.connectionSetupInstructions = config.connectionSetupInstructions;
258
+ this.dataOverviewInstructions = config.dataOverviewInstructions;
259
+ }
260
+ getConnectionSetupPrompt(language) {
261
+ return this.connectionSetupInstructions?.[language] ?? null;
262
+ }
263
+ getDataOverviewInstructions(language) {
264
+ return this.dataOverviewInstructions[language];
265
+ }
266
+ };
267
+
268
+ // ../connectors/src/connector-tool.ts
269
+ var ConnectorTool = class {
270
+ name;
271
+ description;
272
+ inputSchema;
273
+ outputSchema;
274
+ _execute;
275
+ constructor(config) {
276
+ this.name = config.name;
277
+ this.description = config.description;
278
+ this.inputSchema = config.inputSchema;
279
+ this.outputSchema = config.outputSchema;
280
+ this._execute = config.execute;
281
+ }
282
+ createTool(connections, config) {
283
+ return {
284
+ description: this.description,
285
+ inputSchema: this.inputSchema,
286
+ outputSchema: this.outputSchema,
287
+ execute: (input) => this._execute(input, connections, config)
288
+ };
289
+ }
290
+ };
291
+
292
+ // ../connectors/src/connector-plugin.ts
293
+ var ConnectorPlugin = class _ConnectorPlugin {
294
+ slug;
295
+ authType;
296
+ name;
297
+ description;
298
+ iconUrl;
299
+ parameters;
300
+ releaseFlag;
301
+ proxyPolicy;
302
+ experimentalAttributes;
303
+ onboarding;
304
+ systemPrompt;
305
+ tools;
306
+ query;
307
+ checkConnection;
308
+ constructor(config) {
309
+ this.slug = config.slug;
310
+ this.authType = config.authType;
311
+ this.name = config.name;
312
+ this.description = config.description;
313
+ this.iconUrl = config.iconUrl;
314
+ this.parameters = config.parameters;
315
+ this.releaseFlag = config.releaseFlag;
316
+ this.proxyPolicy = config.proxyPolicy;
317
+ this.experimentalAttributes = config.experimentalAttributes;
318
+ this.onboarding = config.onboarding;
319
+ this.systemPrompt = config.systemPrompt;
320
+ this.tools = config.tools;
321
+ this.query = config.query;
322
+ this.checkConnection = config.checkConnection;
323
+ }
324
+ get connectorKey() {
325
+ return _ConnectorPlugin.deriveKey(this.slug, this.authType);
326
+ }
327
+ /**
328
+ * Create tools for connections that belong to this connector.
329
+ * Filters connections by connectorKey internally.
330
+ * Returns tools keyed as `${connectorKey}_${toolName}`.
331
+ */
332
+ createTools(connections, config) {
333
+ const myConnections = connections.filter(
334
+ (c) => _ConnectorPlugin.deriveKey(c.connector.slug, c.connector.authType) === this.connectorKey
335
+ );
336
+ const result = {};
337
+ for (const t of Object.values(this.tools)) {
338
+ result[`${this.connectorKey}_${t.name}`] = t.createTool(
339
+ myConnections,
340
+ config
341
+ );
342
+ }
343
+ return result;
344
+ }
345
+ static deriveKey(slug, authType) {
346
+ return authType ? `${slug}-${authType}` : slug;
347
+ }
348
+ };
349
+
350
+ // ../connectors/src/connectors/google-ads/setup.ts
351
+ var googleAdsOnboarding = new ConnectorOnboarding({
352
+ dataOverviewInstructions: {
353
+ en: `1. Call google-ads_request with POST customers/{customerId}/googleAds:searchStream to explore available campaign data using GAQL: SELECT campaign.id, campaign.name, campaign.status FROM campaign LIMIT 10
354
+ 2. Explore ad group and keyword data as needed to understand the data structure`,
355
+ ja: `1. google-ads_request \u3067 POST customers/{customerId}/googleAds:searchStream \u3092\u547C\u3073\u51FA\u3057\u3001GAQL\u3067\u30AD\u30E3\u30F3\u30DA\u30FC\u30F3\u30C7\u30FC\u30BF\u3092\u63A2\u7D22: SELECT campaign.id, campaign.name, campaign.status FROM campaign LIMIT 10
356
+ 2. \u5FC5\u8981\u306B\u5FDC\u3058\u3066\u5E83\u544A\u30B0\u30EB\u30FC\u30D7\u3084\u30AD\u30FC\u30EF\u30FC\u30C9\u30C7\u30FC\u30BF\u3092\u63A2\u7D22\u3057\u3001\u30C7\u30FC\u30BF\u69CB\u9020\u3092\u628A\u63E1`
357
+ }
358
+ });
359
+
360
+ // ../connectors/src/connectors/google-ads/tools/request.ts
361
+ import { z } from "zod";
362
+ var BASE_URL2 = "https://googleads.googleapis.com/v18/";
363
+ var REQUEST_TIMEOUT_MS = 6e4;
364
+ var inputSchema = z.object({
365
+ toolUseIntent: z.string().optional().describe(
366
+ "Brief description of what you intend to accomplish with this tool call"
367
+ ),
368
+ connectionId: z.string().describe("ID of the Google Ads connection to use"),
369
+ method: z.enum(["GET", "POST"]).describe("HTTP method"),
370
+ path: z.string().describe(
371
+ "API path appended to https://googleads.googleapis.com/v18/ (e.g., 'customers/{customerId}/googleAds:searchStream'). {customerId} is automatically replaced."
372
+ ),
373
+ body: z.record(z.string(), z.unknown()).optional().describe("POST request body (JSON)")
374
+ });
375
+ var outputSchema = z.discriminatedUnion("success", [
376
+ z.object({
377
+ success: z.literal(true),
378
+ status: z.number(),
379
+ data: z.unknown()
380
+ }),
381
+ z.object({
382
+ success: z.literal(false),
383
+ error: z.string()
384
+ })
385
+ ]);
386
+ var requestTool = new ConnectorTool({
387
+ name: "request",
388
+ description: `Send authenticated requests to the Google Ads API v18.
389
+ Authentication is handled automatically using a service account.
390
+ {customerId} in the path is automatically replaced with the connection's customer ID (hyphens removed).`,
391
+ inputSchema,
392
+ outputSchema,
393
+ async execute({ connectionId, method, path: path2, body }, connections) {
394
+ const connection2 = connections.find((c) => c.id === connectionId);
395
+ if (!connection2) {
396
+ return {
397
+ success: false,
398
+ error: `Connection ${connectionId} not found`
399
+ };
400
+ }
401
+ console.log(
402
+ `[connector-request] google-ads/${connection2.name}: ${method} ${path2}`
403
+ );
404
+ try {
405
+ const { GoogleAuth } = await import("google-auth-library");
406
+ const keyJsonBase64 = parameters.serviceAccountKeyJsonBase64.getValue(connection2);
407
+ const developerToken = parameters.developerToken.getValue(connection2);
408
+ const rawCustomerId = parameters.customerId.tryGetValue(connection2);
409
+ const customerId = rawCustomerId?.replace(/-/g, "") ?? "";
410
+ const rawLoginCustomerId = parameters.loginCustomerId.tryGetValue(connection2);
411
+ const loginCustomerId = rawLoginCustomerId?.replace(/-/g, "") ?? "";
412
+ const credentials = JSON.parse(
413
+ Buffer.from(keyJsonBase64, "base64").toString("utf-8")
414
+ );
415
+ const auth = new GoogleAuth({
416
+ credentials,
417
+ scopes: ["https://www.googleapis.com/auth/adwords"]
418
+ });
419
+ const token = await auth.getAccessToken();
420
+ if (!token) {
421
+ return {
422
+ success: false,
423
+ error: "Failed to obtain access token"
424
+ };
425
+ }
426
+ const resolvedPath = customerId ? path2.replace(/\{customerId\}/g, customerId) : path2;
427
+ const url = `${BASE_URL2}${resolvedPath}`;
428
+ const controller = new AbortController();
429
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
430
+ try {
431
+ const lid = loginCustomerId || customerId;
432
+ const response = await fetch(url, {
433
+ method,
434
+ headers: {
435
+ Authorization: `Bearer ${token}`,
436
+ "Content-Type": "application/json",
437
+ "developer-token": developerToken,
438
+ ...lid ? { "login-customer-id": lid } : {}
439
+ },
440
+ body: method === "POST" && body ? JSON.stringify(body) : void 0,
441
+ signal: controller.signal
442
+ });
443
+ const data = await response.json();
444
+ if (!response.ok) {
445
+ const dataObj = data;
446
+ const errorObj = dataObj?.error;
447
+ return {
448
+ success: false,
449
+ error: errorObj?.message ?? `HTTP ${response.status} ${response.statusText}`
450
+ };
451
+ }
452
+ return { success: true, status: response.status, data };
453
+ } finally {
454
+ clearTimeout(timeout);
455
+ }
456
+ } catch (err) {
457
+ const msg = err instanceof Error ? err.message : String(err);
458
+ return { success: false, error: msg };
459
+ }
460
+ }
461
+ });
462
+
463
+ // ../connectors/src/connectors/google-ads/tools/list-customers.ts
464
+ import { z as z2 } from "zod";
465
+ var BASE_URL3 = "https://googleads.googleapis.com/v18/";
466
+ var REQUEST_TIMEOUT_MS2 = 6e4;
467
+ var inputSchema2 = z2.object({
468
+ toolUseIntent: z2.string().optional().describe(
469
+ "Brief description of what you intend to accomplish with this tool call"
470
+ ),
471
+ connectionId: z2.string().describe("ID of the Google Ads connection to use")
472
+ });
473
+ var outputSchema2 = z2.discriminatedUnion("success", [
474
+ z2.object({
475
+ success: z2.literal(true),
476
+ customers: z2.array(
477
+ z2.object({
478
+ customerId: z2.string(),
479
+ descriptiveName: z2.string()
480
+ })
481
+ )
482
+ }),
483
+ z2.object({
484
+ success: z2.literal(false),
485
+ error: z2.string()
486
+ })
487
+ ]);
488
+ var listCustomersTool = new ConnectorTool({
489
+ name: "listCustomers",
490
+ description: "List Google Ads customer accounts accessible with the service account credentials.",
491
+ inputSchema: inputSchema2,
492
+ outputSchema: outputSchema2,
493
+ async execute({ connectionId }, connections) {
494
+ const connection2 = connections.find((c) => c.id === connectionId);
495
+ if (!connection2) {
496
+ return {
497
+ success: false,
498
+ error: `Connection ${connectionId} not found`
499
+ };
500
+ }
501
+ console.log(
502
+ `[connector-request] google-ads/${connection2.name}: listCustomers`
503
+ );
504
+ try {
505
+ const { GoogleAuth } = await import("google-auth-library");
506
+ const keyJsonBase64 = parameters.serviceAccountKeyJsonBase64.getValue(connection2);
507
+ const developerToken = parameters.developerToken.getValue(connection2);
508
+ const credentials = JSON.parse(
509
+ Buffer.from(keyJsonBase64, "base64").toString("utf-8")
510
+ );
511
+ const auth = new GoogleAuth({
512
+ credentials,
513
+ scopes: ["https://www.googleapis.com/auth/adwords"]
514
+ });
515
+ const token = await auth.getAccessToken();
516
+ if (!token) {
517
+ return {
518
+ success: false,
519
+ error: "Failed to obtain access token"
520
+ };
521
+ }
522
+ const controller = new AbortController();
523
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS2);
524
+ try {
525
+ const listResponse = await fetch(
526
+ `${BASE_URL3}customers:listAccessibleCustomers`,
527
+ {
528
+ method: "GET",
529
+ headers: {
530
+ Authorization: `Bearer ${token}`,
531
+ "developer-token": developerToken
532
+ },
533
+ signal: controller.signal
534
+ }
535
+ );
536
+ const listData = await listResponse.json();
537
+ if (!listResponse.ok) {
538
+ return {
539
+ success: false,
540
+ error: listData.error?.message ?? `HTTP ${listResponse.status} ${listResponse.statusText}`
541
+ };
542
+ }
543
+ const customerIds = (listData.resourceNames ?? []).map(
544
+ (rn) => rn.replace(/^customers\//, "")
545
+ );
546
+ const customers = [];
547
+ for (const cid of customerIds) {
548
+ try {
549
+ const detailResponse = await fetch(
550
+ `${BASE_URL3}customers/${cid}/googleAds:searchStream`,
551
+ {
552
+ method: "POST",
553
+ headers: {
554
+ Authorization: `Bearer ${token}`,
555
+ "Content-Type": "application/json",
556
+ "developer-token": developerToken,
557
+ "login-customer-id": cid
558
+ },
559
+ body: JSON.stringify({
560
+ query: "SELECT customer.id, customer.descriptive_name FROM customer LIMIT 1"
561
+ }),
562
+ signal: controller.signal
563
+ }
564
+ );
565
+ if (detailResponse.ok) {
566
+ const detailData = await detailResponse.json();
567
+ const customer = detailData?.[0]?.results?.[0]?.customer;
568
+ customers.push({
569
+ customerId: cid,
570
+ descriptiveName: customer?.descriptiveName ?? cid
571
+ });
572
+ } else {
573
+ customers.push({
574
+ customerId: cid,
575
+ descriptiveName: cid
576
+ });
577
+ }
578
+ } catch {
579
+ customers.push({
580
+ customerId: cid,
581
+ descriptiveName: cid
582
+ });
583
+ }
584
+ }
585
+ return { success: true, customers };
586
+ } finally {
587
+ clearTimeout(timeout);
588
+ }
589
+ } catch (err) {
590
+ const msg = err instanceof Error ? err.message : String(err);
591
+ return { success: false, error: msg };
592
+ }
593
+ }
594
+ });
595
+
596
+ // ../connectors/src/connectors/google-ads/index.ts
597
+ var tools = {
598
+ request: requestTool,
599
+ listCustomers: listCustomersTool
600
+ };
601
+ var googleAdsConnector = new ConnectorPlugin({
602
+ slug: "google-ads",
603
+ authType: null,
604
+ name: "Google Ads",
605
+ description: "Connect to Google Ads for advertising campaign data and reporting using a service account.",
606
+ iconUrl: "https://images.ctfassets.net/9ncizv60xc5y/1NGvmgvCxX7Tn11EST2N3N/a745fe7c63d360ed40a27ddaad3af168/google-ads.svg",
607
+ parameters,
608
+ releaseFlag: { dev1: true, dev2: false, prod: false },
609
+ onboarding: googleAdsOnboarding,
610
+ systemPrompt: {
611
+ en: `### Tools
612
+
613
+ - \`google-ads_request\`: Send authenticated requests to the Google Ads API. Use it for GAQL queries via searchStream. The {customerId} placeholder in paths is automatically replaced (hyphens removed). Authentication via service account and developer token are configured automatically.
614
+ - \`google-ads_listCustomers\`: List accessible Google Ads customer accounts. Use this during setup to discover available accounts.
615
+
616
+ ### Google Ads API Reference
617
+
618
+ #### Query Data (searchStream)
619
+ - POST customers/{customerId}/googleAds:searchStream
620
+ - Body: { "query": "SELECT campaign.id, campaign.name, metrics.impressions FROM campaign WHERE segments.date DURING LAST_30_DAYS" }
621
+
622
+ ### Common GAQL Resources
623
+ - \`campaign\`: Campaign data (campaign.id, campaign.name, campaign.status)
624
+ - \`ad_group\`: Ad group data (ad_group.id, ad_group.name, ad_group.status)
625
+ - \`ad_group_ad\`: Ad data (ad_group_ad.ad.id, ad_group_ad.status)
626
+ - \`keyword_view\`: Keyword performance data
627
+
628
+ ### Common Metrics
629
+ metrics.impressions, metrics.clicks, metrics.cost_micros, metrics.conversions,
630
+ metrics.ctr, metrics.average_cpc, metrics.conversions_value
631
+
632
+ ### Common Segments
633
+ segments.date, segments.device, segments.ad_network_type
634
+
635
+ ### Date Filters
636
+ - \`DURING LAST_7_DAYS\`, \`DURING LAST_30_DAYS\`, \`DURING THIS_MONTH\`
637
+ - \`WHERE segments.date BETWEEN '2024-01-01' AND '2024-01-31'\`
638
+
639
+ ### Tips
640
+ - cost_micros is in micros (divide by 1,000,000 for actual currency)
641
+ - Use LIMIT to restrict result count
642
+ - Always include relevant WHERE clauses to filter data
643
+
644
+ ### Business Logic
645
+
646
+ The business logic type for this connector is "typescript". Write handler code using the connector SDK shown below. Do NOT access credentials directly from environment variables.
647
+
648
+ #### Example
649
+
650
+ \`\`\`ts
651
+ import { connection } from "@squadbase/vite-server/connectors/google-ads";
652
+
653
+ const ads = connection("<connectionId>");
654
+
655
+ // Execute a GAQL query
656
+ const rows = await ads.search(
657
+ "SELECT campaign.name, metrics.impressions, metrics.clicks FROM campaign WHERE segments.date DURING LAST_7_DAYS"
658
+ );
659
+ rows.forEach(row => console.log(row));
660
+
661
+ // List accessible customer accounts
662
+ const customerIds = await ads.listAccessibleCustomers();
663
+ \`\`\``,
664
+ ja: `### \u30C4\u30FC\u30EB
665
+
666
+ - \`google-ads_request\`: Google Ads API\u3078\u8A8D\u8A3C\u6E08\u307F\u30EA\u30AF\u30A8\u30B9\u30C8\u3092\u9001\u4FE1\u3057\u307E\u3059\u3002searchStream\u3092\u4F7F\u3063\u305FGAQL\u30AF\u30A8\u30EA\u306B\u4F7F\u7528\u3057\u307E\u3059\u3002\u30D1\u30B9\u5185\u306E{customerId}\u30D7\u30EC\u30FC\u30B9\u30DB\u30EB\u30C0\u30FC\u306F\u81EA\u52D5\u7684\u306B\u7F6E\u63DB\u3055\u308C\u307E\u3059\uFF08\u30CF\u30A4\u30D5\u30F3\u306F\u9664\u53BB\uFF09\u3002\u30B5\u30FC\u30D3\u30B9\u30A2\u30AB\u30A6\u30F3\u30C8\u306B\u3088\u308B\u8A8D\u8A3C\u3068\u30C7\u30D9\u30ED\u30C3\u30D1\u30FC\u30C8\u30FC\u30AF\u30F3\u306F\u81EA\u52D5\u8A2D\u5B9A\u3055\u308C\u307E\u3059\u3002
667
+ - \`google-ads_listCustomers\`: \u30A2\u30AF\u30BB\u30B9\u53EF\u80FD\u306AGoogle Ads\u9867\u5BA2\u30A2\u30AB\u30A6\u30F3\u30C8\u306E\u4E00\u89A7\u3092\u53D6\u5F97\u3057\u307E\u3059\u3002\u30BB\u30C3\u30C8\u30A2\u30C3\u30D7\u6642\u306B\u5229\u7528\u53EF\u80FD\u306A\u30A2\u30AB\u30A6\u30F3\u30C8\u3092\u78BA\u8A8D\u3059\u308B\u305F\u3081\u306B\u4F7F\u7528\u3057\u307E\u3059\u3002
668
+
669
+ ### Google Ads API \u30EA\u30D5\u30A1\u30EC\u30F3\u30B9
670
+
671
+ #### \u30C7\u30FC\u30BF\u306E\u30AF\u30A8\u30EA (searchStream)
672
+ - POST customers/{customerId}/googleAds:searchStream
673
+ - Body: { "query": "SELECT campaign.id, campaign.name, metrics.impressions FROM campaign WHERE segments.date DURING LAST_30_DAYS" }
674
+
675
+ ### \u4E3B\u8981\u306AGAQL\u30EA\u30BD\u30FC\u30B9
676
+ - \`campaign\`: \u30AD\u30E3\u30F3\u30DA\u30FC\u30F3\u30C7\u30FC\u30BF (campaign.id, campaign.name, campaign.status)
677
+ - \`ad_group\`: \u5E83\u544A\u30B0\u30EB\u30FC\u30D7\u30C7\u30FC\u30BF (ad_group.id, ad_group.name, ad_group.status)
678
+ - \`ad_group_ad\`: \u5E83\u544A\u30C7\u30FC\u30BF (ad_group_ad.ad.id, ad_group_ad.status)
679
+ - \`keyword_view\`: \u30AD\u30FC\u30EF\u30FC\u30C9\u30D1\u30D5\u30A9\u30FC\u30DE\u30F3\u30B9\u30C7\u30FC\u30BF
680
+
681
+ ### \u4E3B\u8981\u306A\u30E1\u30C8\u30EA\u30AF\u30B9
682
+ metrics.impressions, metrics.clicks, metrics.cost_micros, metrics.conversions,
683
+ metrics.ctr, metrics.average_cpc, metrics.conversions_value
684
+
685
+ ### \u4E3B\u8981\u306A\u30BB\u30B0\u30E1\u30F3\u30C8
686
+ segments.date, segments.device, segments.ad_network_type
687
+
688
+ ### \u65E5\u4ED8\u30D5\u30A3\u30EB\u30BF
689
+ - \`DURING LAST_7_DAYS\`, \`DURING LAST_30_DAYS\`, \`DURING THIS_MONTH\`
690
+ - \`WHERE segments.date BETWEEN '2024-01-01' AND '2024-01-31'\`
691
+
692
+ ### \u30D2\u30F3\u30C8
693
+ - cost_micros \u306F\u30DE\u30A4\u30AF\u30ED\u5358\u4F4D\u3067\u3059\uFF08\u5B9F\u969B\u306E\u901A\u8CA8\u984D\u306B\u3059\u308B\u306B\u306F1,000,000\u3067\u5272\u308A\u307E\u3059\uFF09
694
+ - LIMIT \u3092\u4F7F\u7528\u3057\u3066\u7D50\u679C\u6570\u3092\u5236\u9650\u3057\u307E\u3059
695
+ - \u30C7\u30FC\u30BF\u3092\u30D5\u30A3\u30EB\u30BF\u3059\u308B\u305F\u3081\u306B\u5E38\u306B\u9069\u5207\u306AWHERE\u53E5\u3092\u542B\u3081\u3066\u304F\u3060\u3055\u3044
696
+
697
+ ### Business Logic
698
+
699
+ \u3053\u306E\u30B3\u30CD\u30AF\u30BF\u306E\u30D3\u30B8\u30CD\u30B9\u30ED\u30B8\u30C3\u30AF\u30BF\u30A4\u30D7\u306F "typescript" \u3067\u3059\u3002\u4EE5\u4E0B\u306B\u793A\u3059\u30B3\u30CD\u30AF\u30BFSDK\u3092\u4F7F\u7528\u3057\u3066\u30CF\u30F3\u30C9\u30E9\u30B3\u30FC\u30C9\u3092\u8A18\u8FF0\u3057\u3066\u304F\u3060\u3055\u3044\u3002\u74B0\u5883\u5909\u6570\u304B\u3089\u76F4\u63A5\u8A8D\u8A3C\u60C5\u5831\u306B\u30A2\u30AF\u30BB\u30B9\u3057\u306A\u3044\u3067\u304F\u3060\u3055\u3044\u3002
700
+
701
+ #### Example
702
+
703
+ \`\`\`ts
704
+ import { connection } from "@squadbase/vite-server/connectors/google-ads";
705
+
706
+ const ads = connection("<connectionId>");
707
+
708
+ // Execute a GAQL query
709
+ const rows = await ads.search(
710
+ "SELECT campaign.name, metrics.impressions, metrics.clicks FROM campaign WHERE segments.date DURING LAST_7_DAYS"
711
+ );
712
+ rows.forEach(row => console.log(row));
713
+
714
+ // List accessible customer accounts
715
+ const customerIds = await ads.listAccessibleCustomers();
716
+ \`\`\``
717
+ },
718
+ tools
719
+ });
720
+
721
+ // src/connectors/create-connector-sdk.ts
722
+ import { readFileSync } from "fs";
723
+ import path from "path";
724
+
725
+ // src/connector-client/env.ts
726
+ function resolveEnvVar(entry, key, connectionId) {
727
+ const envVarName = entry.envVars[key];
728
+ if (!envVarName) {
729
+ throw new Error(`Connection "${connectionId}" is missing envVars mapping for key "${key}"`);
730
+ }
731
+ const value = process.env[envVarName];
732
+ if (!value) {
733
+ throw new Error(`Environment variable "${envVarName}" (for connection "${connectionId}", key "${key}") is not set`);
734
+ }
735
+ return value;
736
+ }
737
+ function resolveEnvVarOptional(entry, key) {
738
+ const envVarName = entry.envVars[key];
739
+ if (!envVarName) return void 0;
740
+ return process.env[envVarName] || void 0;
741
+ }
742
+
743
+ // src/connectors/create-connector-sdk.ts
744
+ function loadConnectionsSync() {
745
+ const filePath = process.env.CONNECTIONS_PATH ?? path.join(process.cwd(), ".squadbase/connections.json");
746
+ try {
747
+ const raw = readFileSync(filePath, "utf-8");
748
+ return JSON.parse(raw);
749
+ } catch {
750
+ return {};
751
+ }
752
+ }
753
+ function createConnectorSdk(plugin, createClient2) {
754
+ return (connectionId) => {
755
+ const connections = loadConnectionsSync();
756
+ const entry = connections[connectionId];
757
+ if (!entry) {
758
+ throw new Error(
759
+ `Connection "${connectionId}" not found in .squadbase/connections.json`
760
+ );
761
+ }
762
+ if (entry.connector.slug !== plugin.slug) {
763
+ throw new Error(
764
+ `Connection "${connectionId}" is not a ${plugin.slug} connection (got "${entry.connector.slug}")`
765
+ );
766
+ }
767
+ const params = {};
768
+ for (const param of Object.values(plugin.parameters)) {
769
+ if (param.required) {
770
+ params[param.slug] = resolveEnvVar(entry, param.slug, connectionId);
771
+ } else {
772
+ const val = resolveEnvVarOptional(entry, param.slug);
773
+ if (val !== void 0) params[param.slug] = val;
774
+ }
775
+ }
776
+ return createClient2(params);
777
+ };
778
+ }
779
+
780
+ // src/connectors/entries/google-ads.ts
781
+ var connection = createConnectorSdk(googleAdsConnector, createClient);
782
+ export {
783
+ connection
784
+ };