{
  "name": "Vexqo · Meta ads → Google Sheets swipe file",
  "nodes": [
    {
      "id": "start-here",
      "name": "Start here",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "parameters": {
        "content": "### How it works\nFor marketers keeping an ad swipe file: a manual run or daily schedule reads one page of Meta ads for each configured advertiser. The first live run writes current creatives to Google Sheets; later runs append newly observed or edited creatives. Each creative version gets a row. Media links may expire; this is not an archive of all ads or evidence of sales.\n\n### Setup\nTested with n8n 2.49.7. Import inactive and run manually with demoMode: true. Demo result uses labeled synthetic data; it makes no requests, spends no credits, saves no state and sends nothing.\n\n1. Create an n8n Data Table with two String columns: key and state. Leave it empty and set tableId in Settings.\n2. Get a Vexqo API key. Create a Header Auth credential named X-API-Key, with the key as its value, and select it in each Collect node. Live requests use credits.\n3. In Settings, replace verified advertiser page IDs and choose a unique watchId.\n4. Connect Google Sheets, set spreadsheetId and worksheet, and create the headers listed in the delivery note.\n5. Set demoMode: false, run manually, inspect the result and destination, then publish the schedule.\n\n### Customization\nAdjust the schedule and targets. Changing target/filter settings resets the whole watch. Run one execution at a time. Pause after failures and retry the saved execution before new checks; retries may repeat delivered rows. See the section notes and [setup guide](https://vexqo.dev/n8n-workflows/#setup).",
        "height": 760,
        "width": 720,
        "color": 1
      },
      "position": [
        -600,
        -1000
      ]
    },
    {
      "id": "manual-trigger",
      "name": "Manual Trigger",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "parameters": {},
      "position": [
        -560,
        100
      ]
    },
    {
      "id": "daily-schedule",
      "name": "Daily schedule",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "days",
              "daysInterval": 1,
              "triggerAtHour": 9,
              "triggerAtMinute": 0
            }
          ]
        }
      },
      "position": [
        -560,
        300
      ]
    },
    {
      "id": "settings",
      "name": "Settings",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "jsCode": "// Edit only this object. Keep API keys in n8n credentials, never here.\nconst config = {\n  \"demoMode\": true,\n  \"kind\": \"meta-ad-swipe-file\",\n  \"watchId\": \"meta-ad-swipe-file-1\",\n  \"tableId\": \"\",\n  \"chatId\": \"\",\n  \"spreadsheetId\": \"\",\n  \"worksheet\": \"Sheet1\",\n  \"advertisers\": [\n    {\n      \"name\": \"Example advertiser — replace before going live\",\n      \"pageId\": \"100000000001\"\n    }\n  ],\n  \"country\": \"ALL\",\n  \"limit\": 30\n};\n\nfunction prepareConfig(config) {\n  if (typeof config.demoMode !== 'boolean') throw new Error('demoMode must be true or false.');\n  if (!config.watchId?.trim()) throw new Error('Give this watch a unique watchId.');\n  if (!config.demoMode && !config.tableId?.trim()) throw new Error('Set tableId to your n8n Data Table ID.');\n  const watch = { kind: config.kind, watchId: config.watchId };\n  if (config.kind === 'meta-ad-swipe-file') {\n    if (!config.demoMode && !config.spreadsheetId?.trim()) throw new Error('Set spreadsheetId to your Google spreadsheet ID.');\n    if (!Array.isArray(config.advertisers) || !config.advertisers.length || config.advertisers.some(a => !/^\\d+$/.test(a.pageId))) {\n      throw new Error('Set each advertiser pageId to its numeric Meta Page ID.');\n    }\n    if (!Number.isInteger(config.limit) || config.limit < 1 || config.limit > 100) throw new Error('Meta limit must be 1–100.');\n    Object.assign(watch, { advertisers: config.advertisers, country: config.country, limit: config.limit });\n  } else if (config.kind === 'shopify-price-alerts') {\n    if (!Array.isArray(config.products) || !config.products.length) throw new Error('Add at least one product.');\n    for (const product of config.products) {\n      if (!/^https:\\/\\/[^/]+\\/(?:[^/?#]+\\/)*products\\/[^/?#]+(?:\\?[^#]*)?$/.test(product.url) || !/^\\d+$/.test(product.variantId)) {\n        throw new Error('Each Shopify watch needs an HTTPS product URL and exact numeric variantId.');\n      }\n    }\n    Object.assign(watch, { products: config.products });\n  } else {\n    if (typeof config.query !== 'string' || !config.query.trim() || config.query.length > 300) throw new Error('Set an eBay query of 1–300 characters.');\n    if (!Array.isArray(config.excludeTerms) || !Array.isArray(config.blockedSellers)) throw new Error('Use arrays for excludeTerms and blockedSellers.');\n    if (config.kind !== 'ebay-seller-digest' && config.blockedSellers.length) throw new Error('Use the seller digest workflow to filter by seller username.');\n    Object.assign(watch, { query: config.query, excludeTerms: config.excludeTerms, blockedSellers: config.blockedSellers,\n      maxPrice: config.maxPrice, currency: config.currency, buyingFormat: config.buyingFormat, condition: config.condition });\n  }\n  if (!config.demoMode && config.kind !== 'meta-ad-swipe-file' && !config.chatId?.trim()) throw new Error('Set chatId to your Telegram destination.');\n  return { ...config, stateKey: JSON.stringify(watch) };\n}\nreturn [{json: prepareConfig(config)}];"
      },
      "position": [
        -300,
        100
      ]
    },
    {
      "id": "demo-",
      "name": "Demo?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "condition",
              "leftValue": "={{ $json.demoMode }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "position": [
        -60,
        100
      ]
    },
    {
      "id": "demo-result",
      "name": "Demo result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "jsCode": "function processMeta(responses, previous, config, now) {\n  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);\n  const identifier = value => typeof value === 'string' && value.trim() ? value.trim()\n    : Number.isSafeInteger(value) && value >= 0 ? String(value) : null;\n  const text = value => typeof value === 'string' ? value : '';\n  const media = value => Array.isArray(value) ? value.filter(item => typeof item === 'string' && item.trim()) : [];\n  const mediaIdentity = value => {\n    const parts = /^https?:\\/\\/([a-z0-9.-]+)(\\/[^?#]*)(?:\\?([^#]*))?(?:#.*)?$/i.exec(value);\n    if (!parts || !/(^|\\.)fbcdn\\.net$/i.test(parts[1])) return value;\n    // Facebook CDN signatures/edge routing expire without changing the asset.\n    // Keep paths, rendition parameters (including stp), and all unknown keys.\n    const transport = new Set(['oh', 'oe', 'ccb', 'edm', '_nc_ht', '_nc_cat', '_nc_ohc', '_nc_oc', '_nc_sid', '_nc_gid']);\n    let parameters;\n    try { parameters = (parts[3] || '').split('&').filter(pair => pair && !transport.has(decodeURIComponent(pair.split('=')[0]))); }\n    catch { return value; }\n    return `https://fbcdn.net${parts[2]}${parameters.length ? '?' + parameters.join('&') : ''}`;\n  };\n  if (!object(config) || !Array.isArray(config.advertisers) || !config.advertisers.length) {\n    throw new Error('Meta config needs at least one advertiser with a pageId.');\n  }\n  if (!Array.isArray(responses) || responses.length !== config.advertisers.length) {\n    throw new Error('Meta responses must contain one response for each configured advertiser, in the same order.');\n  }\n  if (previous !== null && previous !== undefined && (!object(previous) || previous.version !== 1 || previous.kind !== 'meta-ad-swipe-file' || !object(previous.ads))) {\n    throw new Error('Unsupported Meta state. Keep the saved state or reset it deliberately.');\n  }\n  const state = previous ? JSON.parse(JSON.stringify(previous)) : { version: 1, kind: 'meta-ad-swipe-file', ads: {} };\n  const rows = [];\n  const warnings = [];\n  const observed = new Set();\n  responses.forEach((response, index) => {\n    if (!object(response) || response.error || !Array.isArray(response.ads) || !object(response.search_information)) {\n      throw new Error(`Invalid Meta response for advertiser ${index + 1}: expected ads and search_information.`);\n    }\n    const target = config.advertisers[index];\n    const pageId = identifier(target?.pageId);\n    if (!pageId) {\n      warnings.push(`Advertiser ${index + 1}: pageId is required to verify advertiser identity; results skipped.`);\n      return;\n    }\n    const information = response.search_information;\n    if (information.has_more === true) warnings.push(`${text(target.name) || pageId}: more ads are available beyond this response; this swipe file covers only the returned ads.`);\n    if (typeof information.refused_requests === 'number' && information.refused_requests > 0) warnings.push(`${text(target.name) || pageId}: the source refused part of the collection; results may be partial.`);\n    response.ads.forEach((ad, adIndex) => {\n      if (!object(ad)) throw new Error(`Malformed Meta ad ${adIndex + 1} for page ${pageId}.`);\n      const adId = identifier(ad.ad_archive_id);\n      if (!adId || identifier(ad.page_id) !== pageId) {\n        warnings.push(`Ad ${adId || adIndex + 1}: missing ad ID or unverified advertiser page; skipped for requested page ${pageId}.`);\n        return;\n      }\n      if (!Array.isArray(ad.creatives) || !ad.creatives.length) {\n        warnings.push(`Ad ${adId}: no compact creative groups were returned; use view=compact and retain the previous state.`);\n        return;\n      }\n      const key = `${pageId}:${adId}`;\n      const fingerprints = new Set(Array.isArray(state.ads[key]?.fingerprints) ? state.ads[key].fingerprints : []);\n      observed.add(key);\n      ad.creatives.forEach((creative, creativeIndex) => {\n        if (!object(creative)) throw new Error(`Malformed creative ${creativeIndex + 1} in Meta ad ${adId}.`);\n        const images = media(creative.images);\n        const videos = media(creative.videos);\n        const source = text(creative.source) || `creative[${creativeIndex}]`;\n        const content = [source, text(creative.text), text(creative.title), text(creative.description), text(creative.cta), text(creative.destination_url), images, videos];\n        if (!content.slice(1, 6).some(Boolean) && !images.length && !videos.length) {\n          warnings.push(`Ad ${adId}, creative ${creativeIndex + 1}: no usable creative fields; skipped.`);\n          return;\n        }\n        const fingerprint = JSON.stringify([...content.slice(0, 6), images.map(mediaIdentity), videos.map(mediaIdentity)]);\n        if (fingerprints.has(fingerprint)) return;\n        fingerprints.add(fingerprint);\n        const row = {\n          ad_id: adId,\n          advertiser: text(ad.page_name) || text(target.name),\n          page_id: pageId,\n          library_url: text(ad.ad_library_url) || `https://www.facebook.com/ads/library/?id=${encodeURIComponent(adId)}`,\n          text: text(creative.text),\n          title: text(creative.title),\n          cta: text(creative.cta),\n          destination_url: text(creative.destination_url),\n          images: images.join('\\n'),\n          videos: videos.join('\\n'),\n          observed_at: now,\n          creative_index: creativeIndex + 1,\n          creative_source: source,\n        };\n        const started = text(ad.started_at) || text(ad.start_date_formatted) || text(ad.start_date);\n        if (started) row.start_date = started;\n        if (text(creative.description)) row.description = creative.description;\n        rows.push(row);\n      });\n      state.ads[key] = { fingerprints: [...fingerprints] };\n    });\n  });\n  return { state, rows, summary: { ads_observed: observed.size, creative_rows: rows.length }, warnings };\n}\nfunction asCsv(rows) {\n  const columns = [...new Set(rows.flatMap(row => Object.keys(row)))];\n  const cell = value => {\n    let text = value == null ? '' : typeof value === 'object' ? JSON.stringify(value) : String(value);\n    // Public listing/ad text is untrusted. Do not let a spreadsheet evaluate formulas.\n    if (/^[\\s]*[=+@-]/.test(text) || /^[\\t\\r\\n]/.test(text)) text = `'${text}`;\n    return `\"${text.replace(/\"/g, '\"\"')}\"`;\n  };\n  return [columns.map(cell).join(','), ...rows.map(row => columns.map(key => cell(row[key])).join(','))].join('\\r\\n');\n}\nconst sample = {\n  \"label\": \"SYNTHETIC DEMO — not live data. No requests, credits, saved state or messages.\",\n  \"config\": {\n    \"demoMode\": true,\n    \"kind\": \"meta-ad-swipe-file\",\n    \"watchId\": \"meta-ad-swipe-file-1\",\n    \"tableId\": \"\",\n    \"chatId\": \"\",\n    \"spreadsheetId\": \"\",\n    \"worksheet\": \"Sheet1\",\n    \"advertisers\": [\n      {\n        \"name\": \"Example advertiser — replace before going live\",\n        \"pageId\": \"100000000001\"\n      }\n    ],\n    \"country\": \"ALL\",\n    \"limit\": 30\n  },\n  \"now\": \"2026-11-26T09:00:00.000Z\",\n  \"previous\": null,\n  \"responses\": [\n    {\n      \"ads\": [\n        {\n          \"ad_archive_id\": \"300000000001\",\n          \"page_id\": \"100000000001\",\n          \"page_name\": \"Example audio store\",\n          \"started_at\": \"2026-11-24\",\n          \"creatives\": [\n            {\n              \"source\": \"snapshot\",\n              \"text\": \"Take your music outside.\",\n              \"title\": \"Portable player\",\n              \"cta\": \"SHOP_NOW\",\n              \"destination_url\": \"https://store.example/products/player\",\n              \"images\": [\n                \"https://assets.example/player.jpg\"\n              ],\n              \"videos\": []\n            },\n            {\n              \"source\": \"cards[0]\",\n              \"text\": \"A pocket full of albums.\",\n              \"title\": \"Portable player — blue\",\n              \"cta\": \"SHOP_NOW\",\n              \"destination_url\": \"https://store.example/products/player?color=blue\",\n              \"images\": [],\n              \"videos\": [\n                \"https://assets.example/player.mp4\"\n              ]\n            }\n          ]\n        }\n      ],\n      \"search_information\": {\n        \"ads_returned\": 1,\n        \"has_more\": false\n      }\n    }\n  ]\n};\nconst result = processMeta(sample.responses, sample.previous, sample.config, sample.now);\nreturn [{json: {demo: true, label: sample.label, ...result, csv: asCsv(result.rows)}}];"
      },
      "position": [
        200,
        -260
      ]
    },
    {
      "id": "read-baseline",
      "name": "Read baseline",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "value": "={{ $('Settings').first().json.tableId }}",
          "mode": "id"
        },
        "matchType": "allConditions",
        "filters": {
          "conditions": [
            {
              "keyName": "key",
              "condition": "eq",
              "keyValue": "={{ $('Settings').first().json.stateKey }}"
            }
          ]
        },
        "returnAll": false,
        "limit": 2
      },
      "position": [
        200,
        180
      ],
      "alwaysOutputData": true
    },
    {
      "id": "read-saved-state",
      "name": "Read saved state",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "jsCode": "function readSavedState(items) {\n  const rows = items.filter(row => typeof row.key === 'string');\n  if (rows.length > 1) throw new Error('Duplicate state rows found. Stop overlapping runs and keep one verified row for this key.');\n  if (!rows.length) return null;\n  if (typeof rows[0].state !== 'string' || !rows[0].state.trim()) throw new Error('Saved state is empty; inspect the Data Table before retrying.');\n  const state = JSON.parse(rows[0].state);\n  if (!state || typeof state !== 'object' || Array.isArray(state)) throw new Error('Saved state is not an object.');\n  return state;\n}\nreturn [{json: {previous: readSavedState($input.all().map(item => item.json))}}];"
      },
      "position": [
        440,
        180
      ]
    },
    {
      "id": "build-requests",
      "name": "Build requests",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "jsCode": "function makeRequests(config) {\n  const base = 'https://api.vexqo.dev';\n  if (config.kind === 'meta-ad-swipe-file') return config.advertisers.map(a => ({\n    url: `${base}/facebook/ads`, query: { page_id: a.pageId, country: config.country,\n      active_status: 'active', limit: config.limit, view: 'compact' },\n  }));\n  if (config.kind === 'shopify-price-alerts') return config.products.map(p => {\n    // Replace a pre-existing variant parameter so the API verifies the watched variant.\n    const [path, query = ''] = p.url.split('?');\n    const params = query.split('&').filter(x => x && decodeURIComponent(x.split('=')[0]) !== 'variant');\n    params.push(`variant=${encodeURIComponent(p.variantId)}`);\n    return { url: `${base}/shopify`, body: { url: `${path}?${params.join('&')}` } };\n  });\n  // Do not send max_price: local checks preserve currency and reject price ranges safely.\n  return [{ url: `${base}/ebay/search`, query: { q: config.query, page: 1, per_page: 60,\n    sort: 'newly_listed', buying_format: config.buyingFormat, condition: config.condition } }];\n}\nreturn makeRequests($('Settings').first().json).map(request => ({json: request}));"
      },
      "position": [
        680,
        180
      ]
    },
    {
      "id": "collect-data",
      "name": "Collect data",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "parameters": {
        "method": "GET",
        "url": "={{ $json.url }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendQuery": true,
        "specifyQuery": "json",
        "jsonQuery": "={{ JSON.stringify($json.query || {}) }}",
        "options": {
          "timeout": 120000,
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 7000
            }
          },
          "response": {
            "response": {
              "responseFormat": "json"
            }
          }
        }
      },
      "position": [
        920,
        180
      ],
      "notesInFlow": true,
      "notes": "Select a Header Auth credential: Name X-API-Key, Value your Vexqo key. Requests are serial, 7 seconds apart. Errors stop the run; saved state stays unchanged."
    },
    {
      "id": "configure-the-watch",
      "name": "Configure the watch",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "parameters": {
        "content": "## Configure and try the sample\nEdit the Settings object. Keep secrets in credentials. The manual trigger and schedule use the same settings. Demo mode returns a simulated result and bypasses every live node.",
        "width": 720,
        "height": 170,
        "color": 7
      },
      "position": [
        -600,
        -100
      ]
    },
    {
      "id": "load-history-and-fetch-data",
      "name": "Load history and fetch data",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "parameters": {
        "content": "## Read previous observations, then collect\nThe table stores one JSON baseline per watch. Do not edit it during a run. Collection requests are serial and seven seconds apart. A failed request stops before the baseline is changed.",
        "width": 960,
        "height": 170,
        "color": 7
      },
      "position": [
        160,
        -80
      ]
    },
    {
      "id": "compare-and-deliver",
      "name": "Compare and deliver",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "parameters": {
        "content": "## Write one row per creative version\nCreate these Sheet headers:\n`ad_id,advertiser,page_id,library_url,text,title,description,cta,destination_url,images,videos,start_date,observed_at,creative_index,creative_source`\nKeep RAW input mode: public ad copy must remain text, not formulas. One ad may have multiple rows.",
        "width": 920,
        "height": 170,
        "color": 7
      },
      "position": [
        1120,
        -180
      ]
    },
    {
      "id": "save-after-delivery",
      "name": "Save after delivery",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "parameters": {
        "content": "## Commit the next baseline\nState saves after successful delivery or a valid no-change run. Pause the schedule after errors. Retry the saved failure before fresh checks; fresh data can miss temporary changes. Delivery may repeat if saving fails. Never retry an older failure after newer state.",
        "width": 780,
        "height": 170,
        "color": 7
      },
      "position": [
        2080,
        -180
      ]
    },
    {
      "id": "coverage-and-credits",
      "name": "Coverage and credits",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "parameters": {
        "content": "## Coverage and credits\nOne page, up to 30 ads per advertiser: at most 3 credits per advertiser, minimum 1. More results generate a warning. No automatic pagination or performance estimates.",
        "width": 920,
        "height": 170,
        "color": 7
      },
      "position": [
        1120,
        440
      ]
    },
    {
      "id": "process-live",
      "name": "Process live",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "jsCode": "function processMeta(responses, previous, config, now) {\n  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);\n  const identifier = value => typeof value === 'string' && value.trim() ? value.trim()\n    : Number.isSafeInteger(value) && value >= 0 ? String(value) : null;\n  const text = value => typeof value === 'string' ? value : '';\n  const media = value => Array.isArray(value) ? value.filter(item => typeof item === 'string' && item.trim()) : [];\n  const mediaIdentity = value => {\n    const parts = /^https?:\\/\\/([a-z0-9.-]+)(\\/[^?#]*)(?:\\?([^#]*))?(?:#.*)?$/i.exec(value);\n    if (!parts || !/(^|\\.)fbcdn\\.net$/i.test(parts[1])) return value;\n    // Facebook CDN signatures/edge routing expire without changing the asset.\n    // Keep paths, rendition parameters (including stp), and all unknown keys.\n    const transport = new Set(['oh', 'oe', 'ccb', 'edm', '_nc_ht', '_nc_cat', '_nc_ohc', '_nc_oc', '_nc_sid', '_nc_gid']);\n    let parameters;\n    try { parameters = (parts[3] || '').split('&').filter(pair => pair && !transport.has(decodeURIComponent(pair.split('=')[0]))); }\n    catch { return value; }\n    return `https://fbcdn.net${parts[2]}${parameters.length ? '?' + parameters.join('&') : ''}`;\n  };\n  if (!object(config) || !Array.isArray(config.advertisers) || !config.advertisers.length) {\n    throw new Error('Meta config needs at least one advertiser with a pageId.');\n  }\n  if (!Array.isArray(responses) || responses.length !== config.advertisers.length) {\n    throw new Error('Meta responses must contain one response for each configured advertiser, in the same order.');\n  }\n  if (previous !== null && previous !== undefined && (!object(previous) || previous.version !== 1 || previous.kind !== 'meta-ad-swipe-file' || !object(previous.ads))) {\n    throw new Error('Unsupported Meta state. Keep the saved state or reset it deliberately.');\n  }\n  const state = previous ? JSON.parse(JSON.stringify(previous)) : { version: 1, kind: 'meta-ad-swipe-file', ads: {} };\n  const rows = [];\n  const warnings = [];\n  const observed = new Set();\n  responses.forEach((response, index) => {\n    if (!object(response) || response.error || !Array.isArray(response.ads) || !object(response.search_information)) {\n      throw new Error(`Invalid Meta response for advertiser ${index + 1}: expected ads and search_information.`);\n    }\n    const target = config.advertisers[index];\n    const pageId = identifier(target?.pageId);\n    if (!pageId) {\n      warnings.push(`Advertiser ${index + 1}: pageId is required to verify advertiser identity; results skipped.`);\n      return;\n    }\n    const information = response.search_information;\n    if (information.has_more === true) warnings.push(`${text(target.name) || pageId}: more ads are available beyond this response; this swipe file covers only the returned ads.`);\n    if (typeof information.refused_requests === 'number' && information.refused_requests > 0) warnings.push(`${text(target.name) || pageId}: the source refused part of the collection; results may be partial.`);\n    response.ads.forEach((ad, adIndex) => {\n      if (!object(ad)) throw new Error(`Malformed Meta ad ${adIndex + 1} for page ${pageId}.`);\n      const adId = identifier(ad.ad_archive_id);\n      if (!adId || identifier(ad.page_id) !== pageId) {\n        warnings.push(`Ad ${adId || adIndex + 1}: missing ad ID or unverified advertiser page; skipped for requested page ${pageId}.`);\n        return;\n      }\n      if (!Array.isArray(ad.creatives) || !ad.creatives.length) {\n        warnings.push(`Ad ${adId}: no compact creative groups were returned; use view=compact and retain the previous state.`);\n        return;\n      }\n      const key = `${pageId}:${adId}`;\n      const fingerprints = new Set(Array.isArray(state.ads[key]?.fingerprints) ? state.ads[key].fingerprints : []);\n      observed.add(key);\n      ad.creatives.forEach((creative, creativeIndex) => {\n        if (!object(creative)) throw new Error(`Malformed creative ${creativeIndex + 1} in Meta ad ${adId}.`);\n        const images = media(creative.images);\n        const videos = media(creative.videos);\n        const source = text(creative.source) || `creative[${creativeIndex}]`;\n        const content = [source, text(creative.text), text(creative.title), text(creative.description), text(creative.cta), text(creative.destination_url), images, videos];\n        if (!content.slice(1, 6).some(Boolean) && !images.length && !videos.length) {\n          warnings.push(`Ad ${adId}, creative ${creativeIndex + 1}: no usable creative fields; skipped.`);\n          return;\n        }\n        const fingerprint = JSON.stringify([...content.slice(0, 6), images.map(mediaIdentity), videos.map(mediaIdentity)]);\n        if (fingerprints.has(fingerprint)) return;\n        fingerprints.add(fingerprint);\n        const row = {\n          ad_id: adId,\n          advertiser: text(ad.page_name) || text(target.name),\n          page_id: pageId,\n          library_url: text(ad.ad_library_url) || `https://www.facebook.com/ads/library/?id=${encodeURIComponent(adId)}`,\n          text: text(creative.text),\n          title: text(creative.title),\n          cta: text(creative.cta),\n          destination_url: text(creative.destination_url),\n          images: images.join('\\n'),\n          videos: videos.join('\\n'),\n          observed_at: now,\n          creative_index: creativeIndex + 1,\n          creative_source: source,\n        };\n        const started = text(ad.started_at) || text(ad.start_date_formatted) || text(ad.start_date);\n        if (started) row.start_date = started;\n        if (text(creative.description)) row.description = creative.description;\n        rows.push(row);\n      });\n      state.ads[key] = { fingerprints: [...fingerprints] };\n    });\n  });\n  return { state, rows, summary: { ads_observed: observed.size, creative_rows: rows.length }, warnings };\n}\nconst config = $('Settings').first().json;\nconst previous = $('Read saved state').first().json.previous;\nconst result = processMeta($input.all().map(item => item.json), previous, config, new Date().toISOString());\nreturn [{json: {demo: false, ...result}}];"
      },
      "position": [
        1160,
        180
      ]
    },
    {
      "id": "has-new-rows-",
      "name": "Has new rows?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "condition",
              "leftValue": "={{ $json.rows.length > 0 }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "position": [
        1400,
        180
      ]
    },
    {
      "id": "sheet-rows",
      "name": "Sheet rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "jsCode": "const columns = ['ad_id','advertiser','page_id','library_url','text','title','description','cta','destination_url','images','videos','start_date','observed_at','creative_index','creative_source'];\nreturn $input.first().json.rows.map(row => ({json: Object.fromEntries(columns.map(key => [key, row[key] ?? '']))}));"
      },
      "position": [
        1640,
        60
      ]
    },
    {
      "id": "append-to-swipe-file",
      "name": "Append to swipe file",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "={{ $('Settings').first().json.spreadsheetId }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "={{ $('Settings').first().json.worksheet }}",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {
          "cellFormat": "RAW"
        }
      },
      "position": [
        1880,
        60
      ],
      "notesInFlow": true,
      "notes": "Select your Google Sheets credential, document and sheet. Add the 15 column headers from the setup guide. RAW keeps public ad text from becoming spreadsheet formulas."
    },
    {
      "id": "prepare-state",
      "name": "Prepare state",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "jsCode": "const config = $('Settings').first().json;\nconst result = $('Process live').first().json;\nreturn [{json: {key: config.stateKey, state: JSON.stringify(result.state)}}];"
      },
      "position": [
        2120,
        180
      ]
    },
    {
      "id": "save-baseline",
      "name": "Save baseline",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "parameters": {
        "resource": "row",
        "operation": "upsert",
        "dataTableId": {
          "__rl": true,
          "value": "={{ $('Settings').first().json.tableId }}",
          "mode": "id"
        },
        "matchType": "allConditions",
        "filters": {
          "conditions": [
            {
              "keyName": "key",
              "condition": "eq",
              "keyValue": "={{ $('Settings').first().json.stateKey }}"
            }
          ]
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "position": [
        2360,
        180
      ]
    },
    {
      "id": "run-result",
      "name": "Run result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "jsCode": "const result = $('Process live').first().json;\nreturn [{json: {saved: true, rows: result.rows, summary: result.summary, warnings: result.warnings}}];"
      },
      "position": [
        2600,
        180
      ]
    }
  ],
  "connections": {
    "Manual Trigger": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Daily schedule": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Settings": {
      "main": [
        [
          {
            "node": "Demo?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Demo?": {
      "main": [
        [
          {
            "node": "Demo result",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Read baseline",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read baseline": {
      "main": [
        [
          {
            "node": "Read saved state",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read saved state": {
      "main": [
        [
          {
            "node": "Build requests",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build requests": {
      "main": [
        [
          {
            "node": "Collect data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Collect data": {
      "main": [
        [
          {
            "node": "Process live",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Process live": {
      "main": [
        [
          {
            "node": "Has new rows?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Has new rows?": {
      "main": [
        [
          {
            "node": "Sheet rows",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Prepare state",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sheet rows": {
      "main": [
        [
          {
            "node": "Append to swipe file",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Append to swipe file": {
      "main": [
        [
          {
            "node": "Prepare state",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare state": {
      "main": [
        [
          {
            "node": "Save baseline",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save baseline": {
      "main": [
        [
          {
            "node": "Run result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "pinData": {},
  "settings": {
    "executionOrder": "v1",
    "timezone": "UTC",
    "saveDataErrorExecution": "all",
    "saveDataSuccessExecution": "all",
    "saveManualExecutions": true,
    "executionTimeout": 3600
  },
  "tags": [],
  "meta": {
    "templateCredsSetupCompleted": false
  }
}
