@gscdump/sdk 0.26.10 → 0.27.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,40 +1,53 @@
1
1
  import { query_d_exports } from "./_chunks/query.mjs";
2
- import { AddPartnerTeamMemberParams, AnalyticsClient, AnalyticsClient as AnalyticsClient$1, BackfillRange, BackfillResponse, BindPartnerSiteTeamParams, BuilderState, BulkRegisterPartnerSiteResult, BulkRegisterPartnerSitesParams, BulkRegisterPartnerSitesResponse, CANONICAL_WEBHOOK_EVENTS, CanonicalWebhookEventType, CreatePartnerTeamParams, CreateWebhookEnvelopeOptions, DataDetailOptions, DataQueryOptions, DeletePartnerUserResponse, GscComparisonFilter, GscdumpAnalysisParams, GscdumpAnalysisPreset, GscdumpAnalysisResponse, GscdumpAnalysisSourcesResponse, GscdumpAvailableSite, GscdumpCanonicalMismatchesResponse, GscdumpDataDetailResponse, GscdumpDataResponse, GscdumpDataRow, GscdumpDateRangeParams, GscdumpIndexPercentResponse, GscdumpIndexingDiagnosticsResponse, GscdumpIndexingResponse, GscdumpIndexingUrlStatus, GscdumpIndexingUrlsResponse, GscdumpKeywordSparklinesParams, GscdumpKeywordSparklinesResponse, GscdumpMeta, GscdumpPageTrendParams, GscdumpPageTrendResponse, GscdumpPermissionRecovery, GscdumpQueryTrendParams, GscdumpQueryTrendResponse, GscdumpSiteRegistration, GscdumpSitemap, GscdumpSitemapChangesResponse, GscdumpSitemapHistory, GscdumpSitemapsResponse, GscdumpSyncStatusResponse, GscdumpSyncStatusResponse as GscdumpSyncStatusResponse$1, GscdumpTeamMemberRow, GscdumpTeamRow, GscdumpTopAssociationParams, GscdumpTopAssociationResponse, GscdumpTotals, GscdumpUserRegistration, GscdumpUserSettings, GscdumpUserSite, GscdumpUserSite as GscdumpUserSite$1, GscdumpUserStatus, GscdumpUserTokenUpdate, IndexingUrlsParams, InspectionHistoryResponse, InspectionIndex, PartnerClient, PartnerClient as PartnerClient$1, PartnerLifecycleAccount, PartnerLifecycleResponse, PartnerLifecycleResponse as PartnerLifecycleResponse$1, PartnerLifecycleSite, PartnerLifecycleSite as PartnerLifecycleSite$1, PartnerRealtimeEvent, PartnerRealtimeEvent as PartnerRealtimeEvent$1, PartnerRealtimeEventType, PartnerRealtimeMessage, PartnerRealtimeMessage as PartnerRealtimeMessage$1, PartnerWebhookData, PartnerWebhookHeaders, PartnerWebhookHeaders as PartnerWebhookHeaders$1, RealtimeAuthFailedEvent, RealtimeAuthRequiredMessage, RealtimeConnectedMessage, RealtimeEnrichmentCompleteEvent, RealtimeErrorMessage, RealtimeJobFailedEvent, RealtimeNeedsReauthEvent, RealtimePongMessage, RealtimeSiteAddedEvent, RealtimeSiteRemovedEvent, RealtimeSubscribedMessage, RealtimeSyncCompleteEvent, RealtimeSyncFailedEvent, RealtimeSyncJobCompleteEvent, RealtimeSyncProgressEvent, RealtimeSyncSiteCompleteEvent, RegisterPartnerSiteParams, RegisterPartnerUserParams, RollupEnvelope, UpdatePartnerUserTokensParams, VALID_WEBHOOK_EVENTS, WEBHOOK_CONTRACT_VERSION, WEBHOOK_CONTRACT_VERSION_HEADER, WEBHOOK_DELIVERY_HEADER, WEBHOOK_EVENT_HEADER, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_TIMESTAMP_HEADER, WebhookEnvelope, WebhookEnvelope as WebhookEnvelope$1, WebhookEventType, WhoamiResponse } from "@gscdump/contracts";
3
2
  import { Result } from "gscdump/result";
4
- import { BuilderState as BuilderState$1, Dimension, Metric, SearchType } from "gscdump/query";
3
+ import { AddPartnerTeamMemberParams, AnalyticsClient, AnalyticsClient as AnalyticsClient$1, BackfillRange, BackfillResponse, BindPartnerSiteTeamParams, BuilderState, BulkRegisterPartnerSiteResult, BulkRegisterPartnerSitesParams, BulkRegisterPartnerSitesResponse, CANONICAL_WEBHOOK_EVENTS, CanonicalWebhookEventType, CreatePartnerTeamParams, CreateWebhookEnvelopeOptions, DataDetailOptions, DataQueryOptions, DeletePartnerUserResponse, GscComparisonFilter, GscdumpAnalysisParams, GscdumpAnalysisPreset, GscdumpAnalysisResponse, GscdumpAnalysisSourcesResponse, GscdumpAvailableSite, GscdumpCanonicalMismatchesResponse, GscdumpDataDetailResponse, GscdumpDataResponse, GscdumpDataRow, GscdumpDateRangeParams, GscdumpIndexPercentResponse, GscdumpIndexingDiagnosticsResponse, GscdumpIndexingResponse, GscdumpIndexingUrlStatus, GscdumpIndexingUrlsResponse, GscdumpKeywordSparklinesParams, GscdumpKeywordSparklinesResponse, GscdumpMeta, GscdumpPageTrendParams, GscdumpPageTrendResponse, GscdumpPermissionRecovery, GscdumpQueryTrendParams, GscdumpQueryTrendResponse, GscdumpSiteRegistration, GscdumpSitemap, GscdumpSitemapChangesResponse, GscdumpSitemapHistory, GscdumpSitemapsResponse, GscdumpSyncStatusResponse, GscdumpSyncStatusResponse as GscdumpSyncStatusResponse$1, GscdumpTeamMemberRow, GscdumpTeamRow, GscdumpTopAssociationParams, GscdumpTopAssociationResponse, GscdumpTotals, GscdumpUserRegistration, GscdumpUserSettings, GscdumpUserSite, GscdumpUserSite as GscdumpUserSite$1, GscdumpUserStatus, GscdumpUserTokenUpdate, IndexingUrlsParams, InspectionHistoryResponse, InspectionIndex, PartnerClient, PartnerClient as PartnerClient$1, PartnerLifecycleAccount, PartnerLifecycleResponse, PartnerLifecycleResponse as PartnerLifecycleResponse$1, PartnerLifecycleSite, PartnerLifecycleSite as PartnerLifecycleSite$1, PartnerRealtimeEvent, PartnerRealtimeEvent as PartnerRealtimeEvent$1, PartnerRealtimeEventType, PartnerRealtimeMessage, PartnerRealtimeMessage as PartnerRealtimeMessage$1, PartnerWebhookData, PartnerWebhookHeaders, PartnerWebhookHeaders as PartnerWebhookHeaders$1, RealtimeAuthFailedEvent, RealtimeAuthRequiredMessage, RealtimeConnectedMessage, RealtimeEnrichmentCompleteEvent, RealtimeErrorMessage, RealtimeJobFailedEvent, RealtimeNeedsReauthEvent, RealtimePongMessage, RealtimeSiteAddedEvent, RealtimeSiteRemovedEvent, RealtimeSubscribedMessage, RealtimeSyncCompleteEvent, RealtimeSyncFailedEvent, RealtimeSyncJobCompleteEvent, RealtimeSyncProgressEvent, RealtimeSyncSiteCompleteEvent, RegisterPartnerSiteParams, RegisterPartnerUserParams, RollupEnvelope, UpdatePartnerUserTokensParams, VALID_WEBHOOK_EVENTS, WEBHOOK_CONTRACT_VERSION, WEBHOOK_CONTRACT_VERSION_HEADER, WEBHOOK_DELIVERY_HEADER, WEBHOOK_EVENT_HEADER, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_TIMESTAMP_HEADER, WebhookEnvelope, WebhookEnvelope as WebhookEnvelope$1, WebhookEventType, WhoamiResponse } from "@gscdump/contracts";
5
4
  import { ActionSource } from "@gscdump/analysis";
6
5
  import { AnalysisTool } from "@gscdump/engine/analysis-types";
7
6
  export * from "@gscdump/contracts";
