Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(google-ads): add Google Ads piece (#16294)

Fabio219d76bc9d31
diff --git a/bun.lock b/bun.lock
index d7667b2246d..93930b63e55 100644
--- a/bun.lock
+++ b/bun.lock
@@ -3829,6 +3829,18 @@
"tslib": "2.6.2",
},
},
+ "packages/pieces/community/google-ads": {
+ "name": "@activepieces/piece-google-ads",
+ "version": "0.0.1",
+ "dependencies": {
+ "@activepieces/pieces-common": "workspace:*",
+ "@activepieces/pieces-framework": "workspace:*",
+ },
+ "devDependencies": {
+ "tslib": "2.6.2",
+ "vitest": "3.2.6",
+ },
+ },
"packages/pieces/community/google-bigquery": {
"name": "@activepieces/piece-google-bigquery",
"version": "0.1.2",
@@ -11913,6 +11925,7 @@
"@activepieces/piece-goodmem": ["@activepieces/piece-goodmem@workspace:packages/pieces/community/goodmem"],
+ "@activepieces/piece-google-ads": ["@activepieces/piece-google-ads@workspace:packages/pieces/community/google-ads"],
"@activepieces/piece-google-bigquery": ["@activepieces/piece-google-bigquery@workspace:packages/pieces/community/google-bigquery"],
"@activepieces/piece-google-calendar": ["@activepieces/piece-google-calendar@workspace:packages/pieces/community/google-calendar"],
diff --git a/packages/pieces/community/google-ads/.eslintrc.json b/packages/pieces/community/google-ads/.eslintrc.json
new file mode 100644
index 00000000000..9ee1a0770e8
--- /dev/null
+++ b/packages/pieces/community/google-ads/.eslintrc.json
@@ -0,0 +1,26 @@
+{
+ "extends": ["../../../../.eslintrc.json"],
+ "ignorePatterns": ["!**/*"],
+ "overrides": [
+ { "files": ["*.ts", "*.tsx", "*.js", "*.jsx"], "rules": {} },
+ {
+ "files": ["*.ts", "*.tsx"],
+ "rules": {
+ "no-restricted-imports": [
+ "error",
+ {
+ "patterns": [
+ "lodash",
+ "lodash/*",
+ "@activepieces/core-*",
+ "@activepieces/server*",
+ "@activepieces/engine",
+ "@activepieces/shared"
+ ]
+ }
+ ]
+ }
+ },
+ { "files": ["*.js", "*.jsx"], "rules": {} }
+ ]
+}
diff --git a/packages/pieces/community/google-ads/README.md b/packages/pieces/community/google-ads/README.md
new file mode 100644
index 00000000000..5c55deb0b4a
--- /dev/null
+++ b/packages/pieces/community/google-ads/README.md
@@ -0,0 +1,37 @@
+# Google Ads
+
+Manage campaigns, ad groups, ads, keywords, audiences and performance reports in Google Ads through the
+[Google Ads API](https://developers.google.com/google-ads/api) (v25) and, for Customer Match, the
+[Data Manager API](https://developers.google.com/data-manager/api).
+
+## Connection
+
+Google OAuth2 with an OAuth client from your own Google Cloud project:
+
+1. Enable the **Google Ads API** (and the **Data Manager API** if you use Customer Match) in the project.
+2. Check the project's Google Ads API access level. New projects get *Test* access (test accounts only); apply for *Explorer* or *Basic* access to operate real accounts.
+3. Add the `https://www.googleapis.com/auth/adwords` and `https://www.googleapis.com/auth/datamanager` scopes to the OAuth consent screen.
+4. Create a *Web application* OAuth client with the redirect URL shown in the connection dialog, and paste the Client ID and Client Secret.
+
+**Login Customer ID (Manager Account)** is optional: fill it with the manager (MCC) account ID when you reach client accounts through a manager.
+
+## Actions
+
+Records are one of five resources: campaign, ad group, ad, keyword or audience list.
+
+| Action | Description |
+| --- | --- |
+| Create Record | Create a record from a JSON body in the REST API shape. Supports *Validate Only*. |
+| Update Record | Change only the fields you send; the update mask is derived from them. Supports *Validate Only*. |
+| Delete Record | Remove a record (Google marks it REMOVED; it cannot be restored). Supports *Validate Only*. |
+| Search Records | Run a GAQL `SELECT` query, one page at a time or all pages up to a row cap. |
+| Retrieve Advertising Report | Metrics per account, campaign, ad group, ad, keyword or search term over a date range, as flat rows. |
+| Add Customer Match Data | Upload e-mails, phones or addresses to a CRM-based audience list. E-mails, phones, first and last names are normalized and SHA-256 hashed; country code and postal code are sent unhashed (trimmed, country code uppercased), as Google requires. Both consent fields must be chosen explicitly. |
+| Remove Customer Match Data | Remove members from a CRM-based audience list. |
+| Custom API Call | Call any Google Ads API endpoint (or a Data Manager API endpoint by full URL, e.g. to check a Customer Match request) with the connection's credentials. |
+
+## Triggers
+
+| Trigger | Description |
+| --- | --- |
+| New Record | Polls the selected account for newly created records of the chosen type. Ads and keywords are detected from the account change history, which covers the last 30 days. Removed records are ignored. One change history query returns at most 10,000 rows and cannot be split below one ad group at one timestamp, so if a single ad group receives more than 10,000 ads or keywords at the same instant (more than one mutate request can create), only the first 10,000 fire and a warning is logged. |
diff --git a/packages/pieces/community/google-ads/package.json b/packages/pieces/community/google-ads/package.json
new file mode 100644
index 00000000000..5ed642c69ae
--- /dev/null
+++ b/packages/pieces/community/google-ads/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@activepieces/piece-google-ads",
+ "version": "0.0.1",
+ "main": "./dist/src/index.js",
+ "types": "./dist/src/index.d.ts",
+ "scripts": {
+ "build": "tsc -p tsconfig.lib.json && cp package.json dist/",
+ "bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
+ },
+ "dependencies": {
+ "@activepieces/pieces-common": "workspace:*",
+ "@activepieces/pieces-framework": "workspace:*"
+ },
+ "devDependencies": {
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
+ }
+}
diff --git a/packages/pieces/community/google-ads/src/i18n/translation.json b/packages/pieces/community/google-ads/src/i18n/translation.json
new file mode 100644
index 00000000000..fc613d0d369
--- /dev/null
+++ b/packages/pieces/community/google-ads/src/i18n/translation.json
@@ -0,0 +1,120 @@
+{
+ "Manage campaigns, ad groups, ads, keywords, audiences and performance reports in Google Ads.": "Manage campaigns, ad groups, ads, keywords, audiences and performance reports in Google Ads.",
+ "Login Customer ID (Manager Account)": "Login Customer ID (Manager Account)",
+ "Only when you access client accounts through a manager (MCC) account: the manager's 10-digit customer ID, with or without dashes. Leave empty when connecting directly as the advertiser.": "Only when you access client accounts through a manager (MCC) account: the manager's 10-digit customer ID, with or without dashes. Leave empty when connecting directly as the advertiser.",
+ "Connect with an OAuth client from **your own** Google Cloud project:\n\n1. In [Google Cloud Console](https://console.cloud.google.com/), select or create a project. **APIs & Services → Library**: enable **Google Ads API** and **Data Manager API** (the latter only for Customer Match uploads).\n2. Open the **Google Ads API** page in the console and check the project's **access level**. New projects get *Test* access (test accounts only). To operate real accounts, apply for *Explorer* or *Basic* access there (Goo": "Connect with an OAuth client from **your own** Google Cloud project:\n\n1. In [Google Cloud Console](https://console.cloud.google.com/), select or create a project. **APIs & Services → Library**: enable **Google Ads API** and **Data Manager API** (the latter only for Customer Match uploads).\n2. Open the **Google Ads API** page in the console and check the project's **access level**. New projects get *Test* access (test accounts only). To operate real accounts, apply for *Explorer* or *Basic* access there (Google reviews it, typically within 10 business days).\n3. **APIs & Services → OAuth consent screen**: add the scopes `https://www.googleapis.com/auth/adwords` and `https://www.googleapis.com/auth/datamanager`. While the app is in *Testing*, add the Google accounts that will connect as test users.\n4. **APIs & Services → Credentials → Create credentials → OAuth client ID**, type *Web application*. Add the **Redirect URL shown below** to *Authorized redirect URIs*.\n5. Paste the **Client ID** and **Client Secret** here and sign in with a Google account that can access the Google Ads accounts you want to automate.\n\n**Login Customer ID (Manager Account)**: fill it only when you reach the accounts through a **manager (MCC) account**: the manager's 10-digit ID. Leave it empty when you connect directly as the advertiser.",
+ "Create Record": "Create Record",
+ "Update Record": "Update Record",
+ "Delete Record": "Delete Record",
+ "Search Records": "Search Records",
+ "Retrieve Advertising Report": "Retrieve Advertising Report",
+ "Add Customer Match Data": "Add Customer Match Data",
+ "Remove Customer Match Data": "Remove Customer Match Data",
+ "Custom API Call": "Custom API Call",
+ "Create a campaign, ad group, ad, keyword or audience list": "Create a campaign, ad group, ad, keyword or audience list",
+ "Change fields of an existing campaign, ad group, ad, keyword or audience list": "Change fields of an existing campaign, ad group, ad, keyword or audience list",
+ "Remove a campaign, ad group, ad, keyword or audience list (Google marks it REMOVED; it cannot be restored)": "Remove a campaign, ad group, ad, keyword or audience list (Google marks it REMOVED; it cannot be restored)",
+ "Run a GAQL query (campaigns, ad groups, ads, keywords, audiences, reports) with pagination": "Run a GAQL query (campaigns, ad groups, ads, keywords, audiences, reports) with pagination",
+ "Performance metrics per campaign, ad group, ad, keyword, search term or account, over a date range": "Performance metrics per campaign, ad group, ad, keyword, search term or account, over a date range",
+ "Upload e-mails, phones or addresses to a Customer Match audience list (Data Manager API)": "Upload e-mails, phones or addresses to a Customer Match audience list (Data Manager API)",
+ "Remove members (by e-mail, phone or address) from a Customer Match audience list (Data Manager API)": "Remove members (by e-mail, phone or address) from a Customer Match audience list (Data Manager API)",
+ "Call any Google Ads API endpoint. The path must start with the API version: /v25/customers/{customerId}/... (e.g. /v25/customers/1234567890/campaignBudgets:mutate). Base URL: https://googleads.googleapis.com. Data Manager API endpoints take a full URL on https://datamanager.googleapis.com (e.g. GET https://datamanager.googleapis.com/v1/requestStatus:retrieve?requestId=... to check a Customer Match upload).": "Call any Google Ads API endpoint. The path must start with the API version: /v25/customers/{customerId}/... (e.g. /v25/customers/1234567890/campaignBudgets:mutate). Base URL: https://googleads.googleapis.com. Data Manager API endpoints take a full URL on https://datamanager.googleapis.com (e.g. GET https://datamanager.googleapis.com/v1/requestStatus:retrieve?requestId=... to check a Customer Match upload).",
+ "Customer": "Customer",
+ "Resource Type": "Resource Type",
+ "Record": "Record",
+ "Validate Only": "Validate Only",
+ "Record ID or Resource Name": "Record ID or Resource Name",
+ "Fields to Update": "Fields to Update",
+ "GAQL Query": "GAQL Query",
+ "Fetch All Pages": "Fetch All Pages",
+ "Max Rows": "Max Rows",
+ "Page Token": "Page Token",
+ "Report On": "Report On",
+ "Date Range": "Date Range",
+ "Start Date": "Start Date",
+ "End Date": "End Date",
+ "One Row per Day": "One Row per Day",
+ "Metrics": "Metrics",
+ "Entity Fields": "Entity Fields",
+ "Filter": "Filter",
+ "Order By": "Order By",
+ "Advanced: Full GAQL Query": "Advanced: Full GAQL Query",
+ "Audience List": "Audience List",
+ "Members": "Members",
+ "Consent: Ad User Data": "Consent: Ad User Data",
+ "Consent: Ad Personalization": "Consent: Ad Personalization",
+ "Customer Match Terms Accepted": "Customer Match Terms Accepted",
+ "Wait for Processing": "Wait for Processing",
+ "Method": "Method",
+ "Headers": "Headers",
+ "Query Parameters": "Query Parameters",
+ "Body Type": "Body Type",
+ "Body": "Body",
+ "Response is Binary": "Response is Binary",
+ "Return Error as Output": "Return Error as Output",
+ "Timeout": "Timeout",
+ "Follow redirects": "Follow redirects",
+ "Google Ads account to operate on. Accounts reached through a manager need the manager ID in the connection.": "Google Ads account to operate on. Accounts reached through a manager need the manager ID in the connection.",
+ "Which kind of record: campaign, ad group, ad, keyword or audience list.": "Which kind of record: campaign, ad group, ad, keyword or audience list.",
+ "Fields of the new record as the Google Ads REST API expects them (camelCase, enums as strings, money in micros as strings). Minimal examples:\n\n**Campaign**: `{\"name\":\"Spring sale\",\"status\":\"PAUSED\",\"advertisingChannelType\":\"SEARCH\",\"campaignBudget\":\"customers/1234567890/campaignBudgets/1122334455\",\"manualCpc\":{},\"networkSettings\":{\"targetGoogleSearch\":true,\"targetSearchNetwork\":true},\"containsEuPoliticalAdvertising\":\"DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING\"}`\n\n**Ad group**: `{\"name\":\"Running shoes\",\"statu": "Fields of the new record as the Google Ads REST API expects them (camelCase, enums as strings, money in micros as strings). Minimal examples:\n\n**Campaign**: `{\"name\":\"Spring sale\",\"status\":\"PAUSED\",\"advertisingChannelType\":\"SEARCH\",\"campaignBudget\":\"customers/1234567890/campaignBudgets/1122334455\",\"manualCpc\":{},\"networkSettings\":{\"targetGoogleSearch\":true,\"targetSearchNetwork\":true},\"containsEuPoliticalAdvertising\":\"DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING\"}`\n\n**Ad group**: `{\"name\":\"Running shoes\",\"status\":\"ENABLED\",\"type\":\"SEARCH_STANDARD\",\"campaign\":\"customers/1234567890/campaigns/123456789\",\"cpcBidMicros\":\"1000000\"}`\n\n**Ad**: `{\"adGroup\":\"customers/1234567890/adGroups/987654321\",\"status\":\"PAUSED\",\"ad\":{\"finalUrls\":[\"https://www.example.com/shoes\"],\"responsiveSearchAd\":{\"headlines\":[{\"text\":\"Running shoes\"},{\"text\":\"Free shipping\"},{\"text\":\"Shop today\"}],\"descriptions\":[{\"text\":\"Lightweight shoes for every runner.\"},{\"text\":\"Order now and run tomorrow.\"}]}}}`\n\n**Keyword**: `{\"adGroup\":\"customers/1234567890/adGroups/987654321\",\"status\":\"ENABLED\",\"keyword\":{\"text\":\"running shoes\",\"matchType\":\"PHRASE\"}}`\n\n**Audience list**: `{\"name\":\"Newsletter subscribers\",\"description\":\"Customers who opted in to the newsletter\",\"membershipLifeSpan\":\"30\",\"crmBasedUserList\":{\"uploadKeyType\":\"CONTACT_INFO\"}}`\n\nA campaign needs an existing campaign budget (`campaignBudgets:mutate` via Custom API Call).",
+ "Ask Google to validate the request without applying it. Nothing is created, changed or removed.": "Ask Google to validate the request without applying it. Nothing is created, changed or removed.",
+ "Numeric id for campaigns, ad groups and audience lists; `<adGroupId>~<adId>` for ads; `<adGroupId>~<criterionId>` for keywords. A full resource name (`customers/…/campaigns/…`) also works.": "Numeric id for campaigns, ad groups and audience lists; `<adGroupId>~<adId>` for ads; `<adGroupId>~<criterionId>` for keywords. A full resource name (`customers/…/campaigns/…`) also works.",
+ "Only the fields to change, as the Google Ads REST API names them (camelCase), e.g. `{\"status\":\"PAUSED\"}` or `{\"name\":\"New name\",\"cpcBidMicros\":\"1500000\"}`. The update mask is derived from these keys; fields you leave out are untouched. Ads are immutable except for `status`: to change an ad, create a new one.": "Only the fields to change, as the Google Ads REST API names them (camelCase), e.g. `{\"status\":\"PAUSED\"}` or `{\"name\":\"New name\",\"cpcBidMicros\":\"1500000\"}`. The update mask is derived from these keys; fields you leave out are untouched. Ads are immutable except for `status`: to change an ad, create a new one.",
+ "Google Ads Query Language SELECT statement. Examples: `SELECT campaign.id, campaign.name, campaign.status FROM campaign ORDER BY campaign.id` · `SELECT ad_group_criterion.criterion_id, ad_group_criterion.keyword.text FROM ad_group_criterion WHERE ad_group_criterion.type = KEYWORD` · `SELECT user_list.id, user_list.name FROM user_list`. Use `LIMIT` to cap the total.": "Google Ads Query Language SELECT statement. Examples: `SELECT campaign.id, campaign.name, campaign.status FROM campaign ORDER BY campaign.id` · `SELECT ad_group_criterion.criterion_id, ad_group_criterion.keyword.text FROM ad_group_criterion WHERE ad_group_criterion.type = KEYWORD` · `SELECT user_list.id, user_list.name FROM user_list`. Use `LIMIT` to cap the total.",
+ "Follow the pagination until the query is exhausted (up to Max Rows). Off: return one page and its next page token.": "Follow the pagination until the query is exhausted (up to Max Rows). Off: return one page and its next page token.",
+ "Only with \"Fetch All Pages\". Stops after this many rows (default 1000, at most 100000).": "Only with \"Fetch All Pages\". Stops after this many rows (default 1000, at most 100000).",
+ "Only without \"Fetch All Pages\": the `nextPageToken` of a previous run to continue from.": "Only without \"Fetch All Pages\": the `nextPageToken` of a previous run to continue from.",
+ "The level the metrics are broken down by.": "The level the metrics are broken down by.",
+ "YYYY-MM-DD, with the custom date range.": "YYYY-MM-DD, with the custom date range.",
+ "Adds `segments.date`, so each entity returns one row per day instead of a total.": "Adds `segments.date`, so each entity returns one row per day instead of a total.",
+ "GAQL metric fields. Default: metrics.impressions, metrics.clicks, metrics.ctr, metrics.average_cpc, metrics.cost_micros, metrics.conversions, metrics.conversions_value.": "GAQL metric fields. Default: metrics.impressions, metrics.clicks, metrics.ctr, metrics.average_cpc, metrics.cost_micros, metrics.conversions, metrics.conversions_value.",
+ "GAQL attribute fields to return next to the metrics (default: the id, name and status of the chosen level).": "GAQL attribute fields to return next to the metrics (default: the id, name and status of the chosen level).",
+ "Extra GAQL condition, e.g. `campaign.status = 'ENABLED'` or `metrics.clicks > 0`.": "Extra GAQL condition, e.g. `campaign.status = 'ENABLED'` or `metrics.clicks > 0`.",
+ "e.g. `metrics.clicks DESC`. The field must be selected.": "e.g. `metrics.clicks DESC`. The field must be selected.",
+ "Stops after this many rows (default 1000, at most 100000).": "Stops after this many rows (default 1000, at most 100000).",
+ "When filled, runs this query as-is and ignores every field above except Customer and Max Rows.": "When filled, runs this query as-is and ignores every field above except Customer and Max Rows.",
+ "CRM-based audience list (Customer Match) the members go to.": "CRM-based audience list (Customer Match) the members go to.",
+ "One entry per person. Fill any of: e-mail, phone (E.164, e.g. +5511999999999), or the full address set (first name, last name, country code, postal code). E-mail, phone, first name and last name are normalized and SHA-256 hashed before upload; country code and postal code are sent unhashed (trimmed, country code uppercased), as Google requires.": "One entry per person. Fill any of: e-mail, phone (E.164, e.g. +5511999999999), or the full address set (first name, last name, country code, postal code). E-mail, phone, first name and last name are normalized and SHA-256 hashed before upload; country code and postal code are sent unhashed (trimmed, country code uppercased), as Google requires.",
+ "Consent the members gave for their data to be used for advertising (required by Google for uploads, enforced in the EEA). Pick the value that matches what the members actually agreed to.": "Consent the members gave for their data to be used for advertising (required by Google for uploads, enforced in the EEA). Pick the value that matches what the members actually agreed to.",
+ "Consent the members gave for personalized advertising. Pick the value that matches what the members actually agreed to.": "Consent the members gave for personalized advertising. Pick the value that matches what the members actually agreed to.",
+ "Google requires every upload to confirm that the advertiser accepted the Customer Match terms of service (https://support.google.com/adspolicy/answer/6299717). Tick to confirm.": "Google requires every upload to confirm that the advertiser accepted the Customer Match terms of service (https://support.google.com/adspolicy/answer/6299717). Tick to confirm.",
+ "Poll the request status for up to ~2 minutes. Matching usually takes longer, so this is off by default: the output carries the request ids to check later.": "Poll the request status for up to ~2 minutes. Matching usually takes longer, so this is off by default: the output carries the request ids to check later.",
+ "Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",
+ "Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.",
+ "Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",
+ "On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",
+ "Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",
+ "Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",
+ "Campaign": "Campaign",
+ "Ad group": "Ad group",
+ "Ad": "Ad",
+ "Keyword": "Keyword",
+ "Audience list": "Audience list",
+ "Account": "Account",
+ "Search term": "Search term",
+ "today": "today",
+ "yesterday": "yesterday",
+ "last 7 days": "last 7 days",
+ "last 14 days": "last 14 days",
+ "last 30 days": "last 30 days",
+ "this week sun today": "this week sun today",
+ "this week mon today": "this week mon today",
+ "last week sun sat": "last week sun sat",
+ "last week mon sun": "last week mon sun",
+ "this month": "this month",
+ "last month": "last month",
+ "last business week": "last business week",
+ "custom (start / end date)": "custom (start / end date)",
+ "all time (no date filter)": "all time (no date filter)",
+ "Granted": "Granted",
+ "Denied": "Denied",
+ "Unspecified": "Unspecified",
+ "GET": "GET",
+ "POST": "POST",
+ "PATCH": "PATCH",
+ "PUT": "PUT",
+ "DELETE": "DELETE",
+ "HEAD": "HEAD",
+ "New Record": "New Record",
+ "Fires when a campaign, ad group, ad, keyword or audience list is created in the selected account (removed records are ignored)": "Fires when a campaign, ad group, ad, keyword or audience list is created in the selected account (removed records are ignored)"
+}
\ No newline at end of file
diff --git a/packages/pieces/community/google-ads/src/index.ts b/packages/pieces/community/google-ads/src/index.ts
new file mode 100644
index 00000000000..b48b1dffa9a
--- /dev/null
+++ b/packages/pieces/community/google-ads/src/index.ts
@@ -0,0 +1,50 @@
+import { createCustomApiCallAction } from '@activepieces/pieces-common';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
+
+import { addCustomerMatchData } from './lib/actions/add-customer-match-data';
+import { createRecord } from './lib/actions/create-record';
+import { deleteRecord } from './lib/actions/delete-record';
+import { removeCustomerMatchData } from './lib/actions/remove-customer-match-data';
+import { retrieveReport } from './lib/actions/retrieve-report';
+import { searchRecords } from './lib/actions/search-records';
+import { updateRecord } from './lib/actions/update-record';
+import { googleAdsAuth } from './lib/auth';
+import { googleAdsClient } from './lib/common/client';
+import { googleAdsUtils } from './lib/common/utils';
+import { newRecord } from './lib/triggers/new-record';
+
+export const googleAds = createPiece({
+ displayName: 'Google Ads',
+ description: 'Manage campaigns, ad groups, ads, keywords, audiences and performance reports in Google Ads.',
+ auth: googleAdsAuth,
+ minimumSupportedRelease: '0.88.0',
+ logoUrl: 'https://cdn.activepieces.com/pieces/google-ads.png',
+ categories: [PieceCategory.MARKETING],
+ authors: ['fabio-kozlowski'],
+ actions: [
+ createRecord,
+ updateRecord,
+ deleteRecord,
+ searchRecords,
+ retrieveReport,
+ addCustomerMatchData,
+ removeCustomerMatchData,
+ createCustomApiCallAction({
+ auth: googleAdsAuth,
+ baseUrl: () => googleAdsClient.baseUrl(),
+ description:
+ 'Call any Google Ads API endpoint. The path must start with the API version: /v25/customers/{customerId}/... (e.g. /v25/customers/1234567890/campaignBudgets:mutate). Data Manager API endpoints take a full URL on https://datamanager.googleapis.com (e.g. GET https://datamanager.googleapis.com/v1/requestStatus:retrieve?requestId=... to check a Customer Match upload).',
+ authMapping: async (auth, propsValue) => {
+ const urlProp: unknown = propsValue['url'];
+ googleAdsUtils.assertAllowedUrl(typeof urlProp === 'object' && urlProp !== null ? Object.fromEntries(Object.entries(urlProp))['url'] : undefined);
+ const raw: unknown = auth.props?.['loginCustomerId'];
+ const loginCustomerId = typeof raw === 'string' ? raw.trim() : undefined;
+ return {
+ Authorization: `Bearer ${auth.access_token}`,
+ ...(loginCustomerId ? { 'login-customer-id': googleAdsUtils.normalizeCustomerId(loginCustomerId) } : {}),
+ };
+ },
+ }),
+ ],
+ triggers: [newRecord],
+});
diff --git a/packages/pieces/community/google-ads/src/lib/actions/add-customer-match-data.ts b/packages/pieces/community/google-ads/src/lib/actions/add-customer-match-data.ts
new file mode 100644
index 00000000000..dbf85d6cdec
--- /dev/null
+++ b/packages/pieces/community/google-ads/src/lib/actions/add-customer-match-data.ts
@@ -0,0 +1,70 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+
+import { googleAdsAuth } from '../auth';
+import { googleAdsApi } from '../common/api';
+import { googleAdsProps } from '../common/props';
+import type { GoogleAdsConsentStatus } from '../common/types';
+import { googleAdsUtils } from '../common/utils';
+import { customerMatchOutputSchema } from '../output-schemas';
+
+const CONSENT_OPTIONS: { label: string; value: GoogleAdsConsentStatus }[] = [
+ { label: 'Granted', value: 'GRANTED' },
+ { label: 'Denied', value: 'DENIED' },
+ { label: 'Unspecified', value: 'UNSPECIFIED' },
+];
+
+export const addCustomerMatchData = createAction({
+ name: 'addCustomerMatchData',
+ classification: 'WRITE',
+ displayName: 'Add Customer Match Data',
+ description: 'Upload e-mails, phones or addresses to a Customer Match audience list (Data Manager API)',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Add people to a CRM-based Customer Match audience list by e-mail, phone or full address; e-mails, phones, first and last names are normalized and SHA-256 hashed before upload, while country code and postal code are sent unhashed (trimmed, country code uppercased), as Google requires. Use to grow an audience for targeting; to take people out use Remove customer match data. Requires consent values and confirmation that the Customer Match terms were accepted. Processing is asynchronous; re-adding the same members does not duplicate them.',
+ idempotent: true,
+ },
+ auth: googleAdsAuth,
+ props: {
+ customerId: googleAdsProps.customerId({ required: true }),
+ userList: googleAdsProps.userList({ required: true }),
+ members: googleAdsProps.members({ required: true }),
+ adUserData: Property.StaticDropdown<GoogleAdsConsentStatus, true>({
+ displayName: 'Consent: Ad User Data',
+ description:
+ 'Consent the members gave for their data to be used for advertising (required by Google for uploads, enforced in the EEA). Pick the value that matches what the members actually agreed to.',
+ required: true,
+ options: { options: CONSENT_OPTIONS },
+ }),
+ adPersonalization: Property.StaticDropdown<GoogleAdsConsentStatus, true>({
+ displayName: 'Consent: Ad Personalization',
+ description: 'Consent the members gave for personalized advertising. Pick the value that matches what the members actually agreed to.',
+ required: true,
+ options: { options: CONSENT_OPTIONS },
+ }),
+ acceptTerms: Property.Checkbox({
+ displayName: 'Customer Match Terms Accepted',
+ description:
+ 'Google requires every upload to confirm that the advertiser accepted the Customer Match terms of service (https://support.google.com/adspolicy/answer/6299717). Tick to confirm.',
+ required: true,
+ defaultValue: false,
+ }),
+ waitForCompletion: googleAdsProps.waitForCompletion({ required: false }),
+ },
+ outputSchema: customerMatchOutputSchema,
+ async run(context) {
+ const { customerId, userList, members, adUserData, adPersonalization, acceptTerms, waitForCompletion } = context.propsValue;
+ if (!acceptTerms) {
+ throw new Error('Customer Match uploads require the advertiser to accept Google\'s Customer Match terms of service. Tick "Customer Match Terms Accepted".');
+ }
+ return await googleAdsApi.uploadCustomerMatch({
+ auth: context.auth,
+ customerId,
+ userList,
+ members: (members ?? []).map(googleAdsUtils.toMemberInput),
+ mode: 'add',
+ consent: { adUserData, adPersonalization },
+ waitForCompletion: Boolean(waitForCompletion),
+ });
+ },
+});
diff --git a/packages/pieces/community/google-ads/src/lib/actions/create-record.ts b/packages/pieces/community/google-ads/src/lib/actions/create-record.ts
new file mode 100644
index 00000000000..91922dfb033
--- /dev/null
+++ b/packages/pieces/community/google-ads/src/lib/actions/create-record.ts
@@ -0,0 +1,40 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+
+import { googleAdsAuth } from '../auth';
+import { googleAdsApi } from '../common/api';
+import { googleAdsProps } from '../common/props';
+import { googleAdsUtils } from '../common/utils';
+import { recordMutationOutputSchema } from '../output-schemas';
+
+const CREATE_EXAMPLES = googleAdsUtils.resources.map((def) => `**${def.label}**: \`${JSON.stringify(def.createExample)}\``).join('\n\n');
+
+export const createRecord = createAction({
+ name: 'createRecord',
+ classification: 'WRITE',
+ displayName: 'Create Record',
+ description: 'Create a campaign, ad group, ad, keyword or audience list',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Create one Google Ads campaign, ad group, ad, keyword or audience list from a JSON body in the REST API shape (camelCase, enums as strings, money in micros). Use Update record to change an existing one. Set Validate Only to dry-run. Each call creates a new record, so retries duplicate.',
+ idempotent: false,
+ },
+ auth: googleAdsAuth,
+ props: {
+ customerId: googleAdsProps.customerId({ required: true }),
+ resourceType: googleAdsProps.resourceType({ required: true }),
+ record: Property.Json({
+ displayName: 'Record',
+ description: `Fields of the new record as the Google Ads REST API expects them (camelCase, enums as strings, money in micros as strings). Minimal examples:\n\n${CREATE_EXAMPLES}\n\nA campaign needs an existing campaign budget (\`campaignBudgets:mutate\` via Custom API Call).`,
+ required: true,
+ }),
+ validateOnly: googleAdsProps.validateOnly({ required: false }),
+ },
+ outputSchema: recordMutationOutputSchema,
+ async run(context) {
+ const { customerId, resourceType, record, validateOnly } = context.propsValue;
+ const def = googleAdsUtils.resourceDefinition(resourceType);
+ const body = Object.fromEntries(Object.entries(record).filter(([key]) => key !== 'resourceName'));
+ return await googleAdsApi.mutateRecord({ auth: context.auth, customerId, def, operation: { create: body }, validateOnly: Boolean(validateOnly) });
+ },
+});
diff --git a/packages/pieces/community/google-ads/src/lib/actions/delete-record.ts b/packages/pieces/community/google-ads/src/lib/actions/delete-record.ts
new file mode 100644
index 00000000000..474057922e6
--- /dev/null
+++ b/packages/pieces/community/google-ads/src/lib/actions/delete-record.ts
@@ -0,0 +1,41 @@
+import { createAction } from '@activepieces/pieces-framework';
+
+import { googleAdsAuth } from '../auth';
+import { googleAdsApi } from '../common/api';
+import { googleAdsProps } from '../common/props';
+import { googleAdsUtils } from '../common/utils';
+import { deleteRecordOutputSchema } from '../output-schemas';
+
+export const deleteRecord = createAction({
+ name: 'deleteRecord',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Record',
+ description: 'Remove a campaign, ad group, ad, keyword or audience list (Google marks it REMOVED; it cannot be restored)',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Permanently remove a Google Ads campaign, ad group, ad, keyword or audience list by id or resource name; Google marks it REMOVED and it cannot be restored. To stop delivery reversibly, use Update record with status PAUSED instead. A retry of a completed removal fails.',
+ idempotent: false,
+ },
+ auth: googleAdsAuth,
+ props: {
+ customerId: googleAdsProps.customerId({ required: true }),
+ resourceType: googleAdsProps.resourceType({ required: true }),
+ identifier: googleAdsProps.identifier({ required: true }),
+ validateOnly: googleAdsProps.validateOnly({ required: false }),
+ },
+ outputSchema: deleteRecordOutputSchema,
+ async run(context) {
+ const { customerId, resourceType, identifier, validateOnly } = context.propsValue;
+ const def = googleAdsUtils.resourceDefinition(resourceType);
+ const resourceName = googleAdsUtils.resourceNameFor({ def, customerId: googleAdsUtils.normalizeCustomerId(customerId), identifier });
+ const result = await googleAdsApi.mutateRecord({
+ auth: context.auth,
+ customerId,
+ def,
+ operation: { remove: resourceName },
+ validateOnly: Boolean(validateOnly),
+ });
+ return { ...result, resourceName: result.resourceName ?? resourceName, removed: !validateOnly };
+ },
+});
diff --git a/packages/pieces/community/google-ads/src/lib/actions/remove-customer-match-data.ts b/packages/pieces/community/google-ads/src/lib/actions/remove-customer-match-data.ts
new file mode 100644
index 00000000000..7dbad28fffd
--- /dev/null
+++ b/packages/pieces/community/google-ads/src/lib/actions/remove-customer-match-data.ts
@@ -0,0 +1,39 @@
+import { createAction } from '@activepieces/pieces-framework';
+
+import { googleAdsAuth } from '../auth';
+import { googleAdsApi } from '../common/api';
+import { googleAdsProps } from '../common/props';
+import { googleAdsUtils } from '../common/utils';
+import { customerMatchOutputSchema } from '../output-schemas';
+
+export const removeCustomerMatchData = createAction({
+ name: 'removeCustomerMatchData',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Remove Customer Match Data',
+ description: 'Remove members (by e-mail, phone or address) from a Customer Match audience list (Data Manager API)',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Remove people from a CRM-based Customer Match audience list, matched by e-mail, phone or full address (e-mails, phones, first and last names are SHA-256 hashed; country code and postal code are sent unhashed). Use for opt-outs or deletion requests; to add people use Add customer match data. Processing is asynchronous; removing members that are not in the list is harmless, so retries are safe.',
+ idempotent: true,
+ },
+ auth: googleAdsAuth,
+ props: {
+ customerId: googleAdsProps.customerId({ required: true }),
+ userList: googleAdsProps.userList({ required: true }),
+ members: googleAdsProps.members({ required: true }),
+ waitForCompletion: googleAdsProps.waitForCompletion({ required: false }),
+ },
+ outputSchema: customerMatchOutputSchema,
+ async run(context) {
+ const { customerId, userList, members, waitForCompletion } = context.propsValue;
+ return await googleAdsApi.uploadCustomerMatch({
+ auth: context.auth,
+ customerId,
+ userList,
+ members: (members ?? []).map(googleAdsUtils.toMemberInput),
+ mode: 'remove',
+ waitForCompletion: Boolean(waitForCompletion),
+ });
+ },
+});
diff --git a/packages/pieces/community/google-ads/src/lib/actions/retrieve-report.ts b/packages/pieces/community/google-ads/src/lib/actions/retrieve-report.ts
new file mode 100644
index 00000000000..efd29f77f44
--- /dev/null
+++ b/packages/pieces/community/google-ads/src/lib/actions/retrieve-report.ts
@@ -0,0 +1,105 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+
+import { googleAdsAuth } from '../auth';
+import { googleAdsApi } from '../common/api';
+import { googleAdsProps } from '../common/props';
+import type { GoogleAdsDateRangePreset, GoogleAdsReportResource } from '../common/types';
+import { googleAdsUtils } from '../common/utils';
+import { retrieveReportOutputSchema } from '../output-schemas';
+
+const DEFAULT_MAX_ROWS = 1000;
+const HARD_MAX_ROWS = 100_000;
+
+const RESOURCE_OPTIONS = googleAdsUtils.reportResourceTypes.map((value) => ({ label: googleAdsUtils.reportResources[value].label, value }));
+
+const DATE_RANGE_OPTIONS: { label: string; value: GoogleAdsDateRangePreset }[] = [
+ ...googleAdsUtils.dateRangePresets.map((value) => ({ label: value.replace(/_/g, ' ').toLowerCase(), value })),
+ { label: 'custom (start / end date)', value: 'CUSTOM' },
+ { label: 'all time (no date filter)', value: 'ALL_TIME' },
+];
+
+export const retrieveReport = createAction({
+ name: 'retrieveReport',
+ classification: 'SEARCH',
+ displayName: 'Retrieve Advertising Report',
+ description: 'Performance metrics per campaign, ad group, ad, keyword, search term or account, over a date range',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Get performance metrics (impressions, clicks, cost, conversions and more) for one Google Ads account, broken down by account, campaign, ad group, ad, keyword or search term over a date range, as flat rows keyed by GAQL field name. Use for reporting; to list records without metrics use Search records. Cost values are in micros; read-only and safe to retry.',
+ idempotent: true,
+ },
+ auth: googleAdsAuth,
+ props: {
+ customerId: googleAdsProps.customerId({ required: true }),
+ resource: Property.StaticDropdown<GoogleAdsReportResource, true>({
+ displayName: 'Report On',
+ description: 'The level the metrics are broken down by.',
+ required: true,
+ defaultValue: 'campaign',
+ options: { options: RESOURCE_OPTIONS },
+ }),
+ dateRange: Property.StaticDropdown<GoogleAdsDateRangePreset, true>({
+ displayName: 'Date Range',
+ required: true,
+ defaultValue: 'LAST_30_DAYS',
+ options: { options: DATE_RANGE_OPTIONS },
+ }),
+ startDate: Property.ShortText({ displayName: 'Start Date', description: 'YYYY-MM-DD, with the custom date range.', required: false }),
+ endDate: Property.ShortText({ displayName: 'End Date', description: 'YYYY-MM-DD, with the custom date range.', required: false }),
+ segmentByDate: Property.Checkbox({
+ displayName: 'One Row per Day',
+ description: 'Adds `segments.date`, so each entity returns one row per day instead of a total.',
+ required: false,
+ defaultValue: false,
+ }),
+ metrics: Property.Array({
+ displayName: 'Metrics',
+ description: `GAQL metric fields. Default: ${googleAdsUtils.defaultMetrics.join(', ')}.`,
+ required: false,
+ }),
+ fields: Property.Array({
+ displayName: 'Entity Fields',
+ description: 'GAQL attribute fields to return next to the metrics (default: the id, name and status of the chosen level).',
+ required: false,
+ }),
+ where: Property.ShortText({
+ displayName: 'Filter',
+ description: "Extra GAQL condition, e.g. `campaign.status = 'ENABLED'` or `metrics.clicks > 0`.",
+ required: false,
+ }),
+ orderBy: Property.ShortText({ displayName: 'Order By', description: 'e.g. `metrics.clicks DESC`. The field must be selected.', required: false }),
+ maxRows: Property.Number({
+ displayName: 'Max Rows',
+ description: `Stops after this many rows (default ${DEFAULT_MAX_ROWS}, at most ${HARD_MAX_ROWS}).`,
+ required: false,
+ defaultValue: DEFAULT_MAX_ROWS,
+ }),
+ query: Property.LongText({
+ displayName: 'Advanced: Full GAQL Query',
+ description: 'When filled, runs this query as-is and ignores every field above except Customer and Max Rows.',
+ required: false,
+ }),
+ },
+ outputSchema: retrieveReportOutputSchema,
+ async run(context) {
+ const { customerId, resource, dateRange, startDate, endDate, segmentByDate, metrics, fields, where, orderBy, maxRows, query } = context.propsValue;
+ const gaql =
+ query?.trim() ||
+ googleAdsUtils.buildReportQuery({
+ resource,
+ dateRange,
+ startDate: startDate || undefined,
+ endDate: endDate || undefined,
+ segmentByDate: Boolean(segmentByDate),
+ metrics: (metrics ?? []).map(String),
+ fields: (fields ?? []).map(String),
+ where: where || undefined,
+ orderBy: orderBy || undefined,
+ });
+ const cap = Math.min(Math.max(Math.floor(Number(maxRows) || DEFAULT_MAX_ROWS), 1), HARD_MAX_ROWS);
+ const { results, truncated } = await googleAdsApi.searchAll({ auth: context.auth, customerId, query: gaql, maxRows: cap });
+ const rows = results.map((row) => googleAdsUtils.flattenRow(row));
+ return { query: gaql, rows, count: rows.length, truncated };
+ },
+});
diff --git a/packages/pieces/community/google-ads/src/lib/actions/search-records.ts b/packages/pieces/community/google-ads/src/lib/actions/search-records.ts
new file mode 100644
index 00000000000..113be303c58
--- /dev/null
+++ b/packages/pieces/community/google-ads/src/lib/actions/search-records.ts
@@ -0,0 +1,61 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+
+import { googleAdsAuth } from '../auth';
+import { googleAdsApi } from '../common/api';
+import { googleAdsProps } from '../common/props';
+import { searchRecordsOutputSchema } from '../output-schemas';
+
+const DEFAULT_MAX_ROWS = 1000;
+const HARD_MAX_ROWS = 100_000;
+
+export const searchRecords = createAction({
+ name: 'searchRecords',
+ classification: 'SEARCH',
+ displayName: 'Search Records',
+ description: 'Run a GAQL query (campaigns, ad groups, ads, keywords, audiences, reports) with pagination',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Run a read-only Google Ads Query Language (GAQL) SELECT against one account and return the raw nested rows, one page at a time or all pages up to a row cap. Use to find campaigns, ad groups, ads, keywords or audience lists and their ids; for metrics over a date range with flat rows prefer Retrieve advertising report. Only SELECT is accepted; safe to retry.',
+ idempotent: true,
+ },
+ auth: googleAdsAuth,
+ props: {
+ customerId: googleAdsProps.customerId({ required: true }),
+ query: Property.LongText({
+ displayName: 'GAQL Query',
+ description:
+ 'Google Ads Query Language SELECT statement. Examples: `SELECT campaign.id, campaign.name, campaign.status FROM campaign ORDER BY campaign.id` · `SELECT ad_group_criterion.criterion_id, ad_group_criterion.keyword.text FROM ad_group_criterion WHERE ad_group_criterion.type = KEYWORD` · `SELECT user_list.id, user_list.name FROM user_list`. Use `LIMIT` to cap the total.',
+ required: true,
+ }),
+ fetchAllPages: Property.Checkbox({
+ displayName: 'Fetch All Pages',
+ description: 'Follow the pagination until the query is exhausted (up to Max Rows). Off: return one page and its next page token.',
+ required: false,
+ defaultValue: false,
+ }),
+ maxRows: Property.Number({
+ displayName: 'Max Rows',
+ description: `Only with "Fetch All Pages". Stops after this many rows (default ${DEFAULT_MAX_ROWS}, at most ${HARD_MAX_ROWS}).`,
+ required: false,
+ defaultValue: DEFAULT_MAX_ROWS,
+ }),
+ pageToken: Property.ShortText({
+ displayName: 'Page Token',
+ description: 'Only without "Fetch All Pages": the `nextPageToken` of a previous run to continue from.',
+ required: false,
+ }),
+ },
+ outputSchema: searchRecordsOutputSchema,
+ async run(context) {
+ const { customerId, query, fetchAllPages, maxRows, pageToken } = context.propsValue;
+ if (fetchAllPages) {
+ const cap = Math.min(Math.max(Math.floor(Number(maxRows) || DEFAULT_MAX_ROWS), 1), HARD_MAX_ROWS);
+ const { results, truncated } = await googleAdsApi.searchAll({ auth: context.auth, customerId, query, maxRows: cap });
+ return { results, count: results.length, truncated };
+ }
+ const page = await googleAdsApi.search({ auth: context.auth, customerId, query, pageToken: pageToken || undefined });
+ const results = page.results ?? [];
+ return { results, count: results.length, nextPageToken: page.nextPageToken ?? null };
+ },
+});
diff --git a/packages/pieces/community/google-ads/src/lib/actions/update-record.ts b/packages/pieces/community/google-ads/src/lib/actions/update-record.ts
new file mode 100644
index 00000000000..526978dd212
--- /dev/null
+++ b/packages/pieces/community/google-ads/src/lib/actions/update-record.ts
@@ -0,0 +1,48 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+
+import { googleAdsAuth } from '../auth';
+import { googleAdsApi } from '../common/api';
+import { googleAdsProps } from '../common/props';
+import { googleAdsUtils } from '../common/utils';
+import { recordMutationOutputSchema } from '../output-schemas';
+
+export const updateRecord = createAction({
+ name: 'updateRecord',
+ classification: 'WRITE',
+ displayName: 'Update Record',
+ description: 'Change fields of an existing campaign, ad group, ad, keyword or audience list',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Set fields of an existing Google Ads campaign, ad group, ad, keyword or audience list, identified by id or resource name; only the fields sent are changed (for example pause a campaign with {"status":"PAUSED"}). Ads only accept status changes. Use Create record for new ones. Safe to retry: it sets the same values again.',
+ idempotent: true,
+ },
+ auth: googleAdsAuth,
+ props: {
+ customerId: googleAdsProps.customerId({ required: true }),
+ resourceType: googleAdsProps.resourceType({ required: true }),
+ identifier: googleAdsProps.identifier({ required: true }),
+ record: Property.Json({
+ displayName: 'Fields to Update',
+ description:
+ 'Only the fields to change, as the Google Ads REST API names them (camelCase), e.g. `{"status":"PAUSED"}` or `{"name":"New name","cpcBidMicros":"1500000"}`. The update mask is derived from these keys; fields you leave out are untouched. Ads are immutable except for `status`: to change an ad, create a new one.',
+ required: true,
+ }),
+ validateOnly: googleAdsProps.validateOnly({ required: false }),
+ },
+ outputSchema: recordMutationOutputSchema,
+ async run(context) {
+ const { customerId, resourceType, identifier, record, validateOnly } = context.propsValue;
+ const def = googleAdsUtils.resourceDefinition(resourceType);
+ const resourceName = googleAdsUtils.resourceNameFor({ def, customerId: googleAdsUtils.normalizeCustomerId(customerId), identifier });
+ const fields = Object.fromEntries(Object.entries(record).filter(([key]) => key !== 'resourceName'));
+ const updateMask = googleAdsUtils.updateMaskFor(fields);
+ return await googleAdsApi.mutateRecord({
+ auth: context.auth,
+ customerId,
+ def,
+ operation: { update: { ...fields, resourceName }, updateMask },
+ validateOnly: Boolean(validateOnly),
+ });
+ },
+});
diff --git a/packages/pieces/community/google-ads/src/lib/auth.ts b/packages/pieces/community/google-ads/src/lib/auth.ts
new file mode 100644
index 00000000000..ddc6d772fe2
--- /dev/null
+++ b/packages/pieces/community/google-ads/src/lib/auth.ts
@@ -0,0 +1,35 @@
+import { PieceAuth, Property } from '@activepieces/pieces-framework';
+
+export const googleAdsScopes = [
+ 'https://www.googleapis.com/auth/adwords',
+ 'https://www.googleapis.com/auth/datamanager',
+ 'email',
+];
+
+const connectionInstructions = `
+Connect with an OAuth client from **your own** Google Cloud project:
+
+1. In [Google Cloud Console](https://console.cloud.google.com/), select or create a project. **APIs & Services → Library**: enable **Google Ads API** and **Data Manager API** (the latter only for Customer Match uploads).
+2. Open the **Google Ads API** page in the console and check the project's **access level**. New projects get *Test* access (test accounts only). To operate real accounts, apply for *Explorer* or *Basic* access there (Google reviews it, typically within 10 business days).
+3. **APIs & Services → OAuth consent screen**: add the scopes \`https://www.googleapis.com/auth/adwords\` and \`https://www.googleapis.com/auth/datamanager\`. While the app is in *Testing*, add the Google accounts that will connect as test users.
+4. **APIs & Services → Credentials → Create credentials → OAuth client ID**, type *Web application*. Add the **Redirect URL shown below** to *Authorized redirect URIs*.
+5. Paste the **Client ID** and **Client Secret** here and sign in with a Google account that can access the Google Ads accounts you want to automate.
+
+**Login Customer ID (Manager Account)**: fill it only when you reach the accounts through a **manager (MCC) account**: the manager's 10-digit ID. Leave it empty when you connect directly as the advertiser.
+`.trim();
+
+export const googleAdsAuth = PieceAuth.OAuth2({
+ description: connectionInstructions,
+ authUrl: 'https://accounts.google.com/o/oauth2/auth',
+ tokenUrl: 'https://oauth2.googleapis.com/token',
+ required: true,
+ scope: googleAdsScopes,
+ props: {
+ loginCustomerId: Property.ShortText({
+ displayName: 'Login Customer ID (Manager Account)',
+ description:
+ 'Only when you access client accounts through a manager (MCC) account: the manager\'s 10-digit customer ID, with or without dashes. Leave empty when connecting directly as the advertiser.',
+ required: false,
+ }),
+ },
+});
diff --git a/packages/pieces/community/google-ads/src/lib/common/api.ts b/packages/pieces/community/google-ads/src/lib/common/api.ts
new file mode 100644
index 00000000000..7decf70ec33
--- /dev/null
+++ b/packages/pieces/community/google-ads/src/lib/common/api.ts
@@ -0,0 +1,319 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+
+import { googleAdsClient } from './client';
+import type {
+ GoogleAdsAuthValue,
+ GoogleAdsCustomerInfo,
+ GoogleAdsCustomerMatchRequest,
+ GoogleAdsCustomerMatchResult,
+ GoogleAdsDestination,
+ GoogleAdsFieldWarning,
+ GoogleAdsIngestResponse,
+ GoogleAdsMutateResponse,
+ GoogleAdsRecordMutationResult,
+ GoogleAdsRecordOperation,
+ GoogleAdsRequestStatusPerDestination,
+ GoogleAdsRequestStatusResponse,
+ GoogleAdsResourceDefinition,
+ GoogleAdsRow,
+ GoogleAdsSearchAllResult,
+ GoogleAdsSearchPage,
+ GoogleAdsUploadParams,
+} from './types';
+import { googleAdsUtils } from './utils';
+
+async function listAccessibleCustomers({ auth }: { auth: GoogleAdsAuthValue }): Promise<string[]> {
+ const body = await googleAdsClient.request<{ resourceNames?: string[] }>({ auth, method: HttpMethod.GET, path: '/customers:listAccessibleCustomers' });
+ return (body.resourceNames ?? []).map((name) => name.replace(/^customers\//, ''));
+}
+
+async function search({ auth, customerId, query, pageToken }: SearchParams & { auth: GoogleAdsAuthValue }): Promise<GoogleAdsSearchPage> {
+ return await googleAdsClient.request<GoogleAdsSearchPage>({
+ auth,
+ method: HttpMethod.POST,
+ path: `/customers/${googleAdsUtils.normalizeCustomerId(customerId)}/googleAds:search`,
+ body: { query: googleAdsUtils.assertGaql(query), ...(pageToken ? { pageToken } : {}) },
+ });
+}
+
+async function searchAll({ auth, customerId, query, maxRows }: SearchParams & { auth: GoogleAdsAuthValue; maxRows: number }): Promise<GoogleAdsSearchAllResult> {
+ const limit = Math.max(Math.floor(maxRows), 1);
+ const results: GoogleAdsRow[] = [];
+ let pageToken: string | undefined;
+ do {
+ const page = await search({ auth, customerId, query, pageToken });
+ const rows = page.results ?? [];
+ const room = limit - results.length;
+ results.push(...rows.slice(0, room));
+ pageToken = page.nextPageToken || undefined;
+ if (results.length >= limit) {
+ return { results, truncated: rows.length > room || pageToken !== undefined };
+ }
+ } while (pageToken);
+ return { results, truncated: false };
+}
+
+async function mutateRecord({ auth, customerId, def, operation, validateOnly }: MutateRecordParams & { auth: GoogleAdsAuthValue }): Promise<GoogleAdsRecordMutationResult> {
+ const normalizedCustomerId = googleAdsUtils.normalizeCustomerId(customerId);
+ const response = await googleAdsClient.request<GoogleAdsMutateResponse>({
+ auth,
+ method: HttpMethod.POST,
+ path: `/customers/${normalizedCustomerId}/googleAds:mutate`,
+ body: {
+ mutateOperations: [googleAdsUtils.buildOperation({ def, operation })],
+ validateOnly,
+ responseContentType: 'MUTABLE_RESOURCE',
+ },
+ });
+ const { resourceName, ...rest } = response.mutateOperationResponses?.[0]?.[def.resultKey] ?? {};
+ const returned = Object.keys(rest).length > 0 ? rest : null;
+ const record =
+ returned === null && resourceName && !validateOnly && !('remove' in operation)
+ ? await findRecord({ auth, customerId: normalizedCustomerId, query: googleAdsUtils.recordByResourceNameQuery({ def, resourceName }) })
+ : returned;
+ return {
+ resourceType: def.type,
+ resourceName: resourceName ?? null,
+ id: googleAdsUtils.idFromResourceName(resourceName),
+ record,
+ validateOnly,
+ };
+}
+
+async function listCustomerClients({ auth, managerId }: { auth: GoogleAdsAuthValue; managerId: string }): Promise<{ clients: GoogleAdsCustomerInfo[]; truncated: boolean }> {
+ const { results, truncated } = await searchAll({
+ auth,
+ customerId: managerId,
+ query:
+ "SELECT customer_client.id, customer_client.descriptive_name, customer_client.manager, customer_client.test_account, customer_client.level, customer_client.status FROM customer_client ORDER BY customer_client.level, customer_client.descriptive_name",
+ maxRows: MAX_CUSTOMER_CLIENTS,
+ });
+ return { clients: results.map((row) => ({ ...row.customerClient, id: String(row.customerClient?.id ?? '') })), truncated };
+}
+
+async function getCustomerInfo({ auth, customerId }: { auth: GoogleAdsAuthValue; customerId: string }): Promise<GoogleAdsCustomerInfo> {
+ const page = await search({
+ auth,
+ customerId,
+ query: 'SELECT customer.id, customer.descriptive_name, customer.manager, customer.test_account FROM customer LIMIT 1',
+ });
+ return { ...page.results?.[0]?.customer, id: customerId };
+}
+
+async function listContactInfoUserLists({ auth, customerId }: { auth: GoogleAdsAuthValue; customerId: string }): Promise<GoogleAdsSearchAllResult> {
+ return await searchAll({
+ auth,
+ customerId,
+ query:
+ "SELECT user_list.resource_name, user_list.id, user_list.name FROM user_list WHERE user_list.type = 'CRM_BASED' AND user_list.crm_based_user_list.upload_key_type = 'CONTACT_INFO' ORDER BY user_list.name",
+ maxRows: MAX_USER_LISTS,
+ });
+}
+
+async function listNewestRecords({ auth, customerId, def, limit }: { auth: GoogleAdsAuthValue; customerId: string; def: GoogleAdsResourceDefinition; limit: number }): Promise<GoogleAdsRow[]> {
+ const page = await search({ auth, customerId, query: googleAdsUtils.newestRecordsQuery({ def, limit }) });
+ return page.results ?? [];
+}
+
+async function listRecordsAfterId({ auth, customerId, def, afterId }: { auth: GoogleAdsAuthValue; customerId: string; def: GoogleAdsResourceDefinition; afterId: string }): Promise<GoogleAdsRow[]> {
+ const { results } = await searchAll({ auth, customerId, query: googleAdsUtils.recordsAfterIdQuery({ def, afterId }), maxRows: MAX_ROWS_PER_POLL });
+ return results;
+}
+
+async function listRecordsByResourceNames({ auth, customerId, def, resourceNames }: { auth: GoogleAdsAuthValue; customerId: string; def: GoogleAdsResourceDefinition; resourceNames: string[] }): Promise<GoogleAdsRow[]> {
+ const rows: GoogleAdsRow[] = [];
+ for (let start = 0; start < resourceNames.length; start += NAMES_PER_QUERY) {
+ const chunk = resourceNames.slice(start, start + NAMES_PER_QUERY);
+ const { results } = await searchAll({ auth, customerId, query: googleAdsUtils.recordsByResourceNamesQuery({ def, resourceNames: chunk }), maxRows: chunk.length });
+ rows.push(...results);
+ }
+ return rows;
+}
+
+async function listCreateEvents({ auth, customerId, changeEventType, after, until, order, limit }: ListCreateEventsParams & { auth: GoogleAdsAuthValue }): Promise<GoogleAdsRow[]> {
+ if (!/^[A-Z_]+$/.test(changeEventType) || !TIMESTAMP.test(after) || !TIMESTAMP.test(until)) {
+ throw new Error(`Invalid change event query (${changeEventType}, ${after}, ${until}).`);
+ }
+ const { results } = await searchAll({
+ auth,
+ customerId,
+ query: [
+ 'SELECT change_event.resource_name, change_event.change_date_time, change_event.change_resource_name FROM change_event',
+ `WHERE change_event.change_date_time > '${after}' AND change_event.change_date_time <= '${until}'`,
+ `AND change_event.change_resource_type = '${changeEventType}' AND change_event.resource_change_operation = 'CREATE'`,
+ `ORDER BY change_event.change_date_time ${order} LIMIT ${limit}`,
+ ].join(' '),
+ maxRows: limit,
+ });
+ return results;
+}
+
+async function uploadCustomerMatch({ auth, ...params }: GoogleAdsUploadParams & { auth: GoogleAdsAuthValue }): Promise<GoogleAdsCustomerMatchResult> {
+ const { batches, identifiers } = googleAdsUtils.buildMemberBatches({ members: params.members, limit: MEMBERS_PER_REQUEST });
+ const userListId = googleAdsUtils.userListIdFrom({ userList: params.userList, customerId: params.customerId });
+ await assertContactInfoList({ auth, customerId: params.customerId, userListId });
+ const loginCustomerId = auth.props?.loginCustomerId?.trim();
+ const destination: GoogleAdsDestination = {
+ operatingAccount: { accountType: 'GOOGLE_ADS', accountId: googleAdsUtils.normalizeCustomerId(params.customerId) },
+ ...(loginCustomerId ? { loginAccount: { accountType: 'GOOGLE_ADS', accountId: googleAdsUtils.normalizeCustomerId(loginCustomerId) } } : {}),
+ productDestinationId: userListId,
+ };
+
+ const requestIds: string[] = [];
+ const fieldWarnings: GoogleAdsFieldWarning[] = [];
+ for (const [index, audienceMembers] of batches.entries()) {
+ try {
+ const answer = await googleAdsClient.dataManagerRequest<GoogleAdsIngestResponse>({
+ auth,
+ method: HttpMethod.POST,
+ path: params.mode === 'add' ? '/audienceMembers:ingest' : '/audienceMembers:remove',
+ body: {
+ destinations: [destination],
+ audienceMembers,
+ encoding: 'HEX',
+ ...(params.mode === 'add'
+ ? {
+ consent: { adUserData: CONSENT[params.consent.adUserData], adPersonalization: CONSENT[params.consent.adPersonalization] },
+ termsOfService: { customerMatchTermsOfServiceStatus: 'ACCEPTED' },
+ }
+ : {}),
+ },
+ });
+ if (!answer.requestId) {
+ throw new Error('Google accepted the request but did not return a request id, so its processing cannot be tracked; the change may have been applied. Check the audience list before retrying.');
+ }
+ requestIds.push(answer.requestId);
+ fieldWarnings.push(...(answer.fieldWarnings ?? []));
+ } catch (error) {
+ if (requestIds.length === 0) throw error;
+ const reason = (error instanceof Error ? error.message : String(error)).replace(/\.$/, '');
+ throw new Error(
+ `Batch ${index + 1} of ${batches.length} failed: ${reason}. Google already accepted requests ${requestIds.join(', ')} for the earlier batches; ${STATUS_CHECK_HINT} before retrying, since a retry sends those batches again.`
+ );
+ }
+ }
+
+ const statuses = params.waitForCompletion ? await waitForRequests({ auth, requestIds }) : requestIds.map(() => []);
+ const destinations = statuses.flat();
+ const requests: GoogleAdsCustomerMatchRequest[] = requestIds.map((requestId, index) => {
+ const matchRateRange = (statuses[index] ?? []).map((d) => d.audienceMembersIngestionStatus?.userDataIngestionStatus?.uploadMatchRateRange).find(Boolean);
+ return { requestId, status: statusOf(statuses[index] ?? []), ...(matchRateRange ? { matchRateRange } : {}) };
+ });
+ return {
+ requestIds,
+ userList: params.userList,
+ userListId,
+ mode: params.mode,
+ members: params.members.length,
+ identifiers,
+ status: aggregateStatus(requests.map((request) => request.status)),
+ requests,
+ errors: destinations.flatMap((d) => d.errorInfo?.errorCounts ?? []),
+ warnings: destinations.flatMap((d) => d.warningInfo?.warningCounts ?? []),
+ fieldWarnings,
+ };
+}
+
+async function findRecord({ auth, customerId, query }: { auth: GoogleAdsAuthValue; customerId: string; query: string }): Promise<GoogleAdsRow | null> {
+ try {
+ const page = await search({ auth, customerId, query });
+ return page.results?.[0] ?? null;
+ } catch {
+ return null;
+ }
+}
+
+async function assertContactInfoList({ auth, customerId, userListId }: { auth: GoogleAdsAuthValue; customerId: string; userListId: string }): Promise<void> {
+ const resourceName = `customers/${googleAdsUtils.normalizeCustomerId(customerId)}/userLists/${userListId}`;
+ const page = await search({
+ auth,
+ customerId,
+ query: `SELECT user_list.resource_name, user_list.type, user_list.crm_based_user_list.upload_key_type FROM user_list WHERE user_list.resource_name = '${resourceName}' LIMIT 1`,
+ });
+ const list = page.results?.[0]?.userList;
+ if (list === undefined) {
+ throw new Error(`Audience list ${resourceName} was not found. Pick a list from the dropdown or check the id and the selected customer; nothing was sent.`);
+ }
+ if (list.type !== 'CRM_BASED') {
+ throw new Error(`Audience list ${resourceName} is a ${list.type ?? 'UNKNOWN'} list. Customer Match uploads need a CRM-based list whose upload key type is CONTACT_INFO; nothing was sent.`);
+ }
+ const uploadKeyType = list.crmBasedUserList?.uploadKeyType;
+ if (uploadKeyType !== 'CONTACT_INFO') {
+ throw new Error(
+ `Audience list ${resourceName} expects ${uploadKeyType ?? 'UNKNOWN'} identifiers, but this action only sends contact information (e-mail, phone, address). Pick a CRM-based list whose upload key type is CONTACT_INFO; nothing was sent.`
+ );
+ }
+}
+
+async function waitForRequests({ auth, requestIds }: { auth: GoogleAdsAuthValue; requestIds: string[] }): Promise<GoogleAdsRequestStatusPerDestination[][]> {
+ try {
+ let statuses: GoogleAdsRequestStatusPerDestination[][] = requestIds.map(() => []);
+ for (let attempt = 0; attempt < STATUS_POLLS; attempt++) {
+ await new Promise((resolve) => setTimeout(resolve, STATUS_POLL_INTERVAL_MS));
+ statuses = await Promise.all(
+ requestIds.map(async (requestId) => {
+ const answer = await googleAdsClient.dataManagerRequest<GoogleAdsRequestStatusResponse>({
+ auth,
+ method: HttpMethod.GET,
+ path: `/requestStatus:retrieve?${new URLSearchParams({ requestId }).toString()}`,
+ });
+ return answer.requestStatusPerDestination ?? [];
+ })
+ );
+ if (statuses.every((destinations) => FINAL_STATUSES.has(statusOf(destinations)))) {
+ break;
+ }
+ }
+ return statuses;
+ } catch (error) {
+ const reason = error instanceof Error ? error.message : String(error);
+ throw new Error(
+ `Google accepted requests ${requestIds.join(', ')}, but checking their status failed: ${reason}. The upload itself went through and running this step again would send the members again; ${STATUS_CHECK_HINT} instead.`
+ );
+ }
+}
+
+function statusOf(destinations: GoogleAdsRequestStatusPerDestination[]): string {
+ return aggregateStatus(destinations.map((d) => d.requestStatus ?? 'PROCESSING'));
+}
+
+function aggregateStatus(statuses: string[]): string {
+ if (statuses.length === 0 || statuses.some((s) => !FINAL_STATUSES.has(s))) return 'PROCESSING';
+ if (statuses.every((s) => s === 'SUCCESS')) return 'SUCCESS';
+ if (statuses.every((s) => s === 'FAILED')) return 'FAILED';
+ return 'PARTIAL_SUCCESS';
+}
+
+export const googleAdsApi = {
+ listAccessibleCustomers,
+ search,
+ searchAll,
+ mutateRecord,
+ listCustomerClients,
+ getCustomerInfo,
+ listContactInfoUserLists,
+ listNewestRecords,
+ listRecordsAfterId,
+ listRecordsByResourceNames,
+ listCreateEvents,
+ uploadCustomerMatch,
+};
+
+const MAX_CUSTOMER_CLIENTS = 2000;
+const MAX_USER_LISTS = 2000;
+const MAX_ROWS_PER_POLL = 1000;
+const NAMES_PER_QUERY = 500;
+const MEMBERS_PER_REQUEST = 10_000;
+const STATUS_POLLS = 12;
+const STATUS_POLL_INTERVAL_MS = 10_000;
+const FINAL_STATUSES = new Set(['SUCCESS', 'PARTIAL_SUCCESS', 'FAILED']);
+const TIMESTAMP = /^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}:\d{2}(\.\d{1,6})?)?$/;
+const CONSENT = { GRANTED: 'CONSENT_GRANTED', DENIED: 'CONSENT_DENIED', UNSPECIFIED: 'CONSENT_STATUS_UNSPECIFIED' };
+const STATUS_CHECK_HINT =
+ 'check each request with Custom API Call: method GET, URL https://datamanager.googleapis.com/v1/requestStatus:retrieve?requestId=<request id>';
+
+type SearchParams = { customerId: string; query: string; pageToken?: string };
+
+type MutateRecordParams = { customerId: string; def: GoogleAdsResourceDefinition; operation: GoogleAdsRecordOperation; validateOnly: boolean };
+
+type ListCreateEventsParams = { customerId: string; changeEventType: string; after: string; until: string; order: 'ASC' | 'DESC'; limit: number };
diff --git a/packages/pieces/community/google-ads/src/lib/common/client.ts b/packages/pieces/community/google-ads/src/lib/common/client.ts
new file mode 100644
index 00000000000..82b9f19ab93
--- /dev/null
+++ b/packages/pieces/community/google-ads/src/lib/common/client.ts
@@ -0,0 +1,126 @@
+import { AuthenticationType, HttpError, HttpMethod, httpClient } from '@activepieces/pieces-common';
+
+import type { GoogleAdsAuthValue } from './types';
+
+function baseUrl(): string {
+ return GOOGLE_ADS_API_ROOT;
+}
+
+async function request<T>({ auth, method, path, body }: RequestParams & { auth: GoogleAdsAuthValue }): Promise<T> {
+ const loginCustomerId = auth.props?.loginCustomerId?.trim();
+ try {
+ const response = await httpClient.sendRequest<T>({
+ method,
+ url: `${GOOGLE_ADS_API_ROOT}/${API_VERSION}${path}`,
+ headers: loginCustomerId ? { 'login-customer-id': normalizeLoginCustomerId(loginCustomerId) } : {},
+ authentication: { type: AuthenticationType.BEARER_TOKEN, token: auth.access_token },
+ body,
+ });
+ return response.body;
+ } catch (error) {
+ if (error instanceof HttpError) {
+ throw googleAdsError(error);
+ }
+ throw error;
+ }
+}
+
+async function dataManagerRequest<T>({ auth, method, path, body, timeoutMs }: RequestParams & { auth: GoogleAdsAuthValue; timeoutMs?: number }): Promise<T> {
+ try {
+ const response = await httpClient.sendRequest<T>({
+ method,
+ url: `${DATA_MANAGER_API_ROOT}/v1${path}`,
+ authentication: { type: AuthenticationType.BEARER_TOKEN, token: auth.access_token },
+ body,
+ timeout: timeoutMs ?? DATA_MANAGER_TIMEOUT_MS,
+ });
+ return response.body;
+ } catch (error) {
+ if (error instanceof HttpError) {
+ throw dataManagerError(error);
+ }
+ throw error;
+ }
+}
+
+function normalizeLoginCustomerId(value: string): string {
+ const digits = value.replace(/^customers\//, '').replace(/[-\s]/g, '');
+ if (!/^\d{10}$/.test(digits)) {
+ throw new Error(`Invalid Google Ads customer ID "${value}": expected 10 digits (dashes optional), e.g. 123-456-7890.`);
+ }
+ return digits;
+}
+
+function parseErrorBody(body: unknown): RpcErrorBody {
+ try {
+ const parsed: RpcErrorBody = JSON.parse(typeof body === 'string' ? body : JSON.stringify(body ?? {}));
+ return parsed ?? {};
+ } catch {
+ return {};
+ }
+}
+
+function googleAdsError(error: HttpError): Error {
+ const { status, body } = error.response;
+ const rpcError = parseErrorBody(body).error ?? {};
+ const failure = (rpcError.details ?? []).find((detail) => Array.isArray(detail.errors));
+ const errors = (failure?.errors ?? []).map(describeAdsError);
+ const head = `Google Ads API returned ${status}${rpcError.status ? ` (${rpcError.status})` : ''}`;
+ const detail = errors.length > 0 ? errors.join('; ') : rpcError.message ?? (typeof body === 'string' ? body : JSON.stringify(body ?? null));
+ const requestId = failure?.requestId;
+ const apiError = new Error(`${head}: ${detail}${requestId ? ` [request-id: ${requestId}]` : ''}`);
+ apiError.name = 'GoogleAdsApiError';
+ return apiError;
+}
+
+function describeAdsError(error: AdsErrorDetail): string {
+ const [enumName, value] = Object.entries(error.errorCode ?? {})[0] ?? ['UnknownError', 'UNKNOWN'];
+ const field = (error.location?.fieldPathElements ?? [])
+ .map((p) => (p.index === undefined ? p.fieldName : `${p.fieldName}[${p.index}]`))
+ .filter(Boolean)
+ .join('.');
+ const trigger = error.trigger?.stringValue ?? error.trigger?.int64Value;
+ return `${enumName}.${String(value)}: ${error.message ?? ''}${field ? ` [${field}]` : ''}${trigger ? ` (trigger: ${trigger})` : ''}`;
+}
+
+function dataManagerError(error: HttpError): Error {
+ const { status } = error.response;
+ const rpcError = parseErrorBody(error.response.body).error ?? {};
+ const extras = (rpcError.details ?? []).flatMap((detail) => [
+ ...(detail.fieldViolations ?? []).map((v) => `${v.field ?? '?'}: ${v.description ?? ''}`.trim()),
+ ...(detail.reason ? [`reason: ${detail.reason}`] : []),
+ ]);
+ const head = `Data Manager API returned ${status}${rpcError.status ? ` (${rpcError.status})` : ''}`;
+ const apiError = new Error(`${head}: ${rpcError.message ?? 'no error details'}${extras.length > 0 ? ` [${extras.join('; ')}]` : ''}`);
+ apiError.name = 'DataManagerApiError';
+ return apiError;
+}
+
+export const googleAdsClient = { baseUrl, request, dataManagerRequest };
+
+const API_VERSION = 'v25';
+const GOOGLE_ADS_API_ROOT = 'https://googleads.googleapis.com';
+const DATA_MANAGER_API_ROOT = 'https://datamanager.googleapis.com';
+const DATA_MANAGER_TIMEOUT_MS = 60_000;
+
+type RequestParams = { method: HttpMethod; path: string; body?: unknown };
+
+type AdsErrorDetail = {
+ errorCode?: Record<string, string>;
+ message?: string;
+ location?: { fieldPathElements?: { fieldName?: string; index?: number }[] };
+ trigger?: { stringValue?: string; int64Value?: string };
+};
+
+type RpcErrorBody = {
+ error?: {
+ status?: string;
+ message?: string;
+ details?: {
+ errors?: AdsErrorDetail[];
+ requestId?: string;
+ fieldViolations?: { field?: string; description?: string }[];
+ reason?: string;
+ }[];
+ };
+};
diff --git a/packages/pieces/community/google-ads/src/lib/common/props.ts b/packages/pieces/community/google-ads/src/lib/common/props.ts
new file mode 100644
index 00000000000..8d0a3cea17b
--- /dev/null
+++ b/packages/pieces/community/google-ads/src/lib/common/props.ts
@@ -0,0 +1,181 @@
+import { Property } from '@activepieces/pieces-framework';
+import type { DropdownState } from '@activepieces/pieces-framework';
+
+import { googleAdsAuth } from '../auth';
+import { googleAdsApi } from './api';
+import type { GoogleAdsAuthValue, GoogleAdsCustomerInfo } from './types';
+import { googleAdsUtils } from './utils';
+
+function customerId<R extends boolean>({
+ required,
+ displayName = 'Customer',
+ description = 'Google Ads account to operate on. Accounts reached through a manager need the manager ID in the connection.',
+}: PropParams<R>) {
+ return Property.Dropdown({
+ auth: googleAdsAuth,
+ displayName,
+ description,
+ required,
+ refreshers: [],
+ options: async ({ auth }) => await customerOptions({ auth }),
+ });
+}
+
+function userList<R extends boolean>({
+ required,
+ displayName = 'Audience List',
+ description = 'CRM-based audience list (Customer Match) the members go to.',
+}: PropParams<R>) {
+ return Property.Dropdown({
+ auth: googleAdsAuth,
+ displayName,
+ description,
+ required,
+ refreshers: ['customerId'],
+ options: async ({ auth, customerId }) => {
+ if (!auth?.access_token) {
+ return disabledOptions({ placeholder: 'Please select an existing or create a new connection.' });
+ }
+ if (typeof customerId !== 'string' || customerId === '') {
+ return disabledOptions({ placeholder: 'Please select a customer.' });
+ }
+ try {
+ const { results, truncated } = await googleAdsApi.listContactInfoUserLists({ auth, customerId });
+ const options = results.map((row) => ({ label: row.userList?.name ?? '', value: row.userList?.resourceName ?? '' }));
+ if (options.length === 0) {
+ return disabledOptions({
+ placeholder: 'No CRM-based audience list with upload key type CONTACT_INFO in this account. Create one first (Create Record, Audience list).',
+ });
+ }
+ return {
+ disabled: false,
+ options,
+ ...(truncated
+ ? {
+ placeholder: `Showing the first ${options.length} CRM-based contact info audience lists. If yours is not listed, enter its resource name (e.g. customers/1234567890/userLists/55) or numeric id as a custom value.`,
+ }
+ : {}),
+ };
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return disabledOptions({ placeholder: `An error occurred while listing the audience lists: ${detail.slice(0, 300)}` });
+ }
+ },
+ });
+}
+
+function resourceType<R extends boolean>({
+ required,
+ displayName = 'Resource Type',
+ description = 'Which kind of record: campaign, ad group, ad, keyword or audience list.',
+}: PropParams<R>) {
+ return Property.StaticDropdown<string, R>({
+ displayName,
+ description,
+ required,
+ options: { options: googleAdsUtils.resources.map((def) => ({ label: def.label, value: def.type })) },
+ });
+}
+
+function validateOnly<R extends boolean>({
+ required,
+ displayName = 'Validate Only',
+ description = 'Ask Google to validate the request without applying it. Nothing is created, changed or removed.',
+}: PropParams<R>) {
+ return Property.Checkbox({ displayName, description, required, defaultValue: false });
+}
+
+function identifier<R extends boolean>({
+ required,
+ displayName = 'Record ID or Resource Name',
+ description = 'Numeric id for campaigns, ad groups and audience lists; `<adGroupId>~<adId>` for ads; `<adGroupId>~<criterionId>` for keywords. A full resource name (`customers/…/campaigns/…`) also works.',
+}: PropParams<R>) {
+ return Property.ShortText({ displayName, description, required });
+}
+
+function members({
+ required,
+ displayName = 'Members',
+ description = 'One entry per person. Fill any of: e-mail, phone (E.164, e.g. +5511999999999), or the full address set (first name, last name, country code, postal code). E-mail, phone, first name and last name are normalized and SHA-256 hashed before upload; country code and postal code are sent unhashed (trimmed, country code uppercased), as Google requires.',
+}: PropParams<true>) {
+ return Property.Array({
+ displayName,
+ description,
+ required,
+ properties: {
+ email: Property.ShortText({ displayName: 'E-mail', required: false }),
+ phone: Property.ShortText({ displayName: 'Phone', required: false }),
+ firstName: Property.ShortText({ displayName: 'First Name', required: false }),
+ lastName: Property.ShortText({ displayName: 'Last Name', required: false }),
+ countryCode: Property.ShortText({ displayName: 'Country Code', description: 'ISO 3166-1 alpha-2, e.g. BR', required: false }),
+ postalCode: Property.ShortText({ displayName: 'Postal Code', required: false }),
+ },
+ });
+}
+
+function waitForCompletion<R extends boolean>({
+ required,
+ displayName = 'Wait for Processing',
+ description = 'Poll the request status for up to ~2 minutes. Matching usually takes longer, so this is off by default: the output carries the request ids to check later.',
+}: PropParams<R>) {
+ return Property.Checkbox({ displayName, description, required, defaultValue: false });
+}
+
+async function customerOptions({ auth }: { auth: GoogleAdsAuthValue | undefined }): Promise<DropdownState<string>> {
+ if (!auth?.access_token) {
+ return disabledOptions({ placeholder: 'Please select an existing or create a new connection.' });
+ }
+ try {
+ const loginCustomerId = auth.props?.loginCustomerId?.trim();
+ if (loginCustomerId) {
+ const { clients, truncated } = await googleAdsApi.listCustomerClients({ auth, managerId: googleAdsUtils.normalizeCustomerId(loginCustomerId) });
+ if (clients.length === 0) {
+ return disabledOptions({ placeholder: 'The manager account has no client accounts.' });
+ }
+ return {
+ disabled: false,
+ options: clients.map((c) => ({ label: labelFor(c), value: c.id })),
+ ...(truncated
+ ? { placeholder: `Showing the first ${clients.length} accounts under the manager. If yours is not listed, enter its customer ID (e.g. 123-456-7890) as a custom value.` }
+ : {}),
+ };
+ }
+ const ids = await googleAdsApi.listAccessibleCustomers({ auth });
+ if (ids.length === 0) {
+ return disabledOptions({ placeholder: 'This Google account has no accessible Google Ads customers.' });
+ }
+ const lookups = await Promise.allSettled(ids.slice(0, MAX_LABEL_LOOKUPS).map((id) => googleAdsApi.getCustomerInfo({ auth, customerId: id })));
+ const options = ids
+ .map((id, index) => {
+ const lookup = lookups[index];
+ return { label: labelFor(lookup?.status === 'fulfilled' ? lookup.value : { id }), value: id };
+ })
+ .sort((a, b) => a.label.localeCompare(b.label));
+ return { disabled: false, options };
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return disabledOptions({ placeholder: `An error occurred while listing the accessible Google Ads customers: ${detail.slice(0, 300)}` });
+ }
+}
+
+function labelFor(info: GoogleAdsCustomerInfo): string {
+ const flags = [
+ info.manager ? 'manager' : '',
+ info.testAccount ? 'test' : '',
+ info.status && info.status !== 'ENABLED' ? info.status.toLowerCase() : '',
+ ]
+ .filter(Boolean)
+ .join(', ');
+ const name = info.descriptiveName ? `${info.descriptiveName}${flags ? ` (${flags})` : ''} · ` : '';
+ return `${name}${googleAdsUtils.formatCustomerId(info.id)}`;
+}
+
+function disabledOptions({ placeholder }: { placeholder: string }): DropdownState<never> {
+ return { disabled: true, options: [], placeholder };
+}
+
+export const googleAdsProps = { customerId, userList, resourceType, validateOnly, identifier, members, waitForCompletion };
+
+const MAX_LABEL_LOOKUPS = 25;
+
+export type PropParams<R extends boolean> = { required: R; displayName?: string; description?: string };
diff --git a/packages/pieces/community/google-ads/src/lib/common/types.ts b/packages/pieces/community/google-ads/src/lib/common/types.ts
new file mode 100644
index 00000000000..c2b5ccbf85e
--- /dev/null
+++ b/packages/pieces/community/google-ads/src/lib/common/types.ts
@@ -0,0 +1,180 @@
+export type GoogleAdsAuthValue = {
+ access_token: string;
+ props?: { loginCustomerId?: string | undefined } | undefined;
+};
+
+export type GoogleAdsEntity = {
+ resourceName?: string;
+ id?: string;
+ name?: string;
+ status?: string;
+ type?: string;
+};
+
+export type GoogleAdsCustomer = {
+ id?: string;
+ descriptiveName?: string;
+ manager?: boolean;
+ testAccount?: boolean;
+ status?: string;
+};
+
+export type GoogleAdsChangeEvent = {
+ resourceName?: string;
+ changeDateTime?: string;
+ changeResourceName?: string;
+};
+
+export type GoogleAdsRow = {
+ campaign?: GoogleAdsEntity;
+ adGroup?: GoogleAdsEntity;
+ adGroupAd?: GoogleAdsEntity & { ad?: GoogleAdsEntity };
+ adGroupCriterion?: GoogleAdsEntity & { criterionId?: string };
+ userList?: GoogleAdsEntity & { crmBasedUserList?: { uploadKeyType?: string } };
+ customer?: GoogleAdsCustomer;
+ customerClient?: GoogleAdsCustomer;
+ changeEvent?: GoogleAdsChangeEvent;
+ [key: string]: unknown;
+};
+
+export type GoogleAdsSearchPage = {
+ results?: GoogleAdsRow[];
+ nextPageToken?: string;
+};
+
+export type GoogleAdsSearchAllResult = { results: GoogleAdsRow[]; truncated: boolean };
+
+export type GoogleAdsMutateResponse = {
+ mutateOperationResponses?: Record<string, ({ resourceName?: string } & Record<string, unknown>) | undefined>[];
+};
+
+export type GoogleAdsCustomerInfo = {
+ id: string;
+ descriptiveName?: string;
+ manager?: boolean;
+ testAccount?: boolean;
+ status?: string;
+};
+
+export type GoogleAdsResourceType = 'campaign' | 'ad_group' | 'ad_group_ad' | 'ad_group_criterion' | 'user_list';
+
+export type GoogleAdsResourceDefinition = {
+ type: GoogleAdsResourceType;
+ label: string;
+ operationKey: string;
+ resultKey: string;
+ collection: string;
+ idField: string;
+ fields: string[];
+ kind?: { field: string; value: string };
+ statusField?: string;
+ compositeIdHint?: string;
+ changeEventType?: string;
+ createExample: Record<string, unknown>;
+ read: (row: GoogleAdsRow) => GoogleAdsEntity | undefined;
+};
+
+export type GoogleAdsRecordOperation =
+ | { create: Record<string, unknown> }
+ | { update: Record<string, unknown>; updateMask: string }
+ | { remove: string };
+
+export type GoogleAdsRecordMutationResult = {
+ resourceType: string;
+ resourceName: string | null;
+ id: string | null;
+ record: Record<string, unknown> | null;
+ validateOnly: boolean;
+};
+
+export type GoogleAdsReportResource = 'customer' | 'campaign' | 'ad_group' | 'ad_group_ad' | 'keyword_view' | 'search_term_view';
+
+export type GoogleAdsDateRangePreset =
+ | 'TODAY'
+ | 'YESTERDAY'
+ | 'LAST_7_DAYS'
+ | 'LAST_14_DAYS'
+ | 'LAST_30_DAYS'
+ | 'THIS_WEEK_SUN_TODAY'
+ | 'THIS_WEEK_MON_TODAY'
+ | 'LAST_WEEK_SUN_SAT'
+ | 'LAST_WEEK_MON_SUN'
+ | 'THIS_MONTH'
+ | 'LAST_MONTH'
+ | 'LAST_BUSINESS_WEEK'
+ | 'CUSTOM'
+ | 'ALL_TIME';
+
+export type GoogleAdsReportSpec = {
+ resource: GoogleAdsReportResource;
+ fields?: string[];
+ metrics?: string[];
+ dateRange?: GoogleAdsDateRangePreset;
+ startDate?: string;
+ endDate?: string;
+ segmentByDate?: boolean;
+ where?: string;
+ orderBy?: string;
+};
+
+export type GoogleAdsMemberInput = {
+ email?: string;
+ phone?: string;
+ firstName?: string;
+ lastName?: string;
+ countryCode?: string;
+ postalCode?: string;
+};
+
+export type GoogleAdsUserIdentifier =
+ | { emailAddress: string }
+ | { phoneNumber: string }
+ | { address: { givenName: string; familyName: string; regionCode: string; postalCode: string } };
+
+export type GoogleAdsAudienceMember = { userData: { userIdentifiers: GoogleAdsUserIdentifier[] } };
+
+export type GoogleAdsConsentStatus = 'GRANTED' | 'DENIED' | 'UNSPECIFIED';
+
+export type GoogleAdsDestination = {
+ operatingAccount: { accountType: 'GOOGLE_ADS'; accountId: string };
+ loginAccount?: { accountType: 'GOOGLE_ADS'; accountId: string };
+ productDestinationId: string;
+};
+
+export type GoogleAdsFieldWarning = { reason?: string; description?: string; field?: string };
+
+export type GoogleAdsIngestResponse = { requestId?: string; fieldWarnings?: GoogleAdsFieldWarning[] };
+
+export type GoogleAdsReasonCount = { recordCount?: string; reason?: string };
+
+export type GoogleAdsRequestStatusPerDestination = {
+ requestStatus?: string;
+ errorInfo?: { errorCounts?: GoogleAdsReasonCount[] };
+ warningInfo?: { warningCounts?: GoogleAdsReasonCount[] };
+ audienceMembersIngestionStatus?: { userDataIngestionStatus?: { uploadMatchRateRange?: string } };
+};
+
+export type GoogleAdsRequestStatusResponse = { requestStatusPerDestination?: GoogleAdsRequestStatusPerDestination[] };
+
+export type GoogleAdsCustomerMatchRequest = { requestId: string; status: string; matchRateRange?: string };
+
+export type GoogleAdsCustomerMatchResult = {
+ requestIds: string[];
+ userList: string;
+ userListId: string;
+ mode: 'add' | 'remove';
+ members: number;
+ identifiers: number;
+ status: string;
+ requests: GoogleAdsCustomerMatchRequest[];
+ errors: GoogleAdsReasonCount[];
+ warnings: GoogleAdsReasonCount[];
+ fieldWarnings: GoogleAdsFieldWarning[];
+};
+
+export type GoogleAdsUploadParams = {
+ customerId: string;
+ userList: string;
+ members: GoogleAdsMemberInput[];
+ waitForCompletion: boolean;
+} & ({ mode: 'add'; consent: { adUserData: GoogleAdsConsentStatus; adPersonalization: GoogleAdsConsentStatus } } | { mode: 'remove' });
diff --git a/packages/pieces/community/google-ads/src/lib/common/utils.ts b/packages/pieces/community/google-ads/src/lib/common/utils.ts
new file mode 100644
index 00000000000..7d05253c6bd
--- /dev/null
+++ b/packages/pieces/community/google-ads/src/lib/common/utils.ts
@@ -0,0 +1,534 @@
+import { createHash } from 'node:crypto';
+
+import type {
+ GoogleAdsAudienceMember,
+ GoogleAdsDateRangePreset,
+ GoogleAdsMemberInput,
+ GoogleAdsRecordOperation,
+ GoogleAdsReportResource,
+ GoogleAdsReportSpec,
+ GoogleAdsResourceDefinition,
+ GoogleAdsResourceType,
+ GoogleAdsUserIdentifier,
+} from './types';
+
+function normalizeCustomerId(value: string): string {
+ const digits = String(value ?? '')
+ .trim()
+ .replace(/^customers\//, '')
+ .replace(/[-\s]/g, '');
+ if (!/^\d{10}$/.test(digits)) {
+ throw new Error(`Invalid Google Ads customer ID "${value}": expected 10 digits (dashes optional), e.g. 123-456-7890.`);
+ }
+ return digits;
+}
+
+function assertGaql(query: string): string {
+ const trimmed = String(query ?? '').trim();
+ if (!/^select\s/i.test(trimmed)) {
+ throw new Error('The query must be a GAQL SELECT statement, e.g. "SELECT campaign.id, campaign.name FROM campaign".');
+ }
+ return trimmed;
+}
+
+function resourceDefinition(type: string): GoogleAdsResourceDefinition {
+ const def = RESOURCES.find((resource) => resource.type === type);
+ if (def === undefined) {
+ throw new Error(`Unknown resource type "${type}". Expected one of: ${RESOURCES.map((r) => r.type).join(', ')}.`);
+ }
+ return def;
+}
+
+function resourceNameFor({ def, customerId, identifier }: { def: GoogleAdsResourceDefinition; customerId: string; identifier: string }): string {
+ const value = String(identifier ?? '').trim();
+ const idPattern = def.compositeIdHint ? COMPOSITE_ID : SIMPLE_ID;
+ if (value.startsWith('customers/')) {
+ const match = RESOURCE_NAME.exec(value);
+ if (match === null || match[2] !== def.collection || !idPattern.test(match[3])) {
+ throw new Error(`"${value}" is not a ${def.label.toLowerCase()} resource name (expected customers/<customerId>/${def.collection}/${def.compositeIdHint ?? '<id>'}).`);
+ }
+ if (match[1] !== customerId) {
+ throw new Error(
+ `${def.label} ${value} belongs to customer ${match[1]}, but the selected customer is ${customerId}. Select customer ${match[1]} or use a ${def.label.toLowerCase()} of customer ${customerId}.`
+ );
+ }
+ return value;
+ }
+ if (!idPattern.test(value)) {
+ throw new Error(
+ def.compositeIdHint
+ ? `${def.label} ids look like ${def.compositeIdHint} (e.g. 987654321~112233445566); got "${value}".`
+ : `${def.label} id must be numeric or a full resource name; got "${value}".`
+ );
+ }
+ return `customers/${customerId}/${def.collection}/${value}`;
+}
+
+function idFromResourceName(resourceName: string | undefined): string | null {
+ const last = resourceName?.split('/').pop();
+ return last ? last : null;
+}
+
+function updateMaskFor(record: Record<string, unknown>): string {
+ const paths = Object.entries(record)
+ .filter(([key]) => key !== 'resourceName')
+ .flatMap(([key, child]) => leafPaths({ value: child, path: key }));
+ if (paths.length === 0) {
+ throw new Error('Nothing to update: the record has no fields besides resourceName.');
+ }
+ return paths.join(',');
+}
+
+function buildOperation({ def, operation }: { def: GoogleAdsResourceDefinition; operation: GoogleAdsRecordOperation }): Record<string, unknown> {
+ return { [def.operationKey]: operation };
+}
+
+function newestRecordsQuery({ def, limit }: { def: GoogleAdsResourceDefinition; limit: number }): string {
+ const conditions = [kindFilter(def), def.statusField ? `${def.statusField} != 'REMOVED'` : undefined].filter(Boolean);
+ const where = conditions.length > 0 ? ` WHERE ${conditions.join(' AND ')}` : '';
+ return `SELECT ${def.fields.join(', ')} FROM ${def.type}${where} ORDER BY ${def.idField} DESC LIMIT ${limit}`;
+}
+
+function recordsAfterIdQuery({ def, afterId }: { def: GoogleAdsResourceDefinition; afterId: string }): string {
+ if (!/^\d+$/.test(afterId)) {
+ throw new Error(`Invalid checkpoint id "${afterId}": expected a numeric Google Ads id.`);
+ }
+ const conditions = [kindFilter(def), def.statusField ? `${def.statusField} != 'REMOVED'` : undefined, `${def.idField} > ${afterId}`].filter(Boolean);
+ return `SELECT ${def.fields.join(', ')} FROM ${def.type} WHERE ${conditions.join(' AND ')} ORDER BY ${def.idField} ASC`;
+}
+
+function recordsByResourceNamesQuery({ def, resourceNames }: { def: GoogleAdsResourceDefinition; resourceNames: string[] }): string {
+ const pattern = new RegExp(`^customers/\\d+/${def.collection}/\\d+(~\\d+)?$`);
+ const invalid = resourceNames.find((name) => !pattern.test(name));
+ if (invalid !== undefined) {
+ throw new Error(`"${invalid}" is not a ${def.label.toLowerCase()} resource name.`);
+ }
+ const fields = def.kind === undefined || def.fields.includes(def.kind.field) ? def.fields : [...def.fields, def.kind.field];
+ return `SELECT ${fields.join(', ')} FROM ${def.type} WHERE ${def.type}.resource_name IN (${resourceNames.map((name) => `'${name}'`).join(', ')})`;
+}
+
+function recordByResourceNameQuery({ def, resourceName }: { def: GoogleAdsResourceDefinition; resourceName: string }): string {
+ return `SELECT ${def.fields.join(', ')} FROM ${def.type} WHERE ${def.type}.resource_name = '${resourceName}' LIMIT 1`;
+}
+
+function buildReportQuery(spec: GoogleAdsReportSpec): string {
+ const resource = REPORT_RESOURCES[spec.resource];
+ if (!resource) {
+ throw new Error(`Unknown report resource "${spec.resource}". Expected one of: ${Object.keys(REPORT_RESOURCES).join(', ')}.`);
+ }
+ const fields = clean(spec.fields);
+ const metrics = clean(spec.metrics);
+ const select = [
+ ...(fields.length > 0 ? fields : resource.entityFields),
+ ...(spec.segmentByDate ? ['segments.date'] : []),
+ ...(metrics.length > 0 ? metrics : DEFAULT_METRICS),
+ ];
+ const unique = select.filter((f, i) => select.indexOf(f) === i);
+ const conditions = [dateCondition(spec), spec.where?.trim() || null].filter((c): c is string => Boolean(c));
+ const where = conditions.length > 0 ? ` WHERE ${conditions.join(' AND ')}` : '';
+ const orderBy = spec.orderBy?.trim() ? ` ORDER BY ${spec.orderBy.trim()}` : '';
+ return `SELECT ${unique.join(', ')} FROM ${spec.resource}${where}${orderBy}`;
+}
+
+function flattenRow(row: Record<string, unknown>, prefix = ''): Record<string, unknown> {
+ return Object.fromEntries(
+ Object.entries(row).flatMap(([key, value]) => {
+ const path = prefix ? `${prefix}.${snake(key)}` : snake(key);
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+ ? Object.entries(flattenRow(Object.fromEntries(Object.entries(value)), path))
+ : [[path, value]];
+ })
+ );
+}
+
+function sha256(value: string): string {
+ return createHash('sha256').update(value, 'utf8').digest('hex');
+}
+
+function normalizeEmail(email: string): string {
+ const value = email.trim().toLowerCase();
+ const at = value.lastIndexOf('@');
+ if (at <= 0) {
+ throw new Error(`"${email}" is not an e-mail address.`);
+ }
+ const user = value.slice(0, at);
+ const domain = value.slice(at + 1);
+ const isGmail = domain === 'gmail.com' || domain === 'googlemail.com';
+ return `${isGmail ? user.replace(/\./g, '') : user}@${domain}`;
+}
+
+function normalizePhone(phone: string): string {
+ const digits = phone.replace(/[^\d]/g, '');
+ if (digits.length < 8) {
+ throw new Error(`"${phone}" is not a phone number in E.164 form (country code + number, e.g. +5511999999999).`);
+ }
+ return `+${digits}`;
+}
+
+function normalizeName(name: string): string {
+ return name
+ .toLowerCase()
+ .replace(/[^\p{L}\p{N}\s]/gu, '')
+ .replace(/\s+/g, ' ')
+ .trim();
+}
+
+function identifiersFor(member: GoogleAdsMemberInput): GoogleAdsUserIdentifier[] {
+ const email: GoogleAdsUserIdentifier[] = member.email?.trim() ? [{ emailAddress: sha256(normalizeEmail(member.email)) }] : [];
+ const phone: GoogleAdsUserIdentifier[] = member.phone?.trim() ? [{ phoneNumber: sha256(normalizePhone(member.phone)) }] : [];
+ return [...email, ...phone, ...addressIdentifiers(member)];
+}
+
+function buildMemberBatches({ members, limit }: { members: GoogleAdsMemberInput[]; limit: number }): { batches: GoogleAdsAudienceMember[][]; identifiers: number } {
+ if (!Array.isArray(members) || members.length === 0) {
+ throw new Error('At least one member is required.');
+ }
+ const payloads = members.map((member, index) => {
+ const userIdentifiers = identifiersFor(member ?? {});
+ if (userIdentifiers.length === 0) {
+ throw new Error(`Member #${index + 1} has no identifier (e-mail, phone or full address).`);
+ }
+ return { userData: { userIdentifiers } };
+ });
+ const identifiers = payloads.reduce((total, payload) => total + payload.userData.userIdentifiers.length, 0);
+ const batches = Array.from({ length: Math.ceil(payloads.length / limit) }, (_, batch) => payloads.slice(batch * limit, batch * limit + limit));
+ return { batches, identifiers };
+}
+
+function toMemberInput(value: unknown): GoogleAdsMemberInput {
+ if (typeof value !== 'object' || value === null) {
+ return {};
+ }
+ const fields: Record<string, unknown> = Object.fromEntries(Object.entries(value));
+ const text = (key: string): string | undefined => {
+ const field = fields[key];
+ return typeof field === 'string' ? field : undefined;
+ };
+ return {
+ email: text('email'),
+ phone: text('phone'),
+ firstName: text('firstName'),
+ lastName: text('lastName'),
+ countryCode: text('countryCode'),
+ postalCode: text('postalCode'),
+ };
+}
+
+function userListIdFrom({ userList, customerId }: { userList: string; customerId: string }): string {
+ const value = String(userList ?? '').trim();
+ if (/^\d+$/.test(value)) {
+ return value;
+ }
+ const match = /^customers\/(\d+)\/userLists\/(\d+)$/.exec(value);
+ if (!match) {
+ throw new Error(`"${value}" is not a user list id or resource name. Use a numeric user list id or a resource name like customers/1234567890/userLists/55.`);
+ }
+ const [, listCustomerId, id] = match;
+ const selectedCustomerId = normalizeCustomerId(customerId);
+ if (listCustomerId !== selectedCustomerId) {
+ throw new Error(
+ `Audience list ${value} belongs to customer ${listCustomerId}, but the selected customer is ${selectedCustomerId}. Select customer ${listCustomerId} or pick an audience list of customer ${selectedCustomerId}.`
+ );
+ }
+ return id;
+}
+
+function assertAllowedUrl(url: unknown): void {
+ if (typeof url !== 'string' || !(url.startsWith('http://') || url.startsWith('https://'))) {
+ return;
+ }
+ if (!ALLOWED_ORIGINS.includes(originOf(url) ?? '')) {
+ throw new Error(
+ `Custom API Call only sends your Google Ads credentials to ${ALLOWED_ORIGINS.join(' or ')}; got "${url}". Use a path relative to ${ALLOWED_ORIGINS[0]} (e.g. /v25/customers/1234567890/googleAds:search) or a full URL on one of those hosts.`
+ );
+ }
+}
+
+function originOf(url: string): string | null {
+ try {
+ const parsed = new URL(url);
+ return parsed.username || parsed.password ? null : parsed.origin;
+ } catch {
+ return null;
+ }
+}
+
+function formatCustomerId(id: string): string {
+ return id.replace(/^(\d{3})(\d{3})(\d{4})$/, '$1-$2-$3');
+}
+
+function addressIdentifiers(member: GoogleAdsMemberInput): GoogleAdsUserIdentifier[] {
+ const parts = {
+ firstName: member.firstName?.trim() ?? '',
+ lastName: member.lastName?.trim() ?? '',
+ countryCode: member.countryCode?.trim() ?? '',
+ postalCode: member.postalCode?.trim() ?? '',
+ };
+ if (Object.values(parts).every((part) => part === '')) {
+ return [];
+ }
+ const missing = Object.entries(parts)
+ .filter(([, part]) => part === '')
+ .map(([key]) => key);
+ if (missing.length > 0) {
+ throw new Error(`Address identifiers need first name, last name, country code and postal code together (missing: ${missing.join(', ')}).`);
+ }
+ return [
+ {
+ address: {
+ givenName: sha256(normalizeName(parts.firstName)),
+ familyName: sha256(normalizeName(parts.lastName)),
+ regionCode: parts.countryCode.toUpperCase(),
+ postalCode: parts.postalCode,
+ },
+ },
+ ];
+}
+
+function leafPaths({ value, path }: { value: unknown; path: string }): string[] {
+ if (typeof value === 'object' && value !== null && !Array.isArray(value) && Object.keys(value).length > 0) {
+ return Object.entries(value).flatMap(([key, child]) => leafPaths({ value: child, path: `${path}.${key}` }));
+ }
+ return [path];
+}
+
+function kindFilter(def: GoogleAdsResourceDefinition): string | undefined {
+ return def.kind === undefined ? undefined : `${def.kind.field} = '${def.kind.value}'`;
+}
+
+function dateCondition(spec: GoogleAdsReportSpec): string | null {
+ const range = spec.dateRange ?? 'LAST_30_DAYS';
+ if (range === 'ALL_TIME') return null;
+ if (range === 'CUSTOM') {
+ if (!spec.startDate || !spec.endDate || !DATE.test(spec.startDate) || !DATE.test(spec.endDate)) {
+ throw new Error('A custom date range needs Start Date and End Date as YYYY-MM-DD.');
+ }
+ return `segments.date BETWEEN '${spec.startDate}' AND '${spec.endDate}'`;
+ }
+ if (!DATE_RANGE_PRESETS.includes(range)) {
+ throw new Error(`Unknown date range "${range}".`);
+ }
+ return `segments.date DURING ${range}`;
+}
+
+function clean(values: string[] | undefined): string[] {
+ return (values ?? []).map((v) => String(v).trim()).filter((v) => v.length > 0);
+}
+
+function snake(segment: string): string {
+ return segment.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
+}
+
+const ALLOWED_ORIGINS = ['https://googleads.googleapis.com', 'https://datamanager.googleapis.com'];
+const CID = 'customers/1234567890';
+const RESOURCE_NAME = /^customers\/(\d+)\/([A-Za-z]+)\/([^/]+)$/;
+const SIMPLE_ID = /^\d+$/;
+const COMPOSITE_ID = /^\d+~\d+$/;
+const DATE = /^\d{4}-\d{2}-\d{2}$/;
+
+const RESOURCES: GoogleAdsResourceDefinition[] = [
+ {
+ type: 'campaign',
+ label: 'Campaign',
+ operationKey: 'campaignOperation',
+ resultKey: 'campaignResult',
+ collection: 'campaigns',
+ idField: 'campaign.id',
+ statusField: 'campaign.status',
+ fields: [
+ 'campaign.id',
+ 'campaign.name',
+ 'campaign.status',
+ 'campaign.advertising_channel_type',
+ 'campaign.bidding_strategy_type',
+ 'campaign.campaign_budget',
+ 'campaign.start_date_time',
+ 'campaign.end_date_time',
+ 'campaign.resource_name',
+ ],
+ createExample: {
+ name: 'Spring sale',
+ status: 'PAUSED',
+ advertisingChannelType: 'SEARCH',
+ campaignBudget: `${CID}/campaignBudgets/1122334455`,
+ manualCpc: {},
+ networkSettings: { targetGoogleSearch: true, targetSearchNetwork: true },
+ containsEuPoliticalAdvertising: 'DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING',
+ },
+ read: (row) => row.campaign,
+ },
+ {
+ type: 'ad_group',
+ label: 'Ad group',
+ operationKey: 'adGroupOperation',
+ resultKey: 'adGroupResult',
+ collection: 'adGroups',
+ idField: 'ad_group.id',
+ statusField: 'ad_group.status',
+ fields: ['ad_group.id', 'ad_group.name', 'ad_group.status', 'ad_group.type', 'ad_group.campaign', 'ad_group.cpc_bid_micros', 'ad_group.resource_name'],
+ createExample: {
+ name: 'Running shoes',
+ status: 'ENABLED',
+ type: 'SEARCH_STANDARD',
+ campaign: `${CID}/campaigns/123456789`,
+ cpcBidMicros: '1000000',
+ },
+ read: (row) => row.adGroup,
+ },
+ {
+ type: 'ad_group_ad',
+ label: 'Ad',
+ operationKey: 'adGroupAdOperation',
+ resultKey: 'adGroupAdResult',
+ collection: 'adGroupAds',
+ idField: 'ad_group_ad.ad.id',
+ statusField: 'ad_group_ad.status',
+ fields: [
+ 'ad_group_ad.ad.id',
+ 'ad_group_ad.ad.name',
+ 'ad_group_ad.ad.type',
+ 'ad_group_ad.ad.final_urls',
+ 'ad_group_ad.status',
+ 'ad_group_ad.ad_group',
+ 'ad_group_ad.resource_name',
+ ],
+ compositeIdHint: '<adGroupId>~<adId>',
+ changeEventType: 'AD_GROUP_AD',
+ createExample: {
+ adGroup: `${CID}/adGroups/987654321`,
+ status: 'PAUSED',
+ ad: {
+ finalUrls: ['https://www.example.com/shoes'],
+ responsiveSearchAd: {
+ headlines: [{ text: 'Running shoes' }, { text: 'Free shipping' }, { text: 'Shop today' }],
+ descriptions: [{ text: 'Lightweight shoes for every runner.' }, { text: 'Order now and run tomorrow.' }],
+ },
+ },
+ },
+ read: (row) => (row.adGroupAd ? { ...row.adGroupAd, id: row.adGroupAd.ad?.id } : undefined),
+ },
+ {
+ type: 'ad_group_criterion',
+ label: 'Keyword',
+ operationKey: 'adGroupCriterionOperation',
+ resultKey: 'adGroupCriterionResult',
+ collection: 'adGroupCriteria',
+ idField: 'ad_group_criterion.criterion_id',
+ statusField: 'ad_group_criterion.status',
+ fields: [
+ 'ad_group_criterion.criterion_id',
+ 'ad_group_criterion.keyword.text',
+ 'ad_group_criterion.keyword.match_type',
+ 'ad_group_criterion.status',
+ 'ad_group_criterion.ad_group',
+ 'ad_group_criterion.resource_name',
+ ],
+ kind: { field: 'ad_group_criterion.type', value: 'KEYWORD' },
+ compositeIdHint: '<adGroupId>~<criterionId>',
+ changeEventType: 'AD_GROUP_CRITERION',
+ createExample: {
+ adGroup: `${CID}/adGroups/987654321`,
+ status: 'ENABLED',
+ keyword: { text: 'running shoes', matchType: 'PHRASE' },
+ },
+ read: (row) => (row.adGroupCriterion ? { ...row.adGroupCriterion, id: row.adGroupCriterion.criterionId } : undefined),
+ },
+ {
+ type: 'user_list',
+ label: 'Audience list',
+ operationKey: 'userListOperation',
+ resultKey: 'userListResult',
+ collection: 'userLists',
+ idField: 'user_list.id',
+ fields: [
+ 'user_list.id',
+ 'user_list.name',
+ 'user_list.description',
+ 'user_list.type',
+ 'user_list.membership_status',
+ 'user_list.size_for_display',
+ 'user_list.size_for_search',
+ 'user_list.resource_name',
+ ],
+ createExample: {
+ name: 'Newsletter subscribers',
+ description: 'Customers who opted in to the newsletter',
+ membershipLifeSpan: '30',
+ crmBasedUserList: { uploadKeyType: 'CONTACT_INFO' },
+ },
+ read: (row) => row.userList,
+ },
+];
+
+const REPORT_RESOURCES: Record<GoogleAdsReportResource, { label: string; entityFields: string[] }> = {
+ customer: { label: 'Account', entityFields: ['customer.id', 'customer.descriptive_name'] },
+ campaign: { label: 'Campaign', entityFields: ['campaign.id', 'campaign.name', 'campaign.status'] },
+ ad_group: { label: 'Ad group', entityFields: ['ad_group.id', 'ad_group.name', 'ad_group.status', 'campaign.name'] },
+ ad_group_ad: { label: 'Ad', entityFields: ['ad_group_ad.ad.id', 'ad_group_ad.ad.type', 'ad_group_ad.status', 'ad_group.name'] },
+ keyword_view: {
+ label: 'Keyword',
+ entityFields: ['ad_group_criterion.criterion_id', 'ad_group_criterion.keyword.text', 'ad_group_criterion.keyword.match_type', 'ad_group.name'],
+ },
+ search_term_view: { label: 'Search term', entityFields: ['search_term_view.search_term', 'ad_group.name', 'campaign.name'] },
+};
+
+const REPORT_RESOURCE_TYPES: GoogleAdsReportResource[] = ['customer', 'campaign', 'ad_group', 'ad_group_ad', 'keyword_view', 'search_term_view'];
+
+const DEFAULT_METRICS = [
+ 'metrics.impressions',
+ 'metrics.clicks',
+ 'metrics.ctr',
+ 'metrics.average_cpc',
+ 'metrics.cost_micros',
+ 'metrics.conversions',
+ 'metrics.conversions_value',
+];
+
+const DATE_RANGE_PRESETS: GoogleAdsDateRangePreset[] = [
+ 'TODAY',
+ 'YESTERDAY',
+ 'LAST_7_DAYS',
+ 'LAST_14_DAYS',
+ 'LAST_30_DAYS',
+ 'THIS_WEEK_SUN_TODAY',
+ 'THIS_WEEK_MON_TODAY',
+ 'LAST_WEEK_SUN_SAT',
+ 'LAST_WEEK_MON_SUN',
+ 'THIS_MONTH',
+ 'LAST_MONTH',
+ 'LAST_BUSINESS_WEEK',
+];
+
+const RESOURCE_TYPES: GoogleAdsResourceType[] = RESOURCES.map((resource) => resource.type);
+
+export const googleAdsUtils = {
+ normalizeCustomerId,
+ formatCustomerId,
+ assertAllowedUrl,
+ assertGaql,
+ resourceDefinition,
+ resourceNameFor,
+ idFromResourceName,
+ updateMaskFor,
+ buildOperation,
+ newestRecordsQuery,
+ recordsAfterIdQuery,
+ recordsByResourceNamesQuery,
+ recordByResourceNameQuery,
+ buildReportQuery,
+ flattenRow,
+ sha256,
+ normalizeEmail,
+ normalizePhone,
+ normalizeName,
+ identifiersFor,
+ buildMemberBatches,
+ toMemberInput,
+ userListIdFrom,
+ resources: RESOURCES,
+ resourceTypes: RESOURCE_TYPES,
+ reportResources: REPORT_RESOURCES,
+ reportResourceTypes: REPORT_RESOURCE_TYPES,
+ defaultMetrics: DEFAULT_METRICS,
+ dateRangePresets: DATE_RANGE_PRESETS,
+};
diff --git a/packages/pieces/community/google-ads/src/lib/output-schemas.ts b/packages/pieces/community/google-ads/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..b28ab7d60ab
--- /dev/null
+++ b/packages/pieces/community/google-ads/src/lib/output-schemas.ts
@@ -0,0 +1,80 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+const recordMutationFields: OutputSchema['fields'] = [
+ { key: 'resourceType', label: 'Resource Type' },
+ { key: 'resourceName', label: 'Resource Name' },
+ { key: 'id', label: 'Record ID' },
+ { key: 'record', label: 'Record', description: 'The record as Google Ads returns it after the change; its shape depends on the resource type' },
+ { key: 'validateOnly', label: 'Validate Only', format: 'boolean' },
+];
+
+const fieldWarningFields: OutputSchema['fields'] = [
+ { key: 'field', label: 'Field' },
+ { key: 'reason', label: 'Reason' },
+ { key: 'description', label: 'Description' },
+];
+
+const requestFields: OutputSchema['fields'] = [
+ { key: 'requestId', label: 'Request ID' },
+ { key: 'status', label: 'Status' },
+ { key: 'matchRateRange', label: 'Match Rate Range', description: 'Only for additions once Google finished matching this request' },
+];
+
+const reasonCountFields: OutputSchema['fields'] = [
+ { key: 'reason', label: 'Reason' },
+ { key: 'recordCount', label: 'Record Count', format: 'number' },
+];
+
+export const recordMutationOutputSchema: OutputSchema = {
+ fields: recordMutationFields,
+};
+
+export const deleteRecordOutputSchema: OutputSchema = {
+ fields: [...recordMutationFields, { key: 'removed', label: 'Removed', format: 'boolean' }],
+};
+
+export const searchRecordsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'results', label: 'Results', description: 'GAQL rows, nested by resource (for example campaign.id is under campaign)' },
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'nextPageToken', label: 'Next Page Token', description: 'Only when fetching one page; empty on the last page' },
+ { key: 'truncated', label: 'Truncated', format: 'boolean', description: 'Only when fetching all pages; true when Max Rows was reached' },
+ ],
+};
+
+export const retrieveReportOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'query', label: 'GAQL Query' },
+ { key: 'rows', label: 'Rows', description: 'One flat object per row, keyed by GAQL field name (for example metrics.clicks)' },
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'truncated', label: 'Truncated', format: 'boolean' },
+ ],
+};
+
+export const customerMatchOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'status', label: 'Status', description: 'Combined status of all requests: PROCESSING unless waiting saw SUCCESS, PARTIAL_SUCCESS or FAILED' },
+ { key: 'requestIds', label: 'Request IDs' },
+ { key: 'userList', label: 'Audience List Resource Name' },
+ { key: 'userListId', label: 'Audience List ID' },
+ { key: 'mode', label: 'Mode' },
+ { key: 'members', label: 'Members', format: 'number' },
+ { key: 'identifiers', label: 'Identifiers', format: 'number' },
+ {
+ key: 'requests',
+ label: 'Requests',
+ description: 'One entry per request sent to Google, with its own status and, for additions checked while waiting, its match rate range',
+ labelKey: 'requestId',
+ listItems: requestFields,
+ },
+ { key: 'errors', label: 'Errors', labelKey: 'reason', listItems: reasonCountFields },
+ { key: 'warnings', label: 'Warnings', labelKey: 'reason', listItems: reasonCountFields },
+ {
+ key: 'fieldWarnings',
+ label: 'Submission Warnings',
+ description: 'Row-level warnings Google returned when accepting the upload, with the field path that triggered each one',
+ labelKey: 'field',
+ listItems: fieldWarningFields,
+ },
+ ],
+};
diff --git a/packages/pieces/community/google-ads/src/lib/triggers/new-record.ts b/packages/pieces/community/google-ads/src/lib/triggers/new-record.ts
new file mode 100644
index 00000000000..2072fea87c4
--- /dev/null
+++ b/packages/pieces/community/google-ads/src/lib/triggers/new-record.ts
@@ -0,0 +1,188 @@
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
+
+import { googleAdsAuth } from '../auth';
+import { googleAdsApi } from '../common/api';
+import { googleAdsProps } from '../common/props';
+import type { GoogleAdsAuthValue, GoogleAdsResourceDefinition, GoogleAdsRow } from '../common/types';
+import { googleAdsUtils } from '../common/utils';
+
+const LAST_ID_KEY = 'google_ads_new_record_last_id';
+const EVENTS_KEY = 'google_ads_new_record_create_events';
+const TEST_LIMIT = 5;
+const EVENTS_PER_POLL = 10_000;
+const OVERLAP_MS = 10 * 60_000;
+const DAY_MS = 86_400_000;
+
+export const newRecord = createTrigger({
+ name: 'newRecord',
+ classification: 'READ',
+ displayName: 'New Record',
+ description: 'Fires when a campaign, ad group, ad, keyword or audience list is created in the selected account (removed records are ignored)',
+ aiMetadata: {
+ description:
+ 'Fires once per newly created record of the chosen type (campaign, ad group, ad, keyword or audience list) in one Google Ads account. Campaigns, ad groups and audience lists are detected by polling for ids above the last one seen; ads and keywords are detected from the account change history (creations from the last 30 days) because their ids repeat across ad groups. Each payload is one GAQL row nested under the resource (for example campaign.id); removed records and updates do not fire.',
+ },
+ auth: googleAdsAuth,
+ props: {
+ customerId: googleAdsProps.customerId({ required: true }),
+ resourceType: googleAdsProps.resourceType({ required: true }),
+ },
+ type: TriggerStrategy.POLLING,
+ sampleData: {
+ campaign: {
+ resourceName: 'customers/1234567890/campaigns/123456789',
+ id: '123456789',
+ name: 'Spring sale',
+ status: 'ENABLED',
+ advertisingChannelType: 'SEARCH',
+ biddingStrategyType: 'MANUAL_CPC',
+ campaignBudget: 'customers/1234567890/campaignBudgets/1122334455',
+ startDateTime: '2026-09-01 00:00:00',
+ endDateTime: '2037-12-30 23:59:59',
+ },
+ },
+ async onEnable(context) {
+ const { customerId, resourceType } = context.propsValue;
+ await saveBaseline({ auth: context.auth, customerId, def: googleAdsUtils.resourceDefinition(resourceType), store: context.store });
+ },
+ async onDisable(context) {
+ await context.store.delete(LAST_ID_KEY);
+ await context.store.delete(EVENTS_KEY);
+ },
+ async run(context) {
+ const { auth, store } = context;
+ const { customerId } = context.propsValue;
+ const def = googleAdsUtils.resourceDefinition(context.propsValue.resourceType);
+ if (def.changeEventType) {
+ const state = await store.get<EventState>(EVENTS_KEY);
+ if (!state) {
+ await saveBaseline({ auth, customerId, def, store });
+ return [];
+ }
+ const now = new Date();
+ const events = await googleAdsApi.listCreateEvents({
+ auth,
+ customerId,
+ changeEventType: def.changeEventType,
+ after: latest([windowStart(now), state.full ? state.cursor : shift({ time: state.cursor, ms: -OVERLAP_MS })]),
+ until: windowEnd(now),
+ order: 'ASC',
+ limit: EVENTS_PER_POLL,
+ });
+ const fresh = events.filter((row) => !isSeen({ state, row }));
+ await store.put<EventState>(EVENTS_KEY, absorb({ state, events, full: events.length >= EVENTS_PER_POLL }));
+ return await createdRecords({ auth, customerId, def, events: fresh });
+ }
+ const lastId = await store.get<string>(LAST_ID_KEY);
+ if (lastId === null || lastId === undefined) {
+ await saveBaseline({ auth, customerId, def, store });
+ return [];
+ }
+ const rows = await googleAdsApi.listRecordsAfterId({ auth, customerId, def, afterId: lastId });
+ const newestId = def.read(rows[rows.length - 1] ?? {})?.id;
+ if (newestId) {
+ await store.put(LAST_ID_KEY, String(newestId));
+ }
+ return rows;
+ },
+ async test(context) {
+ const def = googleAdsUtils.resourceDefinition(context.propsValue.resourceType);
+ return await googleAdsApi.listNewestRecords({ auth: context.auth, customerId: context.propsValue.customerId, def, limit: TEST_LIMIT });
+ },
+});
+
+async function saveBaseline({ auth, customerId, def, store }: SaveBaselineParams): Promise<void> {
+ if (def.changeEventType) {
+ const now = new Date();
+ const events = await googleAdsApi.listCreateEvents({
+ auth,
+ customerId,
+ changeEventType: def.changeEventType,
+ after: windowStart(now),
+ until: windowEnd(now),
+ order: 'DESC',
+ limit: EVENTS_PER_POLL,
+ });
+ await store.put<EventState>(EVENTS_KEY, absorb({ state: { cursor: windowStart(now), seen: {} }, events, full: false }));
+ return;
+ }
+ const newest = await googleAdsApi.listNewestRecords({ auth, customerId, def, limit: 1 });
+ await store.put(LAST_ID_KEY, String(def.read(newest[0] ?? {})?.id ?? '0'));
+}
+
+async function createdRecords({ auth, customerId, def, events }: CreatedRecordsParams): Promise<GoogleAdsRow[]> {
+ const prefix = `customers/${googleAdsUtils.normalizeCustomerId(customerId)}/${def.collection}/`;
+ const names = [...new Set(events.map((row) => row.changeEvent?.changeResourceName ?? '').filter((name) => name.startsWith(prefix)))];
+ const rows = await googleAdsApi.listRecordsByResourceNames({ auth, customerId, def, resourceNames: names });
+ const byName = new Map(rows.map((row) => [def.read(row)?.resourceName, row]));
+ return names.flatMap((name) => {
+ const row = byName.get(name);
+ const entity = row === undefined ? undefined : def.read(row);
+ if (row === undefined || entity?.status === 'REMOVED' || (def.kind !== undefined && entity?.type !== def.kind.value)) {
+ return [];
+ }
+ return [row];
+ });
+}
+
+function absorb({ state, events, full }: { state: EventState; events: GoogleAdsRow[]; full: boolean }): EventState {
+ const cursor = latest([state.cursor, ...events.map((row) => secondOf(row.changeEvent?.changeDateTime ?? state.cursor))]);
+ const keep = shift({ time: cursor, ms: -OVERLAP_MS });
+ const seen = events.reduce<Record<string, string>>(
+ (groups, row) => {
+ const second = secondOf(row.changeEvent?.changeDateTime ?? '');
+ return second < keep || isSeen({ state: { cursor, seen: groups }, row }) ? groups : { ...groups, [second]: `${groups[second] ?? ''}${seenKey(row)}` };
+ },
+ Object.fromEntries(Object.entries(state.seen).filter(([second]) => second >= keep))
+ );
+ return { cursor, seen, ...(full ? { full } : {}) };
+}
+
+function isSeen({ state, row }: { state: EventState; row: GoogleAdsRow }): boolean {
+ const keys = state.seen[secondOf(row.changeEvent?.changeDateTime ?? '')] ?? '';
+ const key = seenKey(row);
+ return Array.from({ length: keys.length / SEEN_KEY_LENGTH }, (_, i) => keys.slice(i * SEEN_KEY_LENGTH, (i + 1) * SEEN_KEY_LENGTH)).includes(key);
+}
+
+function seenKey(row: GoogleAdsRow): string {
+ return googleAdsUtils.sha256(row.changeEvent?.resourceName ?? '').slice(0, SEEN_KEY_LENGTH);
+}
+
+function secondOf(time: string): string {
+ return time.slice(0, 19);
+}
+
+function shift({ time, ms }: { time: string; ms: number }): string {
+ const [date, clock = '00:00:00'] = time.split(' ');
+ return formatTime(new Date(Date.parse(`${date}T${clock.slice(0, 8)}Z`) + ms));
+}
+
+function windowStart(now: Date): string {
+ return formatTime(new Date(now.getTime() - 29 * DAY_MS)).slice(0, 10);
+}
+
+function windowEnd(now: Date): string {
+ return formatTime(new Date(now.getTime() + 2 * DAY_MS)).slice(0, 10);
+}
+
+function formatTime(date: Date): string {
+ const iso = date.toISOString();
+ return `${iso.slice(0, 10)} ${iso.slice(11, 19)}`;
+}
+
+function latest(times: string[]): string {
+ return times.reduce((max, time) => (time > max ? time : max));
+}
+
+const SEEN_KEY_LENGTH = 8;
+
+type EventState = { cursor: string; seen: Record<string, string>; full?: boolean };
+
+type SaveBaselineParams = {
+ auth: GoogleAdsAuthValue;
+ customerId: string;
+ def: GoogleAdsResourceDefinition;
+ store: { put: <T>(key: string, value: T) => Promise<T> };
+};
+
+type CreatedRecordsParams = { auth: GoogleAdsAuthValue; customerId: string; def: GoogleAdsResourceDefinition; events: GoogleAdsRow[] };
diff --git a/packages/pieces/community/google-ads/test/lib/common/customer-match.test.ts b/packages/pieces/community/google-ads/test/lib/common/customer-match.test.ts
new file mode 100644
index 00000000000..b32ef9642ce
--- /dev/null
+++ b/packages/pieces/community/google-ads/test/lib/common/customer-match.test.ts
@@ -0,0 +1,108 @@
+import { createHash } from 'node:crypto';
+
+import { describe, expect, it } from 'vitest';
+
+import { googleAdsUtils } from '../../../src/lib/common/utils';
+
+const { buildMemberBatches, identifiersFor, normalizeEmail, normalizeName, normalizePhone, sha256, toMemberInput } = googleAdsUtils;
+
+const hash = (s: string) => createHash('sha256').update(s).digest('hex');
+
+describe('normalizeEmail()', () => {
+ it('should trim, lowercase and drop Gmail dots', () => {
+ expect(normalizeEmail(' [email protected] ')).toBe('[email protected]');
+ expect(normalizeEmail('[email protected]')).toBe('[email protected]');
+ expect(normalizeEmail('[email protected]')).toBe('[email protected]');
+ });
+
+ it('should reject values without an @', () => {
+ expect(() => normalizeEmail('nope')).toThrow('not an e-mail address');
+ });
+});
+
+describe('normalizePhone()', () => {
+ it('should keep digits only and prefix +', () => {
+ expect(normalizePhone('+55 (11) 99999-9999')).toBe('+5511999999999');
+ expect(normalizePhone('5511999999999')).toBe('+5511999999999');
+ });
+
+ it('should reject short values', () => {
+ expect(() => normalizePhone('123')).toThrow('E.164');
+ });
+});
+
+describe('normalizeName()', () => {
+ it('should lowercase, drop punctuation and collapse whitespace, keeping accents', () => {
+ expect(normalizeName(" O'Brien ")).toBe('obrien');
+ expect(normalizeName('Maria José')).toBe('maria josé');
+ expect(normalizeName('Dr. Ana-Luísa')).toBe('dr analuísa');
+ });
+});
+
+describe('identifiersFor()', () => {
+ it('should hash each identifier the member provides in the Data Manager shape', () => {
+ expect(
+ identifiersFor({ email: '[email protected]', phone: '+55 (11) 99999-9999', firstName: ' Ana ', lastName: 'Souza', countryCode: 'br', postalCode: ' 01310-100 ' })
+ ).toEqual([
+ { emailAddress: hash('[email protected]') },
+ { phoneNumber: hash('+5511999999999') },
+ { address: { givenName: hash('ana'), familyName: hash('souza'), regionCode: 'BR', postalCode: '01310-100' } },
+ ]);
+ });
+
+ it('should require the full address set when any address field is given', () => {
+ expect(() => identifiersFor({ firstName: 'Ana' })).toThrow('missing: lastName, countryCode, postalCode');
+ });
+
+ it('should return nothing for an empty member', () => {
+ expect(identifiersFor({})).toEqual([]);
+ expect(sha256('x')).toBe(hash('x'));
+ });
+});
+
+describe('buildMemberBatches()', () => {
+ it('should build one audience member per input member', () => {
+ const { batches, identifiers } = buildMemberBatches({ members: [{ email: '[email protected]' }, { phone: '+5511999999999', email: '[email protected]' }], limit: 10 });
+
+ expect(identifiers).toBe(3);
+ expect(batches).toHaveLength(1);
+ expect(batches[0]).toEqual([
+ { userData: { userIdentifiers: [{ emailAddress: hash('[email protected]') }] } },
+ { userData: { userIdentifiers: [{ emailAddress: hash('[email protected]') }, { phoneNumber: hash('+5511999999999') }] } },
+ ]);
+ });
+
+ it('should split batches by the member limit', () => {
+ const members = Array.from({ length: 5 }, (_, i) => ({ email: `u${i}@x.com` }));
+
+ const { batches, identifiers } = buildMemberBatches({ members, limit: 2 });
+
+ expect(identifiers).toBe(5);
+ expect(batches.map((b) => b.length)).toEqual([2, 2, 1]);
+ expect(batches[2]?.[0]).toEqual({ userData: { userIdentifiers: [{ emailAddress: hash('[email protected]') }] } });
+ });
+
+ it('should reject empty input and members without identifiers', () => {
+ expect(() => buildMemberBatches({ members: [], limit: 10 })).toThrow('At least one member');
+ expect(() => buildMemberBatches({ members: [{ email: '[email protected]' }, {}], limit: 10 })).toThrow('Member #2 has no identifier');
+ });
+});
+
+describe('toMemberInput()', () => {
+ it('should keep the known string fields of a member entry', () => {
+ expect(toMemberInput({ email: '[email protected]', phone: '+5511999999999', firstName: 'Ana', lastName: 'Silva', countryCode: 'BR', postalCode: '01000-000', extra: 'x' })).toEqual({
+ email: '[email protected]',
+ phone: '+5511999999999',
+ firstName: 'Ana',
+ lastName: 'Silva',
+ countryCode: 'BR',
+ postalCode: '01000-000',
+ });
+ });
+
+ it('should drop non-string values and tolerate non-object entries', () => {
+ expect(toMemberInput({ email: 42, phone: null })).toEqual({ email: undefined, phone: undefined, firstName: undefined, lastName: undefined, countryCode: undefined, postalCode: undefined });
+ expect(toMemberInput(null)).toEqual({});
+ expect(toMemberInput('[email protected]')).toEqual({});
+ });
+});
diff --git a/packages/pieces/community/google-ads/test/lib/common/resources.test.ts b/packages/pieces/community/google-ads/test/lib/common/resources.test.ts
new file mode 100644
index 00000000000..f104a583425
--- /dev/null
+++ b/packages/pieces/community/google-ads/test/lib/common/resources.test.ts
@@ -0,0 +1,130 @@
+import { describe, expect, it } from 'vitest';
+
+import { googleAdsUtils } from '../../../src/lib/common/utils';
+
+const { resourceDefinition, resourceNameFor, idFromResourceName, updateMaskFor, buildOperation, newestRecordsQuery, recordsByResourceNamesQuery, recordByResourceNameQuery } =
+ googleAdsUtils;
+const RESOURCES = Object.fromEntries(googleAdsUtils.resources.map((def) => [def.type, def]));
+const RESOURCE_TYPES = googleAdsUtils.resourceTypes;
+
+describe('resourceDefinition()', () => {
+ it('should know the five record types', () => {
+ expect(RESOURCE_TYPES).toEqual(['campaign', 'ad_group', 'ad_group_ad', 'ad_group_criterion', 'user_list']);
+ expect(resourceDefinition('campaign').operationKey).toBe('campaignOperation');
+ });
+
+ it('should reject unknown types with the list of valid ones', () => {
+ expect(() => resourceDefinition('banner')).toThrow('Unknown resource type "banner"');
+ });
+});
+
+describe('resourceNameFor()', () => {
+ it('should build simple resource names from numeric ids', () => {
+ expect(resourceNameFor({ def: RESOURCES.campaign, customerId: '1234567890', identifier: '42' })).toBe('customers/1234567890/campaigns/42');
+ expect(resourceNameFor({ def: RESOURCES.user_list, customerId: '1234567890', identifier: ' 7 ' })).toBe('customers/1234567890/userLists/7');
+ });
+
+ it('should require composite ids for ads and keywords', () => {
+ expect(resourceNameFor({ def: RESOURCES.ad_group_ad, customerId: '1234567890', identifier: '11~22' })).toBe('customers/1234567890/adGroupAds/11~22');
+ expect(() => resourceNameFor({ def: RESOURCES.ad_group_criterion, customerId: '1234567890', identifier: '22' })).toThrow('<adGroupId>~<criterionId>');
+ });
+
+ it('should pass full resource names through when they match the type', () => {
+ expect(resourceNameFor({ def: RESOURCES.ad_group, customerId: '1234567890', identifier: 'customers/1234567890/adGroups/5' })).toBe(
+ 'customers/1234567890/adGroups/5'
+ );
+ expect(() => resourceNameFor({ def: RESOURCES.ad_group, customerId: '1234567890', identifier: 'customers/1234567890/campaigns/5' })).toThrow(
+ 'not a ad group resource name'
+ );
+ });
+
+ it('should reject malformed full resource names before sending anything', () => {
+ for (const identifier of [
+ 'customers/1234567890/campaigns/5/extra',
+ 'customers/abc/campaigns/5',
+ 'customers/1234567890/campaigns/abc',
+ 'customers/1234567890/campaigns/',
+ 'customers/1234567890/xcampaigns/5',
+ 'customers/1234567890/campaigns/5~6',
+ ]) {
+ expect(() => resourceNameFor({ def: RESOURCES.campaign, customerId: '1234567890', identifier })).toThrow('is not a campaign resource name');
+ }
+ expect(() => resourceNameFor({ def: RESOURCES.ad_group_criterion, customerId: '1234567890', identifier: 'customers/1234567890/adGroupCriteria/22' })).toThrow(
+ 'customers/<customerId>/adGroupCriteria/<adGroupId>~<criterionId>'
+ );
+ expect(resourceNameFor({ def: RESOURCES.ad_group_criterion, customerId: '1234567890', identifier: ' customers/1234567890/adGroupCriteria/11~22 ' })).toBe(
+ 'customers/1234567890/adGroupCriteria/11~22'
+ );
+ });
+
+ it('should reject a full resource name of another customer', () => {
+ expect(() => resourceNameFor({ def: RESOURCES.campaign, customerId: '1234567890', identifier: 'customers/1111111111/campaigns/5' })).toThrow(
+ 'Campaign customers/1111111111/campaigns/5 belongs to customer 1111111111, but the selected customer is 1234567890.'
+ );
+ });
+
+ it('should reject non-numeric simple ids', () => {
+ expect(() => resourceNameFor({ def: RESOURCES.campaign, customerId: '1234567890', identifier: 'abc' })).toThrow('must be numeric');
+ });
+});
+
+describe('idFromResourceName()', () => {
+ it('should return the last segment or null', () => {
+ expect(idFromResourceName('customers/1/adGroupAds/2~3')).toBe('2~3');
+ expect(idFromResourceName(undefined)).toBeNull();
+ expect(idFromResourceName('')).toBeNull();
+ });
+});
+
+describe('updateMaskFor()', () => {
+ it('should list every leaf path and skip resourceName', () => {
+ expect(
+ updateMaskFor({
+ resourceName: 'customers/1/adGroups/2',
+ name: 'x',
+ cpcBidMicros: '100',
+ targetingSetting: { targetRestrictions: [{ targetingDimension: 'AUDIENCE' }] },
+ keyword: { text: 'a', matchType: 'EXACT' },
+ emptyMessage: {},
+ })
+ ).toBe('name,cpcBidMicros,targetingSetting.targetRestrictions,keyword.text,keyword.matchType,emptyMessage');
+ });
+
+ it('should refuse an empty update', () => {
+ expect(() => updateMaskFor({ resourceName: 'customers/1/campaigns/2' })).toThrow('Nothing to update');
+ });
+});
+
+describe('buildOperation()', () => {
+ it('should wrap the operation in the per-type envelope', () => {
+ expect(buildOperation({ def: RESOURCES.ad_group_criterion, operation: { remove: 'customers/1/adGroupCriteria/2~3' } })).toEqual({
+ adGroupCriterionOperation: { remove: 'customers/1/adGroupCriteria/2~3' },
+ });
+ });
+});
+
+describe('newestRecordsQuery()', () => {
+ it('should select the default fields newest first with the type filter', () => {
+ expect(newestRecordsQuery({ def: RESOURCES.ad_group_criterion, limit: 5 })).toBe(
+ "SELECT ad_group_criterion.criterion_id, ad_group_criterion.keyword.text, ad_group_criterion.keyword.match_type, ad_group_criterion.status, ad_group_criterion.ad_group, ad_group_criterion.resource_name FROM ad_group_criterion WHERE ad_group_criterion.type = 'KEYWORD' AND ad_group_criterion.status != 'REMOVED' ORDER BY ad_group_criterion.criterion_id DESC LIMIT 5"
+ );
+ expect(newestRecordsQuery({ def: RESOURCES.campaign, limit: 100 })).toMatch(/^SELECT campaign\.id, .* FROM campaign WHERE campaign\.status != 'REMOVED' ORDER BY campaign\.id DESC LIMIT 100$/);
+ expect(newestRecordsQuery({ def: RESOURCES.user_list, limit: 100 })).toMatch(/^SELECT user_list\.id, .* FROM user_list ORDER BY user_list\.id DESC LIMIT 100$/);
+ });
+
+ it('should fetch criteria by resource names with their type, removed ones and other types included so they can be told apart from unreadable ones, and reject anything else', () => {
+ expect(recordsByResourceNamesQuery({ def: RESOURCES.ad_group_criterion, resourceNames: ['customers/1/adGroupCriteria/2~3', 'customers/1/adGroupCriteria/4~3'] })).toBe(
+ `SELECT ${RESOURCES.ad_group_criterion.fields.join(', ')}, ad_group_criterion.type FROM ad_group_criterion WHERE ad_group_criterion.resource_name IN ('customers/1/adGroupCriteria/2~3', 'customers/1/adGroupCriteria/4~3')`
+ );
+ expect(recordsByResourceNamesQuery({ def: RESOURCES.ad_group_ad, resourceNames: ['customers/1/adGroupAds/2~3'] })).toBe(
+ `SELECT ${RESOURCES.ad_group_ad.fields.join(', ')} FROM ad_group_ad WHERE ad_group_ad.resource_name IN ('customers/1/adGroupAds/2~3')`
+ );
+ expect(() => recordsByResourceNamesQuery({ def: RESOURCES.ad_group_ad, resourceNames: ["customers/1/adGroupAds/2~3' OR '1"] })).toThrow('is not a ad resource name');
+ });
+
+ it('should fetch one record by resource name', () => {
+ expect(recordByResourceNameQuery({ def: RESOURCES.user_list, resourceName: 'customers/1/userLists/2' })).toBe(
+ `SELECT ${RESOURCES.user_list.fields.join(', ')} FROM user_list WHERE user_list.resource_name = 'customers/1/userLists/2' LIMIT 1`
+ );
+ });
+});
diff --git a/packages/pieces/community/google-ads/tsconfig.json b/packages/pieces/community/google-ads/tsconfig.json
new file mode 100644
index 00000000000..71bc5814f5d
--- /dev/null
+++ b/packages/pieces/community/google-ads/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "extends": "../../../../tsconfig.base.json",
+ "compilerOptions": {
+ "module": "commonjs",
+ "forceConsistentCasingInFileNames": true,
+ "strict": true,
+ "noImplicitOverride": true,
+ "noPropertyAccessFromIndexSignature": true,
+ "noImplicitReturns": true,
+ "noFallthroughCasesInSwitch": true
+ },
+ "files": [],
+ "include": [],
+ "references": [{ "path": "./tsconfig.lib.json" }]
+}
diff --git a/packages/pieces/community/google-ads/tsconfig.lib.json b/packages/pieces/community/google-ads/tsconfig.lib.json
new file mode 100644
index 00000000000..a648eb45d7f
--- /dev/null
+++ b/packages/pieces/community/google-ads/tsconfig.lib.json
@@ -0,0 +1,13 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "rootDir": ".",
+ "baseUrl": ".",
+ "paths": {},
+ "outDir": "./dist",
+ "declaration": true,
+ "types": ["node"]
+ },
+ "include": ["src/**/*.ts"],
+ "exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"]
+}
diff --git a/packages/pieces/community/google-ads/vitest.config.ts b/packages/pieces/community/google-ads/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/google-ads/vitest.config.ts
@@ -0,0 +1,19 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ root: __dirname,
+ test: {
+ globals: true,
+ environment: 'node',
+ include: ['test/**/*.test.ts'],
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+})
diff --git a/tsconfig.base.json b/tsconfig.base.json
index 4414cf3bf06..1dd2d29e5cd 100644
--- a/tsconfig.base.json
+++ b/tsconfig.base.json
@@ -226,6 +226,9 @@
"@activepieces/piece-calendly": [
"packages/pieces/community/calendly/src/index.ts"
],
+ "@activepieces/piece-google-ads": [
+ "packages/pieces/community/google-ads/src/index.ts"
+ ],
"@activepieces/piece-google-translate": [
"packages/pieces/community/google-translate/src/index.ts"
],