Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement squarespace import source (#65635)

Tom Owers033f449c73a2
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 00e6df0749e9..fd581d713572 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -198,6 +198,7 @@ the row lists both.
| snowflake | DB protocol | snowflake-connector-python | ➖ |
| sparkpost | HTTP | requests | ✅ |
| square | HTTP | requests | ✅ |
+| squarespace | HTTP | requests | ✅ |
| statuspage | HTTP | requests | ✅ |
| stripe | HTTP (vendor SDK) + Webhook | stripe (StripeClient + RequestsClient) + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| supabase | DB protocol | psycopg (delegates to PostgresSource) | ➖ |
@@ -637,7 +638,6 @@ doesn't conflict with concurrent PRs.
- split_io
- spotify_ads
- spotlercrm
-- squarespace
- statsig
- stigg
- stockdata
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 216cd1af009a..1604d0c50e3c 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -2960,7 +2960,7 @@ class SquareSourceConfig(config.Config):
@config.config
class SquarespaceSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/posthog/temporal/data_imports/sources/squarespace/canonical_descriptions.py b/posthog/temporal/data_imports/sources/squarespace/canonical_descriptions.py
new file mode 100644
index 000000000000..9182702e1451
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/squarespace/canonical_descriptions.py
@@ -0,0 +1,106 @@
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
+
+# Descriptions taken from the official Squarespace Commerce + Website API docs.
+# Keyed by the endpoint/schema name returned by `get_schemas`.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "orders": {
+ "description": "Commerce orders placed on the Squarespace store, including totals, "
+ "line items, and fulfillment status.",
+ "docs_url": "https://developers.squarespace.com/commerce-apis/retrieve-all-orders",
+ "columns": {
+ "id": "Unique order id.",
+ "orderNumber": "Human-readable order number shown to the merchant and customer.",
+ "createdOn": "ISO 8601 UTC timestamp of when the order was placed.",
+ "modifiedOn": "ISO 8601 UTC timestamp of when the order was last modified.",
+ "channel": "Sales channel the order was placed through (e.g. web, pos).",
+ "fulfillmentStatus": "Fulfillment state: PENDING, FULFILLED, or CANCELED.",
+ "customerEmail": "Email address of the customer who placed the order.",
+ "customerId": "Identifier of the customer profile, when available.",
+ "grandTotal": "Order total including tax and shipping.",
+ "subtotal": "Order subtotal before tax, shipping, and discounts.",
+ "taxTotal": "Total tax charged on the order.",
+ "shippingTotal": "Total shipping charged on the order.",
+ "discountTotal": "Total discount applied to the order.",
+ "refundedTotal": "Total amount refunded against the order.",
+ "lineItems": "Items purchased in the order.",
+ "billingAddress": "Billing address supplied for the order.",
+ "shippingAddress": "Shipping address supplied for the order.",
+ "testmode": "Whether the order was created in test mode.",
+ },
+ },
+ "products": {
+ "description": "Products in the Squarespace store (physical, service, gift card, and "
+ "digital), including pricing variants and images.",
+ "docs_url": "https://developers.squarespace.com/commerce-apis/retrieve-all-products",
+ "columns": {
+ "id": "Unique product id.",
+ "createdOn": "ISO 8601 UTC timestamp of when the product was created.",
+ "modifiedOn": "ISO 8601 UTC timestamp of when the product was last modified.",
+ "type": "Product type: PHYSICAL, SERVICE, GIFT_CARD, or DIGITAL.",
+ "storePageId": "Identifier of the store page the product belongs to.",
+ "name": "Product name.",
+ "description": "Product description (HTML).",
+ "url": "Public URL of the product.",
+ "urlSlug": "URL slug of the product.",
+ "isVisible": "Whether the product is visible on the storefront.",
+ "tags": "Tags assigned to the product.",
+ "images": "Images associated with the product.",
+ },
+ },
+ "transactions": {
+ "description": "Financial transaction documents for orders and donations, grouping the "
+ "payments, taxes, and totals for each.",
+ "docs_url": "https://developers.squarespace.com/commerce-apis/retrieve-all-transactions",
+ "columns": {
+ "id": "Unique transaction document id.",
+ "createdOn": "ISO 8601 UTC timestamp of when the document was created.",
+ "modifiedOn": "ISO 8601 UTC timestamp of when the document was last modified.",
+ "customerEmail": "Email address of the customer for the transaction.",
+ "salesOrderId": "Identifier of the order this transaction relates to.",
+ "voided": "Whether the transaction was voided.",
+ "total": "Total amount of the transaction.",
+ "totalSales": "Total sales amount.",
+ "totalNetSales": "Net sales amount after discounts.",
+ "totalTaxes": "Total taxes for the transaction.",
+ "totalNetPayment": "Net payment amount received.",
+ "payments": "Individual payments that make up the transaction.",
+ },
+ },
+ "inventory": {
+ "description": "Stock levels per product variant. Inventory is tracked per variant, not per product.",
+ "docs_url": "https://developers.squarespace.com/commerce-apis/retrieve-all-inventory",
+ "columns": {
+ "variantId": "Product variant id; also the unique id of the inventory item.",
+ "sku": "Stock keeping unit (SKU) code assigned by the merchant.",
+ "descriptor": "Human-readable descriptor for the variant.",
+ "quantity": "Current stock quantity available.",
+ "isUnlimited": "Whether the variant has unlimited stock.",
+ },
+ },
+ "store_pages": {
+ "description": "Commerce-enabled store pages on the Squarespace site.",
+ "docs_url": "https://developers.squarespace.com/commerce-apis/retrieve-all-store-pages",
+ "columns": {
+ "id": "Unique store page id.",
+ "title": "Store page title shown on the merchant site.",
+ "isEnabled": "Whether the store page is enabled (accessible to visitors).",
+ "urlSlug": "URL slug of the store page.",
+ },
+ },
+ "profiles": {
+ "description": "Customer profiles on the Squarespace site, including order/donation summary data.",
+ "docs_url": "https://developers.squarespace.com/commerce-apis/retrieve-all-profiles",
+ "columns": {
+ "id": "Unique profile id.",
+ "firstName": "Profile first name.",
+ "lastName": "Profile last name.",
+ "email": "Profile email address.",
+ "hasAccount": "Whether the profile has an account on the website.",
+ "isCustomer": "Whether the profile has any commerce orders or donations.",
+ "createdOn": "ISO 8601 UTC timestamp of when the profile was created.",
+ "acceptsMarketing": "Whether the profile accepts marketing.",
+ "address": "Approximate address derived from existing data (not for shipping/billing).",
+ "transactionsSummary": "Summary of the profile's orders and donations.",
+ },
+ },
+}
diff --git a/posthog/temporal/data_imports/sources/squarespace/settings.py b/posthog/temporal/data_imports/sources/squarespace/settings.py
new file mode 100644
index 000000000000..d037c36cb8be
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/squarespace/settings.py
@@ -0,0 +1,127 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SortMode
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class SquarespaceEndpointConfig:
+ name: str
+ # Per-API version segment of the URL (e.g. "1.0", "v2"). Squarespace versions each
+ # Commerce API independently, so this is per-endpoint, not global.
+ api_version: str
+ path: str
+ # Top-level key in the JSON response holding the list of rows. Differs per endpoint:
+ # orders -> "result", products -> "products", transactions -> "documents", etc.
+ data_key: str
+ primary_keys: list[str]
+ incremental_fields: list[IncrementalField]
+ # Stable datetime field used for partitioning. Must never change for a row
+ # (so `createdOn`, never `modifiedOn`). `None` disables partitioning.
+ partition_key: Optional[str] = None
+ # Whether the endpoint honours the server-side `modifiedAfter`/`modifiedBefore`
+ # time window (which filters on `modifiedOn`). Only set when the API genuinely
+ # filters — this is what enables incremental sync. `None`/False => full refresh.
+ supports_time_filter: bool = False
+ # Order rows arrive in. Squarespace returns the time-filtered list endpoints
+ # newest-modified-first (descending). `desc` is also crash-safe for the watermark:
+ # the pipeline only finalizes the last incremental value at the end of a run.
+ sort_mode: SortMode = "asc"
+ # Static query params applied to the first page only (sort/filter). Cannot be sent
+ # alongside a cursor, so they're dropped once pagination starts.
+ extra_params: dict[str, str] = field(default_factory=dict)
+
+
+def _modified_on_incremental_field() -> list[IncrementalField]:
+ return [
+ {
+ "label": "modifiedOn",
+ "type": IncrementalFieldType.DateTime,
+ "field": "modifiedOn",
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ]
+
+
+# Squarespace Commerce + Website APIs reachable with a single API-key (Bearer) token.
+# Webhook Subscriptions and OAuth-only resources are intentionally excluded — a simple
+# API-key connector cannot manage them.
+SQUARESPACE_ENDPOINTS: dict[str, SquarespaceEndpointConfig] = {
+ # Orders, Products and Transactions expose `modifiedAfter`/`modifiedBefore`, a
+ # server-side filter on `modifiedOn`, so they support incremental sync. The window
+ # params are mutually exclusive with `cursor`, so they apply to the first page only
+ # and pagination continues via the cursor (which preserves the window).
+ "orders": SquarespaceEndpointConfig(
+ name="orders",
+ api_version="1.0",
+ path="/commerce/orders",
+ data_key="result",
+ primary_keys=["id"],
+ partition_key="createdOn",
+ supports_time_filter=True,
+ sort_mode="desc",
+ incremental_fields=_modified_on_incremental_field(),
+ ),
+ "products": SquarespaceEndpointConfig(
+ name="products",
+ api_version="v2",
+ path="/commerce/products",
+ data_key="products",
+ primary_keys=["id"],
+ partition_key="createdOn",
+ supports_time_filter=True,
+ sort_mode="desc",
+ incremental_fields=_modified_on_incremental_field(),
+ ),
+ "transactions": SquarespaceEndpointConfig(
+ name="transactions",
+ api_version="1.0",
+ path="/commerce/transactions",
+ data_key="documents",
+ primary_keys=["id"],
+ partition_key="createdOn",
+ supports_time_filter=True,
+ sort_mode="desc",
+ incremental_fields=_modified_on_incremental_field(),
+ ),
+ # Inventory exposes only the cursor — no time filter and no timestamp fields — so
+ # it's full refresh with no stable partition key. The primary key is the variant id.
+ "inventory": SquarespaceEndpointConfig(
+ name="inventory",
+ api_version="1.0",
+ path="/commerce/inventory",
+ data_key="inventory",
+ primary_keys=["variantId"],
+ incremental_fields=[],
+ ),
+ # Store Pages carry no timestamp fields, so full refresh only.
+ "store_pages": SquarespaceEndpointConfig(
+ name="store_pages",
+ api_version="1.0",
+ path="/commerce/store_pages",
+ data_key="storePages",
+ primary_keys=["id"],
+ incremental_fields=[],
+ ),
+ # Profiles has a `createdOn` (stable partition key) but no `modifiedAfter` filter —
+ # only `sortField`/`sortDirection`/`filter` — so it's full refresh. We sort by
+ # createdOn ascending for stable cursor pagination.
+ "profiles": SquarespaceEndpointConfig(
+ name="profiles",
+ api_version="1.0",
+ path="/profiles",
+ data_key="profiles",
+ primary_keys=["id"],
+ partition_key="createdOn",
+ incremental_fields=[],
+ extra_params={"sortField": "createdOn", "sortDirection": "asc"},
+ ),
+}
+
+ENDPOINTS = tuple(SQUARESPACE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in SQUARESPACE_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/squarespace/source.py b/posthog/temporal/data_imports/sources/squarespace/source.py
index c56176c1dc7e..b39046404882 100644
--- a/posthog/temporal/data_imports/sources/squarespace/source.py
+++ b/posthog/temporal/data_imports/sources/squarespace/source.py
@@ -1,20 +1,33 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import SquarespaceSourceConfig
+from posthog.temporal.data_imports.sources.squarespace.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.squarespace.squarespace import (
+ SquarespaceResumeConfig,
+ squarespace_source,
+ validate_credentials as validate_squarespace_credentials,
+)
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SquarespaceSource(SimpleSource[SquarespaceSourceConfig]):
+class SquarespaceSource(ResumableSource[SquarespaceSourceConfig, SquarespaceResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SQUARESPACE
@@ -25,7 +38,113 @@ class SquarespaceSource(SimpleSource[SquarespaceSourceConfig]):
name=SchemaExternalDataSourceType.SQUARESPACE,
category=DataWarehouseSourceCategory.E_COMMERCE,
label="Squarespace",
+ caption="""Enter a Squarespace API key to pull your Squarespace Commerce data into the PostHog Data warehouse.
+
+Create an **API key** in your Squarespace site under **Settings → Advanced → Developer API Keys**, granting read access to the data you want to sync:
+- **Orders** (orders, transactions)
+- **Products** (products, inventory, store pages)
+- **Profiles** (profiles)
+
+The Commerce APIs (orders, inventory) require the merchant to be on a Commerce plan. Webhook subscriptions are not available with API-key auth, so this source polls on a schedule.""",
iconPath="/static/services/squarespace.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/squarespace",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # A bad/revoked API key surfaces as a 401 when `fetch_page` calls
+ # `raise_for_status()`. Retrying can't fix a credential problem. Match the
+ # stable status text and base host, not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://api.squarespace.com": (
+ "Your Squarespace API key is invalid or has been revoked. Create a new API key in your "
+ "Squarespace developer settings, then reconnect."
+ ),
+ "403 Client Error: Forbidden for url: https://api.squarespace.com": (
+ "Your Squarespace API key (or the site's plan) is missing access needed to sync this data. "
+ "Grant the relevant permission — and ensure the site is on a Commerce plan for orders/inventory — "
+ "then reconnect."
+ ),
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from posthog.temporal.data_imports.sources.squarespace.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: SquarespaceSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=len(INCREMENTAL_FIELDS[endpoint]) > 0,
+ supports_append=len(INCREMENTAL_FIELDS[endpoint]) > 0,
+ incremental_fields=INCREMENTAL_FIELDS[endpoint],
+ )
+ for endpoint in ENDPOINTS
+ ]
+
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+
+ return schemas
+
+ def validate_credentials(
+ self, config: SquarespaceSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ is_valid, is_forbidden = validate_squarespace_credentials(config.api_key, schema_name)
+ if is_valid:
+ return True, None
+
+ # A 403 means the token is genuine but the plan/scope doesn't cover this resource.
+ # Accept that at source-create (schema_name=None) — users may only grant access to
+ # the endpoints they intend to sync — and reject only when validating a schema.
+ if is_forbidden and schema_name is None:
+ return True, None
+
+ if is_forbidden:
+ return False, f"The Squarespace API key is missing the access required to sync '{schema_name}'"
+
+ return False, "Invalid Squarespace API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SquarespaceResumeConfig]:
+ return ResumableSourceManager[SquarespaceResumeConfig](inputs, SquarespaceResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SquarespaceSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SquarespaceResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return squarespace_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/posthog/temporal/data_imports/sources/squarespace/squarespace.py b/posthog/temporal/data_imports/sources/squarespace/squarespace.py
new file mode 100644
index 000000000000..b2e5c650e3f1
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/squarespace/squarespace.py
@@ -0,0 +1,254 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.squarespace.settings import SQUARESPACE_ENDPOINTS, SquarespaceEndpointConfig
+
+SQUARESPACE_BASE_URL = "https://api.squarespace.com"
+
+# Squarespace rate-limits requests with a blank/default User-Agent more aggressively,
+# so a descriptive one is required.
+USER_AGENT = "PostHog-DataWarehouse/1.0 (+https://posthog.com)"
+
+REQUEST_TIMEOUT_SECONDS = 60
+
+# A Squarespace pagination cursor is opaque and dynamic; a resumed or slowly-paginated
+# cursor can be rejected mid-stream. Allow a few restarts so a transient rejection during
+# the re-scan doesn't fail the sync, while still bounding the work.
+MAX_CURSOR_RESTARTS = 3
+
+
+class SquarespaceRetryableError(Exception):
+ pass
+
+
+class SquarespaceInvalidCursorError(Exception):
+ pass
+
+
+class SquarespaceResumeConfig:
+ # The next-page cursor returned by Squarespace. For incremental syncs the cursor
+ # preserves the `modifiedAfter`/`modifiedBefore` window of the original request, so
+ # resuming from it continues the same window. An empty string means "start over"
+ # (merge dedupes the re-pulled rows on the primary key).
+ cursor: str
+
+
+def _is_invalid_cursor_error(response: requests.Response) -> bool:
+ """A 400 whose error payload points at the pagination cursor. Squarespace rejects a
+ cursor that is malformed, expired, or sent alongside other query params."""
+ if response.status_code != 400:
+ return False
+ try:
+ body = response.json()
+ except ValueError:
+ return False
+ subtype = body.get("subtype") or ""
+ message = body.get("message") or ""
+ return "cursor" in subtype.lower() or "cursor" in message.lower()
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_key}",
+ "User-Agent": USER_AGENT,
+ "Accept": "application/json",
+ }
+
+
+def _format_datetime_z(value: Any) -> str:
+ """Format an incremental value as the ISO 8601 UTC string Squarespace expects
+ (YYYY-MM-DDThh:mm:ss.sssZ). Squarespace rejects the +00:00 offset isoformat() emits."""
+ if isinstance(value, datetime):
+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%S.000Z")
+ return str(value)
+
+
+def _clamp_future_value_to_now(value: Any, now: datetime) -> Any:
+ """Cap a future incremental cursor at `now`.
+
+ `modifiedAfter` must be <= `modifiedBefore` (which we set to now), so a future-dated
+ cursor would make Squarespace 400 on an inverted window. Asking for rows newer than now
+ is a no-op anyway, so clamping keeps the request valid and lets the sync self-heal.
+ """
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return now if aware > now else value
+ if isinstance(value, date):
+ return now.date() if value > now.date() else value
+ return value
+
+
+def _build_initial_params(
+ config: SquarespaceEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ modified_before: datetime,
+) -> dict[str, str]:
+ """Query params for the first page. Cursor-based pages drop these — Squarespace
+ rejects a cursor sent alongside any other param."""
+ params: dict[str, str] = dict(config.extra_params)
+
+ if config.supports_time_filter and should_use_incremental_field and db_incremental_field_last_value is not None:
+ last_value = _clamp_future_value_to_now(db_incremental_field_last_value, modified_before)
+ # Squarespace requires modifiedAfter and modifiedBefore together; sending one
+ # without the other is a 400.
+ params["modifiedAfter"] = _format_datetime_z(last_value)
+ params["modifiedBefore"] = _format_datetime_z(modified_before)
+
+ return params
+
+
+def validate_credentials(api_key: str, schema_name: Optional[str] = None) -> tuple[bool, bool]:
+ """Probe Squarespace to confirm the token works.
+
+ Returns ``(is_valid, is_forbidden)``. ``is_forbidden`` distinguishes a 403 (genuine
+ token, but the merchant's plan/scope doesn't grant this resource) from a 401 (bad
+ token) so the caller can accept scope gaps at source-create time but reject them for a
+ specific schema.
+ """
+ config = SQUARESPACE_ENDPOINTS.get(schema_name) if schema_name else None
+ if config is not None:
+ url = f"{SQUARESPACE_BASE_URL}/{config.api_version}{config.path}"
+ else:
+ url = f"{SQUARESPACE_BASE_URL}/1.0/commerce/orders"
+
+ try:
+ response = make_tracked_session().get(url, headers=_get_headers(api_key), timeout=REQUEST_TIMEOUT_SECONDS)
+ except Exception:
+ return False, False
+
+ if response.status_code == 403:
+ return False, True
+
+ return response.status_code == 200, False
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SquarespaceResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = SQUARESPACE_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ url = f"{SQUARESPACE_BASE_URL}/{config.api_version}{config.path}"
+ session = make_tracked_session()
+
+ # Captured once so the window stays stable across pages and restarts. Rows modified
+ # after this point are picked up by the next sync (its window starts at this run's max).
+ modified_before = datetime.now(UTC)
+ initial_params = _build_initial_params(
+ config, should_use_incremental_field, db_incremental_field_last_value, modified_before
+ )
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ cursor: Optional[str] = resume_config.cursor if resume_config and resume_config.cursor else None
+ if cursor:
+ logger.debug(f"Squarespace: resuming {endpoint} from saved cursor")
+
+ @retry(
+ retry=retry_if_exception_type((SquarespaceRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def fetch_page(params: dict[str, str]) -> dict[str, Any]:
+ response = session.get(url, params=params, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise SquarespaceRetryableError(
+ f"Squarespace API error (retryable): status={response.status_code}, url={url}"
+ )
+
+ if _is_invalid_cursor_error(response):
+ raise SquarespaceInvalidCursorError(f"Squarespace rejected the pagination cursor for {endpoint}")
+
+ if not response.ok:
+ logger.error(f"Squarespace API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ restarts_remaining = MAX_CURSOR_RESTARTS
+ while True:
+ # The cursor encodes the original query (including any window), so cursor pages
+ # are requested with the cursor alone — re-sending filters errors.
+ params = {"cursor": cursor} if cursor else initial_params
+ try:
+ data = fetch_page(params)
+ except SquarespaceInvalidCursorError:
+ # A cursor-less initial request can't trigger this, so a rejection there means a
+ # malformed query — surface it. Otherwise restart the stream from the beginning
+ # (merge dedupes on the primary key); the restart budget bounds the work.
+ if cursor is None or restarts_remaining <= 0:
+ raise
+ restarts_remaining -= 1
+ logger.warning(f"Squarespace: cursor for {endpoint} was rejected, restarting stream from the beginning")
+ # Overwrite the stale cursor now so a restart that finishes within a single page
+ # (no fresh cursor to save) doesn't leave the bad value to force a re-scan next sync.
+ resumable_source_manager.save_state(SquarespaceResumeConfig(cursor=""))
+ cursor = None
+ continue
+
+ items = data.get(config.data_key, [])
+ pagination = data.get("pagination") or {}
+ raw_next_cursor = pagination.get("nextPageCursor")
+ next_cursor = str(raw_next_cursor) if raw_next_cursor else None
+ has_next = bool(pagination.get("hasNextPage")) and next_cursor is not None
+
+ if items:
+ yield items
+ # Save state only after yielding, so a crash re-yields the last batch rather
+ # than skipping it (merge dedupes on the primary key).
+ if has_next and next_cursor is not None:
+ resumable_source_manager.save_state(SquarespaceResumeConfig(cursor=next_cursor))
+
+ if not has_next:
+ break
+
+ cursor = next_cursor
+
+
+def squarespace_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SquarespaceResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = SQUARESPACE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ sort_mode=config.sort_mode,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/posthog/temporal/data_imports/sources/squarespace/test_squarespace.py b/posthog/temporal/data_imports/sources/squarespace/test_squarespace.py
new file mode 100644
index 000000000000..e79bbb95bc4d
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/squarespace/test_squarespace.py
@@ -0,0 +1,386 @@
+import json
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+from requests import Response
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.squarespace.settings import SQUARESPACE_ENDPOINTS
+from posthog.temporal.data_imports.sources.squarespace.squarespace import (
+ MAX_CURSOR_RESTARTS,
+ SQUARESPACE_BASE_URL,
+ SquarespaceInvalidCursorError,
+ SquarespaceResumeConfig,
+ _build_initial_params,
+ _clamp_future_value_to_now,
+ _format_datetime_z,
+ _is_invalid_cursor_error,
+ get_rows,
+ validate_credentials,
+)
+
+SQUARESPACE_MODULE = "posthog.temporal.data_imports.sources.squarespace.squarespace"
+
+
+def _make_response(body: dict[str, Any], status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+def _page(data_key: str, items: list[dict[str, Any]], next_cursor: str | None = None) -> Response:
+ pagination = {"hasNextPage": next_cursor is not None, "nextPageCursor": next_cursor, "nextPageUrl": None}
+ return _make_response({data_key: items, "pagination": pagination})
+
+
+class TestFormatDatetimeZ:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000Z"),
+ (
+ "microseconds_truncated",
+ datetime(2026, 1, 15, 10, 30, 45, 123456, tzinfo=UTC),
+ "2026-01-15T10:30:45.123Z",
+ ),
+ ("naive_assumed_utc", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"),
+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00.000Z"),
+ ("string_passthrough", "2026-03-04T02:58:14.000Z", "2026-03-04T02:58:14.000Z"),
+ ]
+ )
+ def test_format(self, _name: str, value: Any, expected: str) -> None:
+ assert _format_datetime_z(value) == expected
+
+ def test_no_plus_offset_in_output(self) -> None:
+ # Squarespace rejects the +00:00 offset; output must use the Z suffix.
+ assert "+00:00" not in _format_datetime_z(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))
+
+
+class TestClampFutureValueToNow:
+ def test_future_datetime_clamped(self) -> None:
+ now = datetime(2026, 6, 1, tzinfo=UTC)
+ assert _clamp_future_value_to_now(datetime(2027, 1, 1, tzinfo=UTC), now) == now
+
+ def test_past_datetime_unchanged(self) -> None:
+ now = datetime(2026, 6, 1, tzinfo=UTC)
+ past = datetime(2025, 1, 1, tzinfo=UTC)
+ assert _clamp_future_value_to_now(past, now) == past
+
+ def test_naive_datetime_treated_as_utc(self) -> None:
+ now = datetime(2026, 6, 1, tzinfo=UTC)
+ assert _clamp_future_value_to_now(datetime(2027, 1, 1), now) == now
+
+
+class TestBuildInitialParams:
+ MODIFIED_BEFORE = datetime(2026, 6, 1, 12, 0, 0, tzinfo=UTC)
+
+ def test_incremental_endpoint_sets_window(self) -> None:
+ params = _build_initial_params(
+ SQUARESPACE_ENDPOINTS["orders"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 5, 1, tzinfo=UTC),
+ modified_before=self.MODIFIED_BEFORE,
+ )
+ # Squarespace requires both window bounds together.
+ assert params["modifiedAfter"] == "2026-05-01T00:00:00.000Z"
+ assert params["modifiedBefore"] == "2026-06-01T12:00:00.000Z"
+ assert "cursor" not in params
+
+ def test_incremental_endpoint_full_refresh_omits_window(self) -> None:
+ params = _build_initial_params(
+ SQUARESPACE_ENDPOINTS["orders"],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ modified_before=self.MODIFIED_BEFORE,
+ )
+ assert params == {}
+
+ def test_first_incremental_sync_without_last_value_omits_window(self) -> None:
+ # supports_incremental but no watermark yet -> scan everything (no window),
+ # otherwise we'd send modifiedBefore without modifiedAfter (a 400).
+ params = _build_initial_params(
+ SQUARESPACE_ENDPOINTS["orders"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ modified_before=self.MODIFIED_BEFORE,
+ )
+ assert "modifiedAfter" not in params
+ assert "modifiedBefore" not in params
+
+ def test_full_refresh_endpoint_never_sets_window(self) -> None:
+ # inventory has no server-side time filter, so even with an incremental value
+ # selected we must not invent a window param.
+ params = _build_initial_params(
+ SQUARESPACE_ENDPOINTS["inventory"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 5, 1, tzinfo=UTC),
+ modified_before=self.MODIFIED_BEFORE,
+ )
+ assert "modifiedAfter" not in params
+ assert "modifiedBefore" not in params
+
+ def test_extra_params_applied_on_first_page(self) -> None:
+ params = _build_initial_params(
+ SQUARESPACE_ENDPOINTS["profiles"],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ modified_before=self.MODIFIED_BEFORE,
+ )
+ assert params == {"sortField": "createdOn", "sortDirection": "asc"}
+
+ def test_future_last_value_clamped_into_window(self) -> None:
+ params = _build_initial_params(
+ SQUARESPACE_ENDPOINTS["orders"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2099, 1, 1, tzinfo=UTC),
+ modified_before=self.MODIFIED_BEFORE,
+ )
+ # modifiedAfter must not exceed modifiedBefore, or Squarespace 400s on an inverted window.
+ assert params["modifiedAfter"] == params["modifiedBefore"]
+
+
+class TestIsInvalidCursorError:
+ @parameterized.expand(
+ [
+ ("cursor_in_message", 400, {"message": "The cursor parameter contains an invalid value"}, True),
+ ("cursor_in_subtype", 400, {"subtype": "INVALID_CURSOR", "message": "bad"}, True),
+ ("unrelated_400", 400, {"message": "modifiedAfter is not a valid ISO 8601 string"}, False),
+ ("empty_400", 400, {}, False),
+ ("not_a_400", 404, {"message": "cursor"}, False),
+ ]
+ )
+ def test_detection(self, _name: str, status_code: int, body: dict[str, Any], expected: bool) -> None:
+ assert _is_invalid_cursor_error(_make_response(body, status_code=status_code)) is expected
+
+ def test_non_json_body_is_not_invalid_cursor(self) -> None:
+ resp = Response()
+ resp.status_code = 400
+ resp._content = b"<html>Bad Request</html>"
+ assert _is_invalid_cursor_error(resp) is False
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, (True, False)),
+ ("unauthorized", 401, (False, False)),
+ ("forbidden", 403, (False, True)),
+ ("server_error", 500, (False, False)),
+ ]
+ )
+ def test_status_code_mapping(self, _name: str, status_code: int, expected: tuple[bool, bool]) -> None:
+ with patch(f"{SQUARESPACE_MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _make_response({}, status_code=status_code)
+ assert validate_credentials("token") == expected
+
+ def test_network_error_returns_invalid(self) -> None:
+ with patch(f"{SQUARESPACE_MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("token") == (False, False)
+
+ def test_no_schema_probes_orders(self) -> None:
+ with patch(f"{SQUARESPACE_MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _make_response({}, status_code=200)
+ validate_credentials("token")
+ url = mock_session.return_value.get.call_args.args[0]
+ assert url == f"{SQUARESPACE_BASE_URL}/1.0/commerce/orders"
+
+ def test_schema_probes_that_endpoint_with_its_version(self) -> None:
+ with patch(f"{SQUARESPACE_MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _make_response({}, status_code=200)
+ validate_credentials("token", schema_name="products")
+ url = mock_session.return_value.get.call_args.args[0]
+ # products is served from the v2 API.
+ assert url == f"{SQUARESPACE_BASE_URL}/v2/commerce/products"
+
+ def test_sends_user_agent_header(self) -> None:
+ with patch(f"{SQUARESPACE_MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _make_response({}, status_code=200)
+ validate_credentials("token")
+ headers = mock_session.return_value.get.call_args.kwargs["headers"]
+ assert headers["User-Agent"]
+ assert headers["Authorization"] == "Bearer token"
+
+
+class TestGetRowsPagination:
+ def _drive(
+ self,
+ endpoint: str,
+ manager: MagicMock,
+ responses: list[Response],
+ **kwargs: Any,
+ ) -> tuple[list[dict[str, Any]], list[list[dict[str, Any]]]]:
+ """Drive get_rows with a mocked session, returning (params sent per page, yielded batches)."""
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_get(_url: str, *, params: dict[str, Any], **_kwargs: Any) -> Response:
+ sent_params.append(dict(params or {}))
+ return next(response_iter)
+
+ with patch(f"{SQUARESPACE_MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = fake_get
+ batches = list(
+ get_rows(
+ api_key="token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager,
+ **kwargs,
+ )
+ )
+ return sent_params, batches
+
+ def test_fresh_run_saves_cursor_after_each_non_terminal_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _page("result", [{"id": "o1"}], next_cursor="cur-1"),
+ _page("result", [{"id": "o2"}], next_cursor="cur-2"),
+ _page("result", [{"id": "o3"}]),
+ ]
+ sent_params, batches = self._drive("orders", manager, responses)
+
+ # First request carries the query params; subsequent pages carry the cursor only.
+ assert "cursor" not in sent_params[0]
+ assert sent_params[1] == {"cursor": "cur-1"}
+ assert sent_params[2] == {"cursor": "cur-2"}
+ assert batches == [[{"id": "o1"}], [{"id": "o2"}], [{"id": "o3"}]]
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [SquarespaceResumeConfig(cursor="cur-1"), SquarespaceResumeConfig(cursor="cur-2")]
+
+ def test_resume_seeds_cursor_from_saved_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = SquarespaceResumeConfig(cursor="cur-resumed")
+
+ sent_params, _ = self._drive("orders", manager, [_page("result", [{"id": "o9"}])])
+
+ assert sent_params == [{"cursor": "cur-resumed"}]
+ manager.load_state.assert_called_once()
+
+ def test_empty_saved_cursor_starts_from_beginning(self) -> None:
+ # An empty cursor (written by a restart) must be treated as "start over", not replayed.
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = SquarespaceResumeConfig(cursor="")
+
+ sent_params, _ = self._drive("orders", manager, [_page("result", [{"id": "o1"}])])
+ assert "cursor" not in sent_params[0]
+
+ def test_terminal_single_page_does_not_save_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ self._drive("orders", manager, [_page("result", [{"id": "only"}])])
+ manager.save_state.assert_not_called()
+
+ def test_does_not_load_state_when_cannot_resume(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ self._drive("orders", manager, [_page("result", [{"id": "a"}])])
+ manager.load_state.assert_not_called()
+
+ def test_terminates_when_has_next_false_even_with_cursor(self) -> None:
+ # hasNextPage=False must stop pagination even if a stray nextPageCursor is present.
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ body = {
+ "result": [{"id": "o1"}],
+ "pagination": {"hasNextPage": False, "nextPageCursor": "should-be-ignored"},
+ }
+ sent_params, _ = self._drive("orders", manager, [_make_response(body)])
+ assert len(sent_params) == 1
+ manager.save_state.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("orders", "result"),
+ ("products", "products"),
+ ("transactions", "documents"),
+ ("inventory", "inventory"),
+ ("store_pages", "storePages"),
+ ("profiles", "profiles"),
+ ]
+ )
+ def test_yields_rows_using_endpoint_data_key(self, endpoint: str, data_key: str) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ _, batches = self._drive(endpoint, manager, [_page(data_key, [{"id": "a"}, {"id": "b"}])])
+ assert batches == [[{"id": "a"}, {"id": "b"}]]
+
+ def test_invalid_cursor_restarts_stream_from_beginning(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = SquarespaceResumeConfig(cursor="stale-cursor")
+
+ responses = [
+ _make_response({"message": "cursor invalid"}, status_code=400),
+ _page("result", [{"id": "o1"}], next_cursor="cur-1"),
+ _page("result", [{"id": "o2"}]),
+ ]
+ sent_params, _ = self._drive("orders", manager, responses)
+
+ assert sent_params[0] == {"cursor": "stale-cursor"}
+ assert "cursor" not in sent_params[1]
+ assert sent_params[2] == {"cursor": "cur-1"}
+
+ def test_invalid_cursor_restart_evicts_stale_cursor(self) -> None:
+ # When the restart finishes within a single page there's no fresh cursor to persist,
+ # so the restart must explicitly overwrite the stale cursor.
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = SquarespaceResumeConfig(cursor="stale-cursor")
+
+ responses = [
+ _make_response({"message": "cursor invalid"}, status_code=400),
+ _page("result", [{"id": "o1"}]),
+ ]
+ self._drive("orders", manager, responses)
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [SquarespaceResumeConfig(cursor="")]
+
+ def test_invalid_cursor_on_initial_request_is_surfaced(self) -> None:
+ # A cursor-less initial request can't trigger cursor expiry, so a cursor-rejection
+ # there is a malformed query — surface it rather than looping forever.
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ with pytest.raises(SquarespaceInvalidCursorError):
+ self._drive("orders", manager, [_make_response({"message": "cursor invalid"}, status_code=400)])
+
+ def test_invalid_cursor_gives_up_after_restart_budget_exhausted(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = SquarespaceResumeConfig(cursor="stale-cursor")
+
+ invalid = _make_response({"message": "cursor invalid"}, status_code=400)
+ responses = [invalid]
+ for _ in range(MAX_CURSOR_RESTARTS):
+ responses.append(_page("result", [{"id": "o"}], next_cursor="cur"))
+ responses.append(invalid)
+ with pytest.raises(SquarespaceInvalidCursorError):
+ self._drive("orders", manager, responses)
+
+ def test_incremental_first_page_sends_window(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ sent_params, _ = self._drive(
+ "orders",
+ manager,
+ [_page("result", [{"id": "o1"}])],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 5, 1, tzinfo=UTC),
+ )
+ assert sent_params[0]["modifiedAfter"] == "2026-05-01T00:00:00.000Z"
+ assert "modifiedBefore" in sent_params[0]
diff --git a/posthog/temporal/data_imports/sources/squarespace/test_squarespace_source.py b/posthog/temporal/data_imports/sources/squarespace/test_squarespace_source.py
new file mode 100644
index 000000000000..87970bb23cd2
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/squarespace/test_squarespace_source.py
@@ -0,0 +1,142 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import SquarespaceSourceConfig
+from posthog.temporal.data_imports.sources.squarespace.settings import ENDPOINTS, SQUARESPACE_ENDPOINTS
+from posthog.temporal.data_imports.sources.squarespace.source import SquarespaceSource
+from posthog.temporal.data_imports.sources.squarespace.squarespace import SquarespaceResumeConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+INCREMENTAL_ENDPOINTS = {"orders", "products", "transactions"}
+
+
+def _make_inputs(**overrides: Any) -> mock.MagicMock:
+ inputs = mock.MagicMock()
+ inputs.schema_name = overrides.get("schema_name", "orders")
+ inputs.should_use_incremental_field = overrides.get("should_use_incremental_field", False)
+ inputs.db_incremental_field_last_value = overrides.get("db_incremental_field_last_value", None)
+ return inputs
+
+
+class TestSquarespaceSource:
+ def setup_method(self) -> None:
+ self.source = SquarespaceSource()
+ self.team_id = 123
+ self.config = SquarespaceSourceConfig(api_key="test-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.SQUARESPACE
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Squarespace"
+ assert config.label == "Squarespace"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # A finished source ships visible — not hidden behind unreleasedSource.
+ assert config.unreleasedSource is not True
+ assert len(config.fields) == 1
+
+ api_key_field = config.fields[0]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+
+ def test_get_schemas_matches_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize("endpoint", sorted(SQUARESPACE_ENDPOINTS))
+ def test_get_schemas_incremental_flags(self, endpoint: str) -> None:
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)
+ expected_incremental = endpoint in INCREMENTAL_ENDPOINTS
+ assert schema.supports_incremental is expected_incremental
+ assert schema.supports_append is expected_incremental
+ if expected_incremental:
+ assert [f["field"] for f in schema.incremental_fields] == ["modifiedOn"]
+ else:
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["orders"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "orders"
+
+ def test_get_schemas_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "expected_key",
+ ["401 Client Error: Unauthorized", "403 Client Error: Forbidden"],
+ )
+ def test_non_retryable_errors(self, expected_key: str) -> None:
+ assert any(expected_key in key for key in self.source.get_non_retryable_errors())
+
+ def test_canonical_descriptions_cover_all_endpoints(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions) == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "mock_return, schema_name, expected_valid, expected_has_message",
+ [
+ ((True, False), None, True, False),
+ ((False, False), None, False, True), # 401 bad token
+ ((False, True), None, True, False), # 403 at source-create -> accepted
+ ((False, True), "orders", False, True), # 403 for a specific schema -> rejected
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.squarespace.source.validate_squarespace_credentials")
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ mock_return: tuple[bool, bool],
+ schema_name: str | None,
+ expected_valid: bool,
+ expected_has_message: bool,
+ ) -> None:
+ mock_validate.return_value = mock_return
+ is_valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
+ assert is_valid is expected_valid
+ assert (message is not None) is expected_has_message
+ mock_validate.assert_called_once_with(self.config.api_key, schema_name)
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is SquarespaceResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.squarespace.source.squarespace_source")
+ def test_source_for_pipeline_passes_arguments(self, mock_squarespace_source: mock.MagicMock) -> None:
+ inputs = _make_inputs(
+ schema_name="transactions",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-01-01T00:00:00Z",
+ )
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ _, kwargs = mock_squarespace_source.call_args
+ assert kwargs["api_key"] == self.config.api_key
+ assert kwargs["endpoint"] == "transactions"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+
+ @mock.patch("posthog.temporal.data_imports.sources.squarespace.source.squarespace_source")
+ def test_source_for_pipeline_drops_last_value_when_not_incremental(
+ self, mock_squarespace_source: mock.MagicMock
+ ) -> None:
+ inputs = _make_inputs(should_use_incremental_field=False, db_incremental_field_last_value="ignored")
+ self.source.source_for_pipeline(self.config, mock.MagicMock(spec=ResumableSourceManager), inputs)
+
+ _, kwargs = mock_squarespace_source.call_args
+ assert kwargs["db_incremental_field_last_value"] is None