8
- type PartnerFetch = <T = unknown>(request: string, options?: PartnerFetchOptions) => Promise<T>;
9
- type PartnerHeaders = HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
10
- interface PartnerFetchOptions {
7
+ type PartnerErrorKind = 'auth' | 'rate-limit' | 'provisioning' | 'permission' | 'network' | 'validation' | 'not-found' | 'server' | 'unknown';
8
+ interface PartnerErrorInfo {
9
+ kind: PartnerErrorKind;
10
+ statusCode?: number;
11
+ message: string;
12
+ data?: unknown;
13
+ }
14
+ declare class PartnerApiError extends Error {
15
+ readonly kind: PartnerErrorKind;
16
+ readonly statusCode?: number;
17
+ readonly data?: unknown;
18
+ constructor(info: PartnerErrorInfo);
19
+ }
20
+ declare function toPartnerError(error: unknown): PartnerApiError;
21
+ /** Narrow an unknown error to the modelled `PartnerApiError`. */
22
+ declare function isPartnerError(error: unknown): error is PartnerApiError;
23
+ /** Human-readable, log-friendly rendering of a modelled partner failure. */
24
+ declare function formatPartnerError(error: PartnerApiError): string;
25
+ /**
26
+ * Re-raise a modelled `PartnerApiError` as itself. The error variant of every
27
+ * `*Result` core already IS the throwable `PartnerApiError`, so the throwing
28
+ * wrappers preserve the exact identity/message existing call sites and tests
29
+ * assert (`rejects.toThrow(PartnerApiError)`, `toThrow('Invalid webhook signature')`).
30
+ */
31
+ declare function partnerErrorToException(error: PartnerApiError): PartnerApiError;
32
+ type HostedFetch = <T = unknown>(request: string, options?: HostedFetchOptions) => Promise<T>;
33
+ type HostedHeaders = HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
34
+ interface HostedFetchOptions {
11
35
  method?: string;
12
36
  headers?: HeadersInit;
13
37
  query?: Record<string, unknown>;
14
38
  body?: unknown;
15
39
  [key: string]: unknown;
16
40
  }
17
- interface PartnerClientOptions {
18
- /**
19
- * Origin API base. Use `/api` for same-origin Nitro routes, or pass a full
20
- * remote origin base from the host app. The client has no baked-in origin.
21
- */
41
+ interface HostedClientOptions {
22
42
  apiBase?: string;
23
- /** Convenience auth hook. Equivalent to supplying `headers: { 'x-api-key': apiKey }`. */
24
- apiKey?: string;
25
- /** Any ofetch-compatible instance: global `$fetch`, `useGscFetch()`, or a custom test fake. */
26
- fetch?: PartnerFetch;
27
- /** Static or lazy headers. Lazy headers are resolved on every operation. */
28
- headers?: PartnerHeaders;
29
- /** Validate request payloads and response bodies with exported Zod schemas. */
43
+ fetch?: HostedFetch;
44
+ headers?: HostedHeaders;
30
45
  validate?: boolean | 'request' | 'response';
31
46
  }
32
- declare function createPartnerClient(options?: PartnerClientOptions): PartnerClient$1;
33
- declare const createGscdumpClient: typeof createPartnerClient;
34
- type AnalyticsFetch = PartnerFetch;
35
- type AnalyticsHeaders = PartnerHeaders;
36
- type AnalyticsFetchOptions = PartnerFetchOptions;
37
- interface AnalyticsClientOptions {
47
+ type AnalyticsFetch = HostedFetch;
48
+ type AnalyticsHeaders = HostedHeaders;
49
+ type AnalyticsFetchOptions = HostedFetchOptions;
50
+ interface AnalyticsClientOptions extends HostedClientOptions {
38
51
  apiBase?: string;
39
52
  fetch?: AnalyticsFetch;
40
53
  headers?: AnalyticsHeaders;
@@ -116,234 +129,27 @@ interface DailyAnonInput {
116
129
  anonymizedImpressionsPct: number;
117
130
  }
118
131
  declare function weightedAnonPct(days: readonly DailyAnonInput[] | null | undefined, window?: number): number | null;
119
- /** The archetype identifiers. */
120
- type QueryArchetype = 'site-daily-timeseries' | 'entity-daily-timeseries' | 'entity-daily-sparkline' | 'top-n-breakdown' | 'single-row-lookup' | 'multi-series-stacked-daily' | 'two-dimension-detail' | 'arbitrary-sql' | 'aux-cloud-only';
121
- /**
122
- * Where an archetype can run.
123
- * - `r2-sql` — expressible in R2 SQL directly (plain GROUP BY + aggregate).
124
- * - `r2-sql-resolved` — R2-SQL-expressible only AFTER the resolver pre-resolves
125
- * entity selections to a literal `IN` list (no `FROM`
126
- * subquery in R2 SQL). Archetypes 2, 3, 4.
127
- * - `duckdb` — needs window functions / `QUALIFY` / `COUNT(DISTINCT)` /
128
- * `OFFSET`; server tail must use DuckDB-over-Iceberg-files.
129
- * - `cloud-only` — not an Iceberg query (aux data: canonicals, sitemaps,
130
- * indexing). Always served by the existing cloud endpoints.
131
- */
132
- type ArchetypeExecutionClass = 'r2-sql' | 'r2-sql-resolved' | 'duckdb' | 'cloud-only';
133
- /** Static execution-class tag per archetype. The server-tail router reads this. */
134
- declare const ARCHETYPE_EXECUTION_CLASS: Record<QueryArchetype, ArchetypeExecutionClass>;
135
- /** Date window every archetype query is scoped to. */
136
- interface DateRange {
137
- /** `YYYY-MM-DD` inclusive. */
138
- start: string;
139
- /** `YYYY-MM-DD` inclusive. */
140
- end: string;
141
- }
142
- /**
143
- * A post-window predicate layered onto an archetype's `WHERE` clause, on top of
144
- * the site/searchType/date partition. The cross-cutting facet mechanism behind
145
- * the dashboard's Country/Device/Brand filters:
146
- * - `eq` — exact column match (e.g. `country = 'ind'`, `device = 'MOBILE'`).
147
- * - `regex` — case-insensitive regex on a text column, e.g. brand
148
- * classification on `query`. DuckDB `regexp_matches(LOWER(col), …)`.
149
- * - `notRegex` — its negation (non-brand traffic).
150
- *
151
- * `regex`/`notRegex` require DuckDB execution — R2 SQL has no regex — so the
152
- * router escalates any query carrying one to the `duckdb` class.
153
- */
154
- interface ArchetypeFacet {
155
- column: Dimension;
156
- op: 'eq' | 'regex' | 'notRegex';
157
- value: string;
158
- }
159
- /** Fields common to every archetype query input. */
160
- interface ArchetypeQueryBase {
161
- archetype: QueryArchetype;
162
- siteId: string;
163
- searchType: SearchType;
164
- range: DateRange;
165
- /**
166
- * Optional prior window for YoY / period-over-period comparison. Widest
167
- * supported total span is ~24 months (12-month period + YoY).
168
- */
169
- compareRange?: DateRange;
132
+ import * as import__gscdump_contracts_archetypes from "@gscdump/contracts/archetypes";
133
+ type PartnerFetch = HostedFetch;
134
+ type PartnerHeaders = HostedHeaders;
135
+ type PartnerFetchOptions = HostedFetchOptions;
136
+ interface PartnerClientOptions extends HostedClientOptions {
170
137
  /**
171
- * Cross-cutting Country/Device/Brand filters applied as extra `WHERE`
172
- * predicates. Applied by `top-n-breakdown` and the daily-timeseries
173
- * archetypes; ignored by fully-specified shapes (`single-row-lookup`).
174
- */
175
- facets?: readonly ArchetypeFacet[];
176
- }
177
- /**
178
- * Whole-site metrics grouped by date. Reads `dates`, the authoritative daily
179
- * total table (site totals + anonymized impressions + device pivot).
180
- * R2 SQL: `GROUP BY date`.
181
- */
182
- interface SiteDailyTimeseriesQuery extends ArchetypeQueryBase {
183
- archetype: 'site-daily-timeseries';
184
- metrics: readonly Metric[];
185
- }
186
- /**
187
- * Daily metrics for ONE resolved entity (a page or query). The resolver must
188
- * resolve `entity.value` to a literal before hitting R2 SQL.
189
- */
190
- interface EntityDailyTimeseriesQuery extends ArchetypeQueryBase {
191
- archetype: 'entity-daily-timeseries';
192
- entity: {
193
- dimension: Extract<Dimension, 'page' | 'query'>;
194
- value: string;
195
- };
196
- metrics: readonly Metric[];
197
- }
198
- /**
199
- * Compact daily series for the top-N entities at once (sparkline column in a
200
- * table). Resolver pre-resolves the top-N entity list to a literal `IN`.
201
- */
202
- interface EntityDailySparklineQuery extends ArchetypeQueryBase {
203
- archetype: 'entity-daily-sparkline';
204
- dimension: Extract<Dimension, 'page' | 'query' | 'queryCanonical'>;
205
- /** Entity values already resolved by the resolver layer. */
206
- entities: readonly string[];
207
- /** Single metric the sparkline plots. */
208
- metric: Metric;
209
- }
210
- /**
211
- * Ranked breakdown over one dimension. `GROUP BY` + `ORDER BY` + `LIMIT`.
212
- * Device breakdowns read the wide `dates` table and unpivot its device columns
213
- * (`clicks_desktop`, `impressions_mobile`, etc.) at query time.
214
- * `offset` pagination is UNVERIFIED in R2 SQL (POC) — when set, the router
215
- * may escalate to `duckdb`.
216
- */
217
- interface TopNBreakdownQuery extends ArchetypeQueryBase {
218
- archetype: 'top-n-breakdown';
219
- dimension: Dimension;
220
- metrics: readonly Metric[];
221
- /** Sort column + direction. */
222
- orderBy: {
223
- metric: Metric;
224
- dir: 'asc' | 'desc';
225
- };
226
- limit: number;
227
- /** Pagination offset. Non-zero may force `duckdb` execution. */
228
- offset?: number;
229
- /**
230
- * Request the full unwindowed group count (`meta.totalRows`) so paginated /
231
- * load-more tables know how many rows exist beyond the current `limit`.
232
- * Computed as `COUNT(*) OVER()` over the grouped result, which requires a
233
- * window function — so a query with `includeTotal` is escalated to `duckdb`
234
- * on the server tail (R2 SQL cannot express it). Not honoured for the
235
- * `device` dimension, which has at most a handful of rows.
236
- */
237
- includeTotal?: boolean;
238
- /**
239
- * Movers mode — re-rank the breakdown by period-over-period movement instead
240
- * of by `orderBy`. Requires `compareRange` (the previous-period CTE supplies
241
- * the deltas); ignored without it. Forces `duckdb` on the server tail (CTE +
242
- * FULL OUTER JOIN). Used by the dashboard's Growing/Declining/New/Lost lists.
243
- * - `improving` — clicks gained vs previous, largest gain first.
244
- * - `declining` — clicks lost vs previous, largest drop first.
245
- * - `new` — impressions appeared (zero previously), by current volume.
246
- * - `lost` — impressions disappeared (zero now), by previous volume.
138
+ * Origin API base. Use `/api` for same-origin Nitro routes, or pass a full
139
+ * remote origin base from the host app. The client has no baked-in origin.
247
140
  */
248
- movers?: 'improving' | 'declining' | 'new' | 'lost';
249
- }
250
- /** One aggregated row for a fully-specified filter. `WHERE` + `GROUP BY`. */
251
- interface SingleRowLookupQuery extends ArchetypeQueryBase {
252
- archetype: 'single-row-lookup';
253
- /** Exact dimension-value filters identifying the row. */
254
- match: Partial<Record<Dimension, string>>;
255
- metrics: readonly Metric[];
256
- }
257
- /**
258
- * Daily metrics split by a secondary dimension. `GROUP BY date, <dim>`.
259
- * Device split charts read `dates` and unpivot the wide device columns.
260
- */
261
- interface MultiSeriesStackedDailyQuery extends ArchetypeQueryBase {
262
- archetype: 'multi-series-stacked-daily';
263
- /** The series dimension, e.g. `device` or `country`. */
264
- seriesDimension: Dimension;
265
- metric: Metric;
266
- }
267
- /**
268
- * The whale archetype — `page_queries` grouped by `(url, query)`. The query ×
269
- * page cross no longer reads the retired `page_keywords` table name. This is
270
- * the reason the server tail exists. R2-SQL-expressible
271
- * (`GROUP BY url, query`).
272
- */
273
- interface TwoDimensionDetailQuery extends ArchetypeQueryBase {
274
- archetype: 'two-dimension-detail';
275
- metrics: readonly Metric[];
276
- /** Optional page or query prefilter to narrow the cross. */
277
- filter?: {
278
- page?: string;
279
- query?: string;
280
- };
281
- orderBy?: {
282
- metric: Metric;
283
- dir: 'asc' | 'desc';
284
- };
285
- limit?: number;
286
- }
287
- /**
288
- * Escape hatch — caller-supplied SQL (moving averages, ranks, window
289
- * functions). ALWAYS `duckdb` on the server tail; R2 SQL cannot express it.
290
- * In the browser, runs against the attached DuckDB-WASM views directly.
291
- */
292
- interface ArbitrarySqlQuery extends ArchetypeQueryBase {
293
- archetype: 'arbitrary-sql';
294
- /** SQL referencing the attached table views by their `IcebergTableName`. */
295
- sql: string;
296
- params?: readonly unknown[];
297
- }
298
- /**
299
- * Non-fact-table data: canonicals, sitemaps, indexing status. Not an Iceberg
300
- * query — served by the existing cloud endpoints. Present in the union so the
301
- * archetype router can recognise and route it without a special case.
302
- */
303
- interface AuxCloudOnlyQuery {
304
- archetype: 'aux-cloud-only';
305
- siteId: string;
306
- /** Which aux dataset. */
307
- dataset: 'canonicals' | 'sitemaps' | 'indexing';
308
- params?: Record<string, unknown>;
309
- }
310
- /** Discriminated union of every archetype query input. */
311
- type ArchetypeQuery = SiteDailyTimeseriesQuery | EntityDailyTimeseriesQuery | EntityDailySparklineQuery | TopNBreakdownQuery | SingleRowLookupQuery | MultiSeriesStackedDailyQuery | TwoDimensionDetailQuery | ArbitrarySqlQuery | AuxCloudOnlyQuery;
312
- /** A single result row — dimension values plus metric values, all flat. */
313
- type ArchetypeResultRow = Record<string, string | number | null>;
314
- /** Where the result was actually computed (for diagnostics + UX). */
315
- type ArchetypeResultSource = 'browser' | 'server-r2-sql' | 'server-duckdb' | 'cloud';
316
- /** Uniform result envelope returned for any archetype. */
317
- interface ArchetypeResult<R extends ArchetypeResultRow = ArchetypeResultRow> {
318
- archetype: QueryArchetype;
319
- rows: R[];
320
- source: ArchetypeResultSource;
321
- meta?: {
322
- rowCount: number;
323
- queryMs: number;
324
- /**
325
- * Full unwindowed group count for a `top-n-breakdown` requested with
326
- * `includeTotal`. Independent of `limit`/`offset`; lets paginated tables
327
- * show "X of Y" and stop loading. Undefined when not requested.
328
- */
329
- totalRows?: number; /** Set when `compareRange` was supplied — the comparison-period rows. */
330
- compareRows?: R[];
331
- truncated?: boolean;
332
- };
333
- }
334
- /**
335
- * Bridge: an archetype query also carries (or resolves to) a `BuilderState`,
336
- * so the existing query-resolver / `buildLogicalPlan` path stays the executor.
337
- * The resolver layer attaches this. Implementation agents: DO NOT bypass
338
- * `BuilderState` — the archetype is the typed front door, `BuilderState` the
339
- * shared backend.
340
- */
341
- interface ResolvedArchetypeQuery {
342
- query: ArchetypeQuery;
343
- /** Undefined only for `aux-cloud-only`, which has no `BuilderState`. */
344
- builder?: BuilderState$1;
345
- executionClass: ArchetypeExecutionClass;
141
+ apiBase?: string;
142
+ /** Convenience auth hook. Equivalent to supplying `headers: { 'x-api-key': apiKey }`. */
143
+ apiKey?: string;
144
+ /** Any ofetch-compatible instance: global `$fetch`, `useGscFetch()`, or a custom test fake. */
145
+ fetch?: PartnerFetch;
146
+ /** Static or lazy headers. Lazy headers are resolved on every operation. */
147
+ headers?: PartnerHeaders;
148
+ /** Validate request payloads and response bodies with exported Zod schemas. */
149
+ validate?: boolean | 'request' | 'response';
346
150
  }
151
+ declare function createPartnerClient(options?: PartnerClientOptions): PartnerClient$1;
152
+ declare const createGscdumpClient: typeof createPartnerClient;
347
153
  declare const COUNTRY_NAMES: Record<string, string>;
348
154
  declare const countryName: (code: string) => string;
349
155
  declare const CWV_GOOD_LCP = 2500;
@@ -366,31 +172,6 @@ declare function splitOpportunityTitle(title: string): Array<{
366
172
  text: string;
367
173
  highlight: boolean;
368
174
  }>;
369
- type PartnerErrorKind = 'auth' | 'rate-limit' | 'provisioning' | 'permission' | 'network' | 'validation' | 'not-found' | 'server' | 'unknown';
370
- interface PartnerErrorInfo {
371
- kind: PartnerErrorKind;
372
- statusCode?: number;
373
- message: string;
374
- data?: unknown;
375
- }
376
- declare class PartnerApiError extends Error {
377
- readonly kind: PartnerErrorKind;
378
- readonly statusCode?: number;
379
- readonly data?: unknown;
380
- constructor(info: PartnerErrorInfo);
381
- }
382
- declare function toPartnerError(error: unknown): PartnerApiError;
383
- /** Narrow an unknown error to the modelled `PartnerApiError`. */
384
- declare function isPartnerError(error: unknown): error is PartnerApiError;
385
- /** Human-readable, log-friendly rendering of a modelled partner failure. */
386
- declare function formatPartnerError(error: PartnerApiError): string;
387
- /**
388
- * Re-raise a modelled `PartnerApiError` as itself. The error variant of every
389
- * `*Result` core already IS the throwable `PartnerApiError`, so the throwing
390
- * wrappers preserve the exact identity/message existing call sites and tests
391
- * assert (`rejects.toThrow(PartnerApiError)`, `toThrow('Invalid webhook signature')`).
392
- */
393
- declare function partnerErrorToException(error: PartnerApiError): PartnerApiError;
394
175
  interface GscConsoleUrlOpts {
395
176
  /** The GSC property — either `sc-domain:example.com` or a URL-prefix. */
396
177
  siteLabel: string;
@@ -929,4 +710,24 @@ declare function parseWebhookPayload<TData extends Record<string, unknown> = Rec
929
710
  validateSignature?: boolean;
930
711
  }): Promise<WebhookEnvelope$1<TData>>;
931
712
  declare function readWebhookHeaders(headers: Headers | PartnerWebhookHeaders$1 | null | undefined): Required<PartnerWebhookHeaders$1>;
713
+ type ARCHETYPE_EXECUTION_CLASS = import__gscdump_contracts_archetypes.ARCHETYPE_EXECUTION_CLASS;
714
+ type ArbitrarySqlQuery = import__gscdump_contracts_archetypes.ArbitrarySqlQuery;
715
+ type ArchetypeExecutionClass = import__gscdump_contracts_archetypes.ArchetypeExecutionClass;
716
+ type ArchetypeFacet = import__gscdump_contracts_archetypes.ArchetypeFacet;
717
+ type ArchetypeQuery = import__gscdump_contracts_archetypes.ArchetypeQuery;
718
+ type ArchetypeQueryBase = import__gscdump_contracts_archetypes.ArchetypeQueryBase;
719
+ type ArchetypeResult = import__gscdump_contracts_archetypes.ArchetypeResult;
720
+ type ArchetypeResultRow = import__gscdump_contracts_archetypes.ArchetypeResultRow;
721
+ type ArchetypeResultSource = import__gscdump_contracts_archetypes.ArchetypeResultSource;
722
+ type AuxCloudOnlyQuery = import__gscdump_contracts_archetypes.AuxCloudOnlyQuery;
723
+ type DateRange = import__gscdump_contracts_archetypes.DateRange;
724
+ type EntityDailySparklineQuery = import__gscdump_contracts_archetypes.EntityDailySparklineQuery;
725
+ type EntityDailyTimeseriesQuery = import__gscdump_contracts_archetypes.EntityDailyTimeseriesQuery;
726
+ type MultiSeriesStackedDailyQuery = import__gscdump_contracts_archetypes.MultiSeriesStackedDailyQuery;
727
+ type QueryArchetype = import__gscdump_contracts_archetypes.QueryArchetype;
728
+ type ResolvedArchetypeQuery = import__gscdump_contracts_archetypes.ResolvedArchetypeQuery;
729
+ type SingleRowLookupQuery = import__gscdump_contracts_archetypes.SingleRowLookupQuery;
730
+ type SiteDailyTimeseriesQuery = import__gscdump_contracts_archetypes.SiteDailyTimeseriesQuery;
731
+ type TopNBreakdownQuery = import__gscdump_contracts_archetypes.TopNBreakdownQuery;
732
+ type TwoDimensionDetailQuery = import__gscdump_contracts_archetypes.TwoDimensionDetailQuery;
932
733
  export { ARCHETYPE_EXECUTION_CLASS, type AddPartnerTeamMemberParams, type AnalyticsClient, type AnalyticsClientOptions, type AnalyticsFetch, type AnalyticsFetchOptions, type AnalyticsHeaders, type ArbitrarySqlQuery, type ArchetypeExecutionClass, type ArchetypeFacet, type ArchetypeQuery, type ArchetypeQueryBase, type ArchetypeResult, type ArchetypeResultRow, type ArchetypeResultSource, type AuxCloudOnlyQuery, type BackfillRange, type BackfillResponse, type BindPartnerSiteTeamParams, type BuilderState, type BulkRegisterPartnerSiteResult, type BulkRegisterPartnerSitesParams, type BulkRegisterPartnerSitesResponse, CANONICAL_WEBHOOK_EVENTS, COMPARE_OPTIONS, COUNTRY_NAMES, CWV_GOOD_CLS, CWV_GOOD_INP, CWV_GOOD_LCP, CWV_POOR_CLS, CWV_POOR_INP, CWV_POOR_LCP, type CalendarPeriod, type CanonicalDailyRow, type CanonicalWebhookEventType, type ClassifySearchConsoleStageInput, type CompareMode, type CreatePartnerTeamParams, type CreateWebhookEnvelopeOptions, type CustomPeriod, type CwvBucket, type DailyAnonInput, type DataDetailOptions, type DataQueryOptions, type DateRange, type DateRangeResult, type DeletePartnerUserResponse, type EntityDailySparklineQuery, type EntityDailyTimeseriesQuery, GSC_COLUMN_OPTIONS, GSC_PERIOD_OPTIONS, GSC_PERIOD_OPTIONS_LONG, GSC_STABLE_LATENCY_DAYS, type GscAnalyzerAccent, type GscAnalyzerCapabilities, type GscAnalyzerCapability, type GscAnalyzerDefinition, type GscAnalyzerDefinitionWithCapability, type GscAnalyzerInsightCard, type GscAnalyzerKind, type GscAnalyzerPanelResult, type GscAnalyzerPanelSpec, type GscAnalyzerStatTile, type GscClassifiedError, type GscColumn, type GscColumnOption, type GscComparisonFilter, type GscConsoleUrlOpts, type GscDailySummary, type GscErrorStatus, type GscRowTotals, type GscdumpAnalysisParams, type GscdumpAnalysisPreset, type GscdumpAnalysisResponse, type GscdumpAnalysisSourcesResponse, type GscdumpAvailableSite, type GscdumpCanonicalMismatchesResponse, type GscdumpDataDetailResponse, type GscdumpDataResponse, type GscdumpDataRow, type GscdumpDateRangeParams, type GscdumpIndexPercentResponse, type GscdumpIndexingDiagnosticsResponse, type GscdumpIndexingResponse, type GscdumpIndexingUrlStatus, type GscdumpIndexingUrlsResponse, type GscdumpKeywordSparklinesParams, type GscdumpKeywordSparklinesResponse, type GscdumpMeta, type GscdumpPageTrendParams, type GscdumpPageTrendResponse, type GscdumpPermissionRecovery, type GscdumpQueryTrendParams, type GscdumpQueryTrendResponse, type GscdumpSiteRegistration, type GscdumpSitemap, type GscdumpSitemapChangesResponse, type GscdumpSitemapHistory, type GscdumpSitemapsResponse, type GscdumpSyncStatusResponse, type GscdumpTeamMemberRow, type GscdumpTeamRow, type GscdumpTopAssociationParams, type GscdumpTopAssociationResponse, type GscdumpTotals, type GscdumpUserRegistration, type GscdumpUserSettings, type GscdumpUserSite, type GscdumpUserStatus, type GscdumpUserTokenUpdate, type HealthStage, type HealthVerdict, type IndexingIssue, type IndexingIssueDetail, type IndexingUrlsParams, type InspectionHistoryResponse, type InspectionIndex, type IssueGroup, type IssueSeverity, type MultiSeriesStackedDailyQuery, PERIOD_PRESETS, PartnerApiError, type PartnerClient, type PartnerClientOptions, type PartnerErrorInfo, type PartnerErrorKind, type PartnerFetch, type PartnerFetchOptions, type PartnerHeaders, type PartnerLifecycleAccount, type PartnerLifecycleResponse, type PartnerLifecycleSite, type PartnerRealtimeClient, type PartnerRealtimeEvent, type PartnerRealtimeEventType, type PartnerRealtimeHandler, type PartnerRealtimeMessage, type PartnerRealtimeOptions, type PartnerRealtimeScope, type PartnerRealtimeStatus, type PartnerWebSocketConstructor, type PartnerWebSocketLike, type PartnerWebhookData, type PartnerWebhookHeaders, type PeerBaselineInput, type PeerConfidence, type PeerStanding, type Period, type PeriodPreset, type QueryArchetype, type RawDailyRow, type ReachStage, type ReachVerdict, type RealtimeAuthFailedEvent, type RealtimeAuthRequiredMessage, type RealtimeConnectedMessage, type RealtimeEnrichmentCompleteEvent, type RealtimeErrorMessage, type RealtimeJobFailedEvent, type RealtimeNeedsReauthEvent, type RealtimePongMessage, type RealtimeSiteAddedEvent, type RealtimeSiteRemovedEvent, type RealtimeSubscribedMessage, type RealtimeSyncCompleteEvent, type RealtimeSyncFailedEvent, type RealtimeSyncJobCompleteEvent, type RealtimeSyncProgressEvent, type RealtimeSyncSiteCompleteEvent, type RegisterPartnerSiteParams, type RegisterPartnerUserParams, type ResolvedArchetypeQuery, type RollingPeriod, type RollupEnvelope, SITE_TYPE_BASELINE, type SearchConsoleStage, type SearchConsoleStageEvidence, type SearchConsoleStageIssue, type SearchConsoleStageKey, type SearchConsoleStagePage, type SearchConsoleStageSeverity, type SearchConsoleStageSitemap, type SearchConsoleStageSummary, type SearchConsoleStageTrajectory, type SingleRowLookupQuery, type SiteBaseline, type SiteDailyTimeseriesQuery, type SiteTriage, type SiteTriageInput, type SiteType, type SiteTypeBaseline, type TopNBreakdownQuery, type TriageEvidence, type TwoDimensionDetailQuery, type UpdatePartnerUserTokensParams, VALID_WEBHOOK_EVENTS, WEBHOOK_CONTRACT_VERSION, WEBHOOK_CONTRACT_VERSION_HEADER, WEBHOOK_DELIVERY_HEADER, WEBHOOK_EVENT_HEADER, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_TIMESTAMP_HEADER, type WebhookEnvelope, type WebhookEventType, type WhoamiResponse, analyticsStatusToSyncStatus, andFilter, classifyGscError, classifyHealthStage, classifyReachStage, classifySearchConsoleStage, classifySiteTriage, coerceRowMetrics, compareRange, countryName, coverageLabel, coverageLabels, createAnalyticsClient, createGscdumpClient, createGscdumpRealtimeClient, createPartnerClient, createPartnerRealtimeClient, cwvBucket, dateFilter, defineGscAnalyzer, derivePeerStanding, deriveSiteBaseline, enrichIssueDetails, findLifecycleSite, formatPartnerError, getGscUnstableCutoffDate, gscConsoleUrl, investigationStatusConfig, isCustomPeriod, isPartnerError, issueDetails, issueGroups, issueTypeToGroup, lifecycleSiteToSyncStatus, lifecycleSiteToUserSite, normalizeSiteType, nuxtSeoTips, parseCustomPeriod, parseWebhookPayload, parseWebhookPayloadResult, partnerErrorToException, periodToDateRange, periodToDays, positionFor, reachLivenessRatio, readWebhookHeaders, serializeWebhookPayload, severityOrder, siteTypeBaseline, siteUrlToHostname, splitOpportunityTitle, summarizeDailyRows, toPartnerError, truncateQuery, verifyWebhookSignature, weightedAnonPct };
package/dist/index.mjs CHANGED
@@ -1,9 +1,12 @@
1
+ import { __exportAll, __reExport } from "./_chunks/chunk.mjs";
1
2
  import { query_exports } from "./query.mjs";
2
- import { CANONICAL_WEBHOOK_EVENTS, VALID_WEBHOOK_EVENTS, WEBHOOK_CONTRACT_VERSION, WEBHOOK_CONTRACT_VERSION_HEADER, WEBHOOK_CONTRACT_VERSION_HEADER as WEBHOOK_CONTRACT_VERSION_HEADER$1, WEBHOOK_DELIVERY_HEADER, WEBHOOK_DELIVERY_HEADER as WEBHOOK_DELIVERY_HEADER$1, WEBHOOK_EVENT_HEADER, WEBHOOK_EVENT_HEADER as WEBHOOK_EVENT_HEADER$1, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_SIGNATURE_HEADER as WEBHOOK_SIGNATURE_HEADER$1, WEBHOOK_TIMESTAMP_HEADER, WEBHOOK_TIMESTAMP_HEADER as WEBHOOK_TIMESTAMP_HEADER$1, analyticsRoutes, partnerEndpointSchemas, partnerRoutes, partnerWebhookEnvelopeSchema } from "@gscdump/contracts";
3
+ import { analyticsEndpointSchemas, analyticsRoutes } from "@gscdump/contracts/analytics";
3
4
  import { err, ok, unwrapResult } from "gscdump/result";
4
5
  import { ofetch } from "ofetch";
6
+ import { partnerEndpointSchemas, partnerRoutes } from "@gscdump/contracts/partner";
5
7
  import { resolveWindow } from "@gscdump/engine/period";
6
8
  import { endOfMonth, format, startOfMonth, startOfQuarter, startOfWeek, subDays, subMonths } from "date-fns";
9
+ import { CANONICAL_WEBHOOK_EVENTS, VALID_WEBHOOK_EVENTS, WEBHOOK_CONTRACT_VERSION, WEBHOOK_CONTRACT_VERSION_HEADER, WEBHOOK_CONTRACT_VERSION_HEADER as WEBHOOK_CONTRACT_VERSION_HEADER$1, WEBHOOK_DELIVERY_HEADER, WEBHOOK_DELIVERY_HEADER as WEBHOOK_DELIVERY_HEADER$1, WEBHOOK_EVENT_HEADER, WEBHOOK_EVENT_HEADER as WEBHOOK_EVENT_HEADER$1, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_SIGNATURE_HEADER as WEBHOOK_SIGNATURE_HEADER$1, WEBHOOK_TIMESTAMP_HEADER, WEBHOOK_TIMESTAMP_HEADER as WEBHOOK_TIMESTAMP_HEADER$1, partnerWebhookEnvelopeSchema } from "@gscdump/contracts";
7
10
  export * from "@gscdump/contracts";
8
11
  var PartnerApiError = class extends Error {
9
12
  kind;
@@ -58,30 +61,56 @@ function formatPartnerError(error) {
58
61
  function partnerErrorToException(error) {
59
62
  return error;
60
63
  }
61
- const TRAILING_SLASH_RE$2 = /\/+$/;
62
- const LEADING_SLASH_RE$1 = /^\/+/;
63
- const DEFAULT_SEARCH_TYPE$1 = "web";
64
- function trimApiBase$1(apiBase) {
65
- return (apiBase ?? "").replace(TRAILING_SLASH_RE$2, "");
64
+ const TRAILING_SLASH_RE$1 = /\/+$/;
65
+ const LEADING_SLASH_RE = /^\/+/;
66
+ function trimApiBase(apiBase, fallback) {
67
+ return (apiBase ?? fallback).replace(TRAILING_SLASH_RE$1, "");
66
68
  }
67
- function buildPath$1(apiBase, path) {
69
+ function buildPath(apiBase, path) {
68
70
  if (!apiBase) return path.startsWith("/") ? path : `/${path}`;
69
- return `${apiBase}/${path.replace(LEADING_SLASH_RE$1, "")}`;
71
+ return `${apiBase}/${path.replace(LEADING_SLASH_RE, "")}`;
70
72
  }
71
- function mergeHeaders$1(base, extra) {
73
+ function mergeHeaders(base, extra) {
72
74
  const headers = new Headers(base);
73
75
  if (extra) for (const [key, value] of new Headers(extra).entries()) headers.set(key, value);
74
76
  return headers;
75
77
  }
76
- async function resolveHeaders$1(options) {
77
- return typeof options.headers === "function" ? await options.headers() : options.headers;
78
+ async function resolveHeaders(options) {
79
+ const resolved = typeof options.headers === "function" ? await options.headers() : options.headers;
80
+ if (!options.apiKey) return resolved;
81
+ return mergeHeaders(resolved, { "x-api-key": options.apiKey });
78
82
  }
79
- function shouldValidate$1(options, phase) {
83
+ function shouldValidate(options, phase) {
80
84
  return options.validate === true || options.validate === phase;
81
85
  }
82
- function parseWith$1(schema, value) {
86
+ function parseWith(schema, value) {
83
87
  return schema ? schema.parse(value) : value;
84
88
  }
89
+ function createHostedRequester(options, defaults) {
90
+ const fetchImpl = options.fetch ?? ofetch;
91
+ const apiBase = trimApiBase(options.apiBase, defaults.apiBase);
92
+ async function requestResult(path, init = {}, responseSchema) {
93
+ const headers = mergeHeaders(await resolveHeaders(options), init.headers);
94
+ try {
95
+ const out = await fetchImpl(buildPath(apiBase, path), {
96
+ ...init,
97
+ headers
98
+ });
99
+ return ok(shouldValidate(options, "response") ? parseWith(responseSchema, out) : out);
100
+ } catch (error) {
101
+ return err(toPartnerError(error));
102
+ }
103
+ }
104
+ async function request(path, init = {}, responseSchema) {
105
+ return unwrapResult(await requestResult(path, init, responseSchema), partnerErrorToException);
106
+ }
107
+ return {
108
+ request,
109
+ requestResult,
110
+ shouldValidate: (phase) => shouldValidate(options, phase)
111
+ };
112
+ }
113
+ const DEFAULT_SEARCH_TYPE$1 = "web";
85
114
  function isAnalysisSourcesOptions$1(value) {
86
115
  return !!value && typeof value === "object" && !Array.isArray(value);
87
116
  }
@@ -129,35 +158,19 @@ function indexingUrlsQuery$1(params = {}) {
129
158
  return query;
130
159
  }
131
160
  function createAnalyticsClient(options = {}) {
132
- const fetchImpl = options.fetch ?? ofetch;
133
- const apiBase = trimApiBase$1(options.apiBase);
134
- async function requestResult(path, init = {}, responseSchema) {
135
- const headers = mergeHeaders$1(await resolveHeaders$1(options), init.headers);
136
- try {
137
- const out = await fetchImpl(buildPath$1(apiBase, path), {
138
- ...init,
139
- headers
140
- });
141
- return ok(shouldValidate$1(options, "response") ? parseWith$1(responseSchema, out) : out);
142
- } catch (error) {
143
- return err(toPartnerError(error));
144
- }
145
- }
146
- async function request(path, init = {}, responseSchema) {
147
- return unwrapResult(await requestResult(path, init, responseSchema), partnerErrorToException);
148
- }
161
+ const { request, shouldValidate } = createHostedRequester(options, { apiBase: "" });
149
162
  return {
150
163
  whoami() {
151
- return request(analyticsRoutes.whoami, {}, partnerEndpointSchemas.analyticsWhoami.response);
164
+ return request(analyticsRoutes.whoami, {}, analyticsEndpointSchemas.analyticsWhoami.response);
152
165
  },
153
166
  listSites() {
154
- return request(analyticsRoutes.sites, {}, partnerEndpointSchemas.analyticsSites.response);
167
+ return request(analyticsRoutes.sites, {}, analyticsEndpointSchemas.analyticsSites.response);
155
168
  },
156
169
  getSourceInfo(siteId, options) {
157
- return request(analyticsRoutes.site.sourceInfo(siteId), { query: sourceInfoQuery(options) }, partnerEndpointSchemas.analyticsSourceInfo.response);
170
+ return request(analyticsRoutes.site.sourceInfo(siteId), { query: sourceInfoQuery(options) }, analyticsEndpointSchemas.analyticsSourceInfo.response);
158
171
  },
159
172
  getAnalysisSources(siteId, tables, options) {
160
- return request(analyticsRoutes.site.analysisSources(siteId), { query: tablesQuery$1(tables, options) }, partnerEndpointSchemas.analyticsAnalysisSources.response);
173
+ return request(analyticsRoutes.site.analysisSources(siteId), { query: tablesQuery$1(tables, options) }, analyticsEndpointSchemas.analyticsAnalysisSources.response);
161
174
  },
162
175
  analyze(siteId, params) {
163
176
  return request(analyticsRoutes.site.analyze(siteId), {
@@ -169,51 +182,51 @@ function createAnalyticsClient(options = {}) {
169
182
  return request(analyticsRoutes.site.rows(siteId), {
170
183
  method: "POST",
171
184
  body: withDefaultSearchType$1(state)
172
- }, partnerEndpointSchemas.analyticsRows.response);
185
+ }, analyticsEndpointSchemas.analyticsRows.response);
173
186
  },
174
187
  getRollup(siteId, rollupId, params) {
175
- return request(analyticsRoutes.site.rollup(siteId, rollupId), { query: params }, partnerEndpointSchemas.analyticsRollup.response);
188
+ return request(analyticsRoutes.site.rollup(siteId, rollupId), { query: params }, analyticsEndpointSchemas.analyticsRollup.response);
176
189
  },
177
190
  requestBackfill(siteId, range) {
178
- const body = shouldValidate$1(options, "request") ? partnerEndpointSchemas.analyticsBackfill.body.parse(range) : range;
191
+ const body = shouldValidate("request") ? analyticsEndpointSchemas.analyticsBackfill.body.parse(range) : range;
179
192
  return request(analyticsRoutes.site.backfill(siteId), {
180
193
  method: "POST",
181
194
  body
182
- }, partnerEndpointSchemas.analyticsBackfill.response);
195
+ }, analyticsEndpointSchemas.analyticsBackfill.response);
183
196
  },
184
197
  getSitemaps(siteId) {
185
- return request(analyticsRoutes.site.sitemaps(siteId), {}, partnerEndpointSchemas.analyticsSitemaps.response);
198
+ return request(analyticsRoutes.site.sitemaps(siteId), {}, analyticsEndpointSchemas.analyticsSitemaps.response);
186
199
  },
187
200
  getSitemapHistory(siteId, hash) {
188
- return request(analyticsRoutes.site.sitemapHistory(siteId, hash), {}, partnerEndpointSchemas.analyticsSitemapHistory.response);
201
+ return request(analyticsRoutes.site.sitemapHistory(siteId, hash), {}, analyticsEndpointSchemas.analyticsSitemapHistory.response);
189
202
  },
190
203
  getSitemapChanges(siteId, params = {}) {
191
- return request(analyticsRoutes.site.sitemapChanges(siteId), { query: params }, partnerEndpointSchemas.analyticsSitemapChanges.response);
204
+ return request(analyticsRoutes.site.sitemapChanges(siteId), { query: params }, analyticsEndpointSchemas.analyticsSitemapChanges.response);
192
205
  },
193
206
  getInspections(siteId) {
194
- return request(analyticsRoutes.site.inspections(siteId), {}, partnerEndpointSchemas.analyticsInspections.response);
207
+ return request(analyticsRoutes.site.inspections(siteId), {}, analyticsEndpointSchemas.analyticsInspections.response);
195
208
  },
196
209
  getInspectionHistory(siteId, hash) {
197
- return request(analyticsRoutes.site.inspectionHistory(siteId, hash), {}, partnerEndpointSchemas.analyticsInspectionHistory.response);
210
+ return request(analyticsRoutes.site.inspectionHistory(siteId, hash), {}, analyticsEndpointSchemas.analyticsInspectionHistory.response);
198
211
  },
199
212
  getIndexingUrls(siteId, params = {}) {
200
- return request(analyticsRoutes.site.indexingUrls(siteId), { query: indexingUrlsQuery$1(params) }, partnerEndpointSchemas.analyticsIndexingUrls.response);
213
+ return request(analyticsRoutes.site.indexingUrls(siteId), { query: indexingUrlsQuery$1(params) }, analyticsEndpointSchemas.analyticsIndexingUrls.response);
201
214
  },
202
215
  getIndexingDiagnostics(siteId) {
203
- return request(analyticsRoutes.site.indexingDiagnostics(siteId), {}, partnerEndpointSchemas.analyticsIndexingDiagnostics.response);
216
+ return request(analyticsRoutes.site.indexingDiagnostics(siteId), {}, analyticsEndpointSchemas.analyticsIndexingDiagnostics.response);
204
217
  },
205
218
  requestIndexingInspect(siteId, body) {
206
- const parsed = shouldValidate$1(options, "request") ? partnerEndpointSchemas.analyticsIndexingInspect.body.parse(body) : body;
219
+ const parsed = shouldValidate("request") ? analyticsEndpointSchemas.analyticsIndexingInspect.body.parse(body) : body;
207
220
  return request(analyticsRoutes.site.indexingInspect(siteId), {
208
221
  method: "POST",
209
222
  body: parsed
210
- }, partnerEndpointSchemas.analyticsIndexingInspect.response);
223
+ }, analyticsEndpointSchemas.analyticsIndexingInspect.response);
211
224
  },
212
225
  getCountries(siteId, range) {
213
- return request(analyticsRoutes.site.countries(siteId), { query: range }, partnerEndpointSchemas.analyticsCountries.response);
226
+ return request(analyticsRoutes.site.countries(siteId), { query: range }, analyticsEndpointSchemas.analyticsCountries.response);
214
227
  },
215
228
  getSearchAppearance(siteId, range) {
216
- return request(analyticsRoutes.site.searchAppearance(siteId), { query: range }, partnerEndpointSchemas.analyticsSearchAppearance.response);
229
+ return request(analyticsRoutes.site.searchAppearance(siteId), { query: range }, analyticsEndpointSchemas.analyticsSearchAppearance.response);
217
230
  }
218
231
  };
219
232
  }
@@ -231,17 +244,9 @@ function weightedAnonPct(days, window = 28) {
231
244
  }
232
245
  return totalImpressions > 0 ? weighted / totalImpressions : null;
233
246
  }
234
- const ARCHETYPE_EXECUTION_CLASS = {
235
- "site-daily-timeseries": "r2-sql",
236
- "entity-daily-timeseries": "r2-sql-resolved",
237
- "entity-daily-sparkline": "r2-sql-resolved",
238
- "top-n-breakdown": "r2-sql-resolved",
239
- "single-row-lookup": "r2-sql",
240
- "multi-series-stacked-daily": "r2-sql",
241
- "two-dimension-detail": "r2-sql",
242
- "arbitrary-sql": "duckdb",
243
- "aux-cloud-only": "cloud-only"
244
- };
247
+ var archetypes_exports = /* @__PURE__ */ __exportAll({});
248
+ import * as import__gscdump_contracts_archetypes from "@gscdump/contracts/archetypes";
249
+ __reExport(archetypes_exports, import__gscdump_contracts_archetypes);
245
250
  function normalizeLifecycleUrl(url) {
246
251
  return (url || "").replace(/^sc-domain:/, "").replace(/^https?:\/\//, "").replace(/^www\./, "").replace(/\/$/, "").toLowerCase();
247
252
  }
@@ -325,26 +330,7 @@ function findLifecycleSite(lifecycle, siteIdOrPropertyUrl) {
325
330
  const propertyKey = normalizeGscPropertyKey(siteIdOrPropertyUrl);
326
331
  return lifecycle.sites.find((site) => site.siteId === siteIdOrPropertyUrl || site.externalSiteId === siteIdOrPropertyUrl || !!propertyKey && normalizeGscPropertyKey(site.gscPropertyUrl) === propertyKey || !site.gscPropertyUrl && normalizeLifecycleUrl(site.requestedUrl) === normalized || !propertyKey && normalizeLifecycleUrl(site.requestedUrl) === normalized) ?? null;
327
332
  }
328
- const TRAILING_SLASH_RE$1 = /\/+$/;
329
- const LEADING_SLASH_RE = /^\/+/;
330
333
  const DEFAULT_SEARCH_TYPE = "web";
331
- function trimApiBase(apiBase) {
332
- return (apiBase ?? "/api").replace(TRAILING_SLASH_RE$1, "");
333
- }
334
- function buildPath(apiBase, path) {
335
- if (!apiBase) return `/${path.replace(LEADING_SLASH_RE, "")}`;
336
- return `${apiBase}/${path.replace(LEADING_SLASH_RE, "")}`;
337
- }
338
- function mergeHeaders(base, extra) {
339
- const headers = new Headers(base);
340
- if (extra) for (const [key, value] of new Headers(extra).entries()) headers.set(key, value);
341
- return headers;
342
- }
343
- async function resolveHeaders(options) {
344
- const resolved = typeof options.headers === "function" ? await options.headers() : options.headers;
345
- if (!options.apiKey) return resolved;
346
- return mergeHeaders(resolved, { "x-api-key": options.apiKey });
347
- }
348
334
  function withDefaultSearchType(state, searchType) {
349
335
  const scoped = state;
350
336
  return {
@@ -452,33 +438,11 @@ function pageTrendQuery(params) {
452
438
  if (params.prevEndDate) query.prevEndDate = params.prevEndDate;
453
439
  return query;
454
440
  }
455
- function shouldValidate(options, phase) {
456
- return options.validate === true || options.validate === phase;
457
- }
458
- function parseWith(schema, value) {
459
- return schema ? schema.parse(value) : value;
460
- }
461
441
  function sleep(ms) {
462
442
  return new Promise((resolve) => setTimeout(resolve, ms));
463
443
  }
464
444
  function createPartnerClient(options = {}) {
465
- const fetchImpl = options.fetch ?? ofetch;
466
- const apiBase = trimApiBase(options.apiBase);
467
- async function requestResult(path, init = {}, responseSchema) {
468
- const headers = mergeHeaders(await resolveHeaders(options), init.headers);
469
- try {
470
- const out = await fetchImpl(buildPath(apiBase, path), {
471
- ...init,
472
- headers
473
- });
474
- return ok(shouldValidate(options, "response") ? parseWith(responseSchema, out) : out);
475
- } catch (error) {
476
- return err(toPartnerError(error));
477
- }
478
- }
479
- async function request(path, init = {}, responseSchema) {
480
- return unwrapResult(await requestResult(path, init, responseSchema), partnerErrorToException);
481
- }
445
+ const { request, requestResult, shouldValidate } = createHostedRequester(options, { apiBase: "/api" });
482
446
  async function waitForUserReadyResult(userId, waitOptions = {}) {
483
447
  const attempts = waitOptions.attempts ?? 12;
484
448
  const intervalMs = waitOptions.intervalMs ?? 1e3;
@@ -551,14 +515,14 @@ function createPartnerClient(options = {}) {
551
515
  }
552
516
  return {
553
517
  registerUser(params) {
554
- const body = shouldValidate(options, "request") ? partnerEndpointSchemas.registerUser.body.parse(params) : params;
518
+ const body = shouldValidate("request") ? partnerEndpointSchemas.registerUser.body.parse(params) : params;
555
519
  return request(partnerRoutes.users.register, {
556
520
  method: "POST",
557
521
  body
558
522
  }, partnerEndpointSchemas.registerUser.response);
559
523
  },
560
524
  updateUserTokens(userId, params) {
561
- const body = shouldValidate(options, "request") ? partnerEndpointSchemas.updateUserTokens.body.parse(params) : params;
525
+ const body = shouldValidate("request") ? partnerEndpointSchemas.updateUserTokens.body.parse(params) : params;
562
526
  return request(partnerRoutes.users.tokens(userId), {
563
527
  method: "PATCH",
564
528
  body
@@ -583,14 +547,14 @@ function createPartnerClient(options = {}) {
583
547
  return request(partnerRoutes.users.availableSites(userId), {}, partnerEndpointSchemas.getAvailableSites.response);
584
548
  },
585
549
  registerSite(params) {
586
- const body = shouldValidate(options, "request") ? partnerEndpointSchemas.registerSite.body.parse(params) : params;
550
+ const body = shouldValidate("request") ? partnerEndpointSchemas.registerSite.body.parse(params) : params;
587
551
  return request(partnerRoutes.partner.sites.register, {
588
552
  method: "POST",
589
553
  body
590
554
  }, partnerEndpointSchemas.registerSite.response);
591
555
  },
592
556
  bulkRegisterSites(params) {
593
- const body = shouldValidate(options, "request") ? partnerEndpointSchemas.bulkRegisterSites.body.parse(params) : params;
557
+ const body = shouldValidate("request") ? partnerEndpointSchemas.bulkRegisterSites.body.parse(params) : params;
594
558
  return request(partnerRoutes.partner.sites.bulkRegister, {
595
559
  method: "POST",
596
560
  body
@@ -609,14 +573,14 @@ function createPartnerClient(options = {}) {
609
573
  return unwrapResult(await getSiteSyncStatusResult(siteId, userId), partnerErrorToException);
610
574
  },
611
575
  getData(siteId, state, queryOptions) {
612
- if (shouldValidate(options, "request")) {
576
+ if (shouldValidate("request")) {
613
577
  partnerEndpointSchemas.getData.state.parse(state);
614
578
  partnerEndpointSchemas.getData.options.parse(queryOptions);
615
579
  }
616
580
  return request(partnerRoutes.sites.data(siteId), { query: dataQuery(state, queryOptions) }, partnerEndpointSchemas.getData.response);
617
581
  },
618
582
  getDataDetail(siteId, state, queryOptions) {
619
- if (shouldValidate(options, "request")) {
583
+ if (shouldValidate("request")) {
620
584
  partnerEndpointSchemas.getDataDetail.state.parse(state);
621
585
  partnerEndpointSchemas.getDataDetail.options.parse(queryOptions);
622
586
  }
@@ -624,7 +588,7 @@ function createPartnerClient(options = {}) {
624
588
  },
625
589
  getAnalysis(siteId, params) {
626
590
  assertAnalysisParams(params);
627
- const query = shouldValidate(options, "request") ? partnerEndpointSchemas.getAnalysis.query.parse(params) : params;
591
+ const query = shouldValidate("request") ? partnerEndpointSchemas.getAnalysis.query.parse(params) : params;
628
592
  return request(partnerRoutes.sites.analysis(siteId), { query: analysisQuery(query) }, partnerEndpointSchemas.getAnalysis.response);
629
593
  },
630
594
  getSitemaps(siteId) {
@@ -652,14 +616,14 @@ function createPartnerClient(options = {}) {
652
616
  return request(partnerRoutes.sites.indexing(siteId), { query: { days } }, partnerEndpointSchemas.getIndexing.response);
653
617
  },
654
618
  getIndexingUrls(siteId, params = {}) {
655
- const parsed = shouldValidate(options, "request") ? partnerEndpointSchemas.getIndexingUrls.query.parse(params) : params;
619
+ const parsed = shouldValidate("request") ? partnerEndpointSchemas.getIndexingUrls.query.parse(params) : params;
656
620
  return request(partnerRoutes.sites.indexingUrls(siteId), { query: indexingUrlsQuery(parsed) }, partnerEndpointSchemas.getIndexingUrls.response);
657
621
  },
658
622
  getIndexingDiagnostics(siteId) {
659
623
  return request(partnerRoutes.sites.indexingDiagnostics(siteId), {}, partnerEndpointSchemas.getIndexingDiagnostics.response);
660
624
  },
661
625
  requestIndexingInspect(siteId, body) {
662
- const parsed = shouldValidate(options, "request") ? partnerEndpointSchemas.getIndexingInspect.body.parse(body) : body;
626
+ const parsed = shouldValidate("request") ? partnerEndpointSchemas.getIndexingInspect.body.parse(body) : body;
663
627
  return request(partnerRoutes.sites.indexingInspect(siteId), {
664
628
  method: "POST",
665
629
  body: parsed
@@ -669,7 +633,7 @@ function createPartnerClient(options = {}) {
669
633
  return request(partnerRoutes.settings.user, {}, partnerEndpointSchemas.getUserSettings.response);
670
634
  },
671
635
  patchUserSettings(body) {
672
- const parsed = shouldValidate(options, "request") ? partnerEndpointSchemas.patchUserSettings.body.parse(body) : body;
636
+ const parsed = shouldValidate("request") ? partnerEndpointSchemas.patchUserSettings.body.parse(body) : body;
673
637
  return request(partnerRoutes.settings.user, {
674
638
  method: "PATCH",
675
639
  body: parsed
@@ -679,7 +643,7 @@ function createPartnerClient(options = {}) {
679
643
  return request(partnerRoutes.sites.recoverPermission(siteId), { method: "POST" }, partnerEndpointSchemas.recoverPermission.response);
680
644
  },
681
645
  getTopAssociation(siteId, params) {
682
- const query = shouldValidate(options, "request") ? partnerEndpointSchemas.getTopAssociation.query.parse(params) : params;
646
+ const query = shouldValidate("request") ? partnerEndpointSchemas.getTopAssociation.query.parse(params) : params;
683
647
  return request(partnerRoutes.sites.topAssociation(siteId), { query }, partnerEndpointSchemas.getTopAssociation.response);
684
648
  },
685
649
  getKeywordSparklines(siteId, params) {
@@ -687,18 +651,18 @@ function createPartnerClient(options = {}) {
687
651
  ...params,
688
652
  searchType: params.searchType ?? DEFAULT_SEARCH_TYPE
689
653
  };
690
- const body = shouldValidate(options, "request") ? partnerEndpointSchemas.getKeywordSparklines.body.parse(withSearchType) : withSearchType;
654
+ const body = shouldValidate("request") ? partnerEndpointSchemas.getKeywordSparklines.body.parse(withSearchType) : withSearchType;
691
655
  return request(partnerRoutes.sites.keywordSparklines(siteId), {
692
656
  method: "POST",
693
657
  body
694
658
  }, partnerEndpointSchemas.getKeywordSparklines.response);
695
659
  },
696
660
  getQueryTrend(siteId, params) {
697
- const query = shouldValidate(options, "request") ? partnerEndpointSchemas.getQueryTrend.query.parse(params) : params;
661
+ const query = shouldValidate("request") ? partnerEndpointSchemas.getQueryTrend.query.parse(params) : params;
698
662
  return request(partnerRoutes.sites.queryTrend(siteId), { query: queryTrendQuery(query) }, partnerEndpointSchemas.getQueryTrend.response);
699
663
  },
700
664
  getPageTrend(siteId, params) {
701
- const query = shouldValidate(options, "request") ? partnerEndpointSchemas.getPageTrend.query.parse(params) : params;
665
+ const query = shouldValidate("request") ? partnerEndpointSchemas.getPageTrend.query.parse(params) : params;
702
666
  return request(partnerRoutes.sites.pageTrend(siteId), { query: pageTrendQuery(query) }, partnerEndpointSchemas.getPageTrend.response);
703
667
  },
704
668
  getCanonicalMismatches(siteId) {
@@ -708,31 +672,31 @@ function createPartnerClient(options = {}) {
708
672
  return request(partnerRoutes.sites.contentVelocity(siteId), { query: days == null ? void 0 : { days } });
709
673
  },
710
674
  getCtrCurve(siteId, params) {
711
- const query = shouldValidate(options, "request") ? partnerEndpointSchemas.getDateRangeInsight.query.parse(params) : params;
675
+ const query = shouldValidate("request") ? partnerEndpointSchemas.getDateRangeInsight.query.parse(params) : params;
712
676
  return request(partnerRoutes.sites.ctrCurve(siteId), { query: dateRangeQuery(query) });
713
677
  },
714
678
  getDarkTraffic(siteId, params) {
715
- const query = shouldValidate(options, "request") ? partnerEndpointSchemas.getDateRangeInsight.query.parse(params) : params;
679
+ const query = shouldValidate("request") ? partnerEndpointSchemas.getDateRangeInsight.query.parse(params) : params;
716
680
  return request(partnerRoutes.sites.darkTraffic(siteId), { query: dateRangeQuery(query) });
717
681
  },
718
682
  getDeviceGap(siteId, params) {
719
- const query = shouldValidate(options, "request") ? partnerEndpointSchemas.getDateRangeInsight.query.parse(params) : params;
683
+ const query = shouldValidate("request") ? partnerEndpointSchemas.getDateRangeInsight.query.parse(params) : params;
720
684
  return request(partnerRoutes.sites.deviceGap(siteId), { query: dateRangeQuery(query) });
721
685
  },
722
686
  getIndexPercent(siteId, params = {}) {
723
- const query = shouldValidate(options, "request") ? partnerEndpointSchemas.getIndexPercent.query.parse(params) : params;
687
+ const query = shouldValidate("request") ? partnerEndpointSchemas.getIndexPercent.query.parse(params) : params;
724
688
  return request(partnerRoutes.sites.indexPercent(siteId), { query }, partnerEndpointSchemas.getIndexPercent.response);
725
689
  },
726
690
  getKeywordBreadth(siteId, params) {
727
- const query = shouldValidate(options, "request") ? partnerEndpointSchemas.getDateRangeInsight.query.parse(params) : params;
691
+ const query = shouldValidate("request") ? partnerEndpointSchemas.getDateRangeInsight.query.parse(params) : params;
728
692
  return request(partnerRoutes.sites.keywordBreadth(siteId), { query: dateRangeQuery(query) });
729
693
  },
730
694
  getPositionDistribution(siteId, params) {
731
- const query = shouldValidate(options, "request") ? partnerEndpointSchemas.getDateRangeInsight.query.parse(params) : params;
695
+ const query = shouldValidate("request") ? partnerEndpointSchemas.getDateRangeInsight.query.parse(params) : params;
732
696
  return request(partnerRoutes.sites.positionDistribution(siteId), { query: dateRangeQuery(query) });
733
697
  },
734
698
  createTeam(params) {
735
- const body = shouldValidate(options, "request") ? partnerEndpointSchemas.createTeam.body.parse(params) : params;
699
+ const body = shouldValidate("request") ? partnerEndpointSchemas.createTeam.body.parse(params) : params;
736
700
  return request(partnerRoutes.teams.create, {
737
701
  method: "POST",
738
702
  body
@@ -751,7 +715,7 @@ function createPartnerClient(options = {}) {
751
715
  return request(partnerRoutes.teams.members(teamId), {}, partnerEndpointSchemas.listTeamMembers.response);
752
716
  },
753
717
  addTeamMember(teamId, params) {
754
- const body = shouldValidate(options, "request") ? partnerEndpointSchemas.addTeamMember.body.parse(params) : params;
718
+ const body = shouldValidate("request") ? partnerEndpointSchemas.addTeamMember.body.parse(params) : params;
755
719
  return request(partnerRoutes.teams.members(teamId), {
756
720
  method: "POST",
757
721
  body
@@ -767,7 +731,7 @@ function createPartnerClient(options = {}) {
767
731
  return request(partnerRoutes.teams.member(teamId, userId), { method: "DELETE" });
768
732
  },
769
733
  bindSiteToTeam(userId, siteId, params) {
770
- const body = shouldValidate(options, "request") ? partnerEndpointSchemas.bindSiteToTeam.body.parse(params) : params;
734
+ const body = shouldValidate("request") ? partnerEndpointSchemas.bindSiteToTeam.body.parse(params) : params;
771
735
  return request(partnerRoutes.partner.users.siteTeam(userId, siteId), {
772
736
  method: "PATCH",
773
737
  body
@@ -2289,4 +2253,5 @@ function readWebhookHeaders(headers) {
2289
2253
  signature: headers.signature ?? null
2290
2254
  };
2291
2255
  }
2256
+ var ARCHETYPE_EXECUTION_CLASS = archetypes_exports.ARCHETYPE_EXECUTION_CLASS;
2292
2257
  export { ARCHETYPE_EXECUTION_CLASS, CANONICAL_WEBHOOK_EVENTS, COMPARE_OPTIONS, COUNTRY_NAMES, CWV_GOOD_CLS, CWV_GOOD_INP, CWV_GOOD_LCP, CWV_POOR_CLS, CWV_POOR_INP, CWV_POOR_LCP, GSC_COLUMN_OPTIONS, GSC_PERIOD_OPTIONS, GSC_PERIOD_OPTIONS_LONG, GSC_STABLE_LATENCY_DAYS, PERIOD_PRESETS, PartnerApiError, SITE_TYPE_BASELINE, VALID_WEBHOOK_EVENTS, WEBHOOK_CONTRACT_VERSION, WEBHOOK_CONTRACT_VERSION_HEADER, WEBHOOK_DELIVERY_HEADER, WEBHOOK_EVENT_HEADER, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_TIMESTAMP_HEADER, analyticsStatusToSyncStatus, andFilter, classifyGscError, classifyHealthStage, classifyReachStage, classifySearchConsoleStage, classifySiteTriage, coerceRowMetrics, compareRange, countryName, coverageLabel, coverageLabels, createAnalyticsClient, createGscdumpClient, createGscdumpRealtimeClient, createPartnerClient, createPartnerRealtimeClient, cwvBucket, dateFilter, defineGscAnalyzer, derivePeerStanding, deriveSiteBaseline, enrichIssueDetails, findLifecycleSite, formatPartnerError, getGscUnstableCutoffDate, gscConsoleUrl, investigationStatusConfig, isCustomPeriod, isPartnerError, issueDetails, issueGroups, issueTypeToGroup, lifecycleSiteToSyncStatus, lifecycleSiteToUserSite, normalizeSiteType, nuxtSeoTips, parseCustomPeriod, parseWebhookPayload, parseWebhookPayloadResult, partnerErrorToException, periodToDateRange, periodToDays, positionFor, reachLivenessRatio, readWebhookHeaders, serializeWebhookPayload, severityOrder, siteTypeBaseline, siteUrlToHostname, splitOpportunityTitle, summarizeDailyRows, toPartnerError, truncateQuery, verifyWebhookSignature, weightedAnonPct };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@gscdump/sdk",
3
3
  "type": "module",
4
- "version": "0.26.10",
4
+ "version": "0.27.1",
5
5
  "description": "Consumer SDK for hosted gscdump.com integrations.",
6
6
  "author": {
7
7
  "name": "Harlan Wilton",
@@ -44,10 +44,10 @@
44
44
  "date-fns": "^4.4.0",
45
45
  "ofetch": "^1.5.1",
46
46
  "zod": "^4.4.3",
47
- "@gscdump/analysis": "0.26.10",
48
- "@gscdump/engine": "0.26.10",
49
- "@gscdump/contracts": "0.26.10",
50
- "gscdump": "0.26.10"
47
+ "@gscdump/analysis": "0.27.1",
48
+ "@gscdump/contracts": "0.27.1",
49
+ "@gscdump/engine": "0.27.1",
50
+ "gscdump": "0.27.1"
51
51
  },
52
52
  "devDependencies": {
53
53
  "typescript": "^6.0.3",