@gscdump/sdk 0.39.0 → 0.40.2

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/README.md CHANGED
@@ -3,10 +3,9 @@
3
3
  Consumer SDK for hosted gscdump.com integrations.
4
4
 
5
5
  > The descriptor-driven HTTP client and ticketed realtime state machine are
6
- > exported from `@gscdump/sdk/v1`. Existing root HTTP/realtime clients remain
7
- > legacy compatibility surfaces during the release and cutover overlap; the
8
- > legacy socket client still sends a long-lived key in its first frame and must
9
- > not be used for a v1 browser integration. See the
6
+ > exported from `@gscdump/sdk/v1`. The root HTTP client remains a temporary
7
+ > compatibility surface during the release and cutover overlap; the unsafe
8
+ > long-lived-key realtime client was removed before v1. See the
10
9
  > [v1 contract](../../docs/hosted-api-v1.md).
11
10
 
12
11
  This package is for partner applications that consume gscdump.com APIs,
@@ -14,9 +13,9 @@ webhooks, and realtime events. Callers inject the HTTP transport and auth they
14
13
  want to use; route construction stays inside the hosted adapter.
15
14
 
16
15
  ```ts
17
- import { createGscdumpClient } from '@gscdump/sdk'
16
+ import { createPartnerClient } from '@gscdump/sdk'
18
17
 
19
- const gscdump = createGscdumpClient({
18
+ const gscdump = createPartnerClient({
20
19
  apiBase: 'https://example.com/api',
21
20
  apiKey: process.env.GSCDUMP_API_KEY,
22
21
  fetch: $fetch,
@@ -1,2 +1,2 @@
1
1
  import * as import_gscdump_query from "gscdump/query";
2
- export { import_gscdump_query as query_d_exports };
2
+ export { __exportAll, __reExport, query_d_exports };
package/dist/index.d.mts CHANGED
@@ -1,6 +1,7 @@
1
- import { query_d_exports } from "./_chunks/query.mjs";
1
+ import { __exportAll, __reExport, query_d_exports } from "./_chunks/query.mjs";
2
2
  import { Result } from "gscdump/result";
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, IndexingDiagnosticsParams, 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
+ import { arbitrarySql as arbitrarySql$1, auxCloudOnly as auxCloudOnly$1, entityDailySparkline as entityDailySparkline$1, entityDailyTimeseries as entityDailyTimeseries$1, multiSeriesStackedDaily as multiSeriesStackedDaily$1, singleRowLookup as singleRowLookup$1, siteDailyTimeseries as siteDailyTimeseries$1, topNBreakdown as topNBreakdown$1, twoDimensionDetail as twoDimensionDetail$1 } from "@gscdump/contracts/archetypes";
4
+ 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, IndexingDiagnosticsParams, IndexingUrlsParams, InspectionHistoryResponse, InspectionIndex, PartnerClient, PartnerClient as PartnerClient$1, PartnerLifecycleAccount, PartnerLifecycleResponse, PartnerLifecycleSite, PartnerLifecycleSite as PartnerLifecycleSite$1, PartnerWebhookData, PartnerWebhookHeaders, PartnerWebhookHeaders as PartnerWebhookHeaders$1, RegisterPartnerSiteParams, RegisterPartnerUserParams, RollupEnvelope, SourceInfoOptions, 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";
4
5
  import { ZodTypeAny } from "zod";
5
6
  import { ActionSource } from "@gscdump/analysis";
6
7
  import { AnalysisTool } from "@gscdump/engine/analysis-types";
@@ -136,7 +137,20 @@ interface DailyAnonInput {
136
137
  anonymizedImpressionsPct: number;
137
138
  }
138
139
  declare function weightedAnonPct(days: readonly DailyAnonInput[] | null | undefined, window?: number): number | null;
140
+ declare namespace archetypes_d_exports {
141
+ export { ARCHETYPE_EXECUTION_CLASS, arbitrarySql, auxCloudOnly, entityDailySparkline, entityDailyTimeseries, multiSeriesStackedDaily, singleRowLookup, siteDailyTimeseries, topNBreakdown, twoDimensionDetail };
142
+ }
139
143
  import * as import__gscdump_contracts_archetypes from "@gscdump/contracts/archetypes";
144
+ declare const ARCHETYPE_EXECUTION_CLASS: Record<import("@gscdump/contracts").QueryArchetype, import("@gscdump/contracts").ArchetypeExecutionClass>;
145
+ declare const arbitrarySql: typeof arbitrarySql$1;
146
+ declare const auxCloudOnly: typeof auxCloudOnly$1;
147
+ declare const entityDailySparkline: typeof entityDailySparkline$1;
148
+ declare const entityDailyTimeseries: typeof entityDailyTimeseries$1;
149
+ declare const multiSeriesStackedDaily: typeof multiSeriesStackedDaily$1;
150
+ declare const singleRowLookup: typeof singleRowLookup$1;
151
+ declare const siteDailyTimeseries: typeof siteDailyTimeseries$1;
152
+ declare const topNBreakdown: typeof topNBreakdown$1;
153
+ declare const twoDimensionDetail: typeof twoDimensionDetail$1;
140
154
  type PartnerFetch = HostedFetch;
141
155
  type PartnerHeaders = HostedHeaders;
142
156
  type PartnerFetchOptions = HostedFetchOptions;
@@ -156,7 +170,6 @@ interface PartnerClientOptions extends HostedClientOptions {
156
170
  validate?: boolean | 'request' | 'response';
157
171
  }
158
172
  declare function createPartnerClient(options?: PartnerClientOptions): PartnerClient$1;
159
- declare const createGscdumpClient: typeof createPartnerClient;
160
173
  declare const COUNTRY_NAMES: Record<string, string>;
161
174
  declare const countryName: (code: string) => string;
162
175
  declare const CWV_GOOD_LCP = 2500;
@@ -213,7 +226,7 @@ interface GscClassifiedError {
213
226
  code?: number;
214
227
  /** Best-effort human message: server-supplied `message`, then `data.message`, then the error's own message. */
215
228
  message?: string;
216
- /** Seconds the server suggested waiting (429 with `retryAfter` payload). */
229
+ /** Seconds the server suggested waiting (429/503 retry payloads). */
217
230
  retryAfter?: number;
218
231
  }
219
232
  declare function classifyGscError(e: unknown): GscClassifiedError;
@@ -246,6 +259,14 @@ interface DateRangeResult {
246
259
  yearEnd: string;
247
260
  days: number;
248
261
  }
262
+ interface PeriodOptions {
263
+ /** Subtract GSC's stable-data latency from `end`. Default `true`. */
264
+ stableData?: boolean;
265
+ /** IANA timezone used to resolve today's calendar date. Default GSC/Pacific time. */
266
+ timezone?: string;
267
+ /** Clock used to resolve today's calendar date. Defaults to the current time. */
268
+ now?: Date;
269
+ }
249
270
  declare function isCustomPeriod(p: Period | string): p is CustomPeriod;
250
271
  declare function parseCustomPeriod(p: Period | string): {
251
272
  start: string;
@@ -253,8 +274,8 @@ declare function parseCustomPeriod(p: Period | string): {
253
274
  prevStart?: string;
254
275
  prevEnd?: string;
255
276
  } | null;
256
- declare function periodToDateRange(period: Period | string, stableData?: boolean): DateRangeResult;
257
- declare function periodToDays(period: Period | string): number;
277
+ declare function periodToDateRange(period: Period | string, stableDataOrOptions?: boolean | PeriodOptions): DateRangeResult;
278
+ declare function periodToDays(period: Period | string, stableDataOrOptions?: boolean | PeriodOptions): number;
258
279
  declare function compareRange(range: DateRangeResult, mode: CompareMode): {
259
280
  start: string;
260
281
  end: string;
@@ -349,6 +370,29 @@ declare function positionFor(r: {
349
370
  impressions: number;
350
371
  sum_position: number;
351
372
  }): number;
373
+ type GscSearchType = 'web' | 'image' | 'video' | 'news' | 'discover' | 'googleNews';
374
+ interface SearchTypeOptions {
375
+ searchType?: GscSearchType;
376
+ }
377
+ interface SourceRangeOptions {
378
+ start?: string;
379
+ end?: string;
380
+ startDate?: string;
381
+ endDate?: string;
382
+ }
383
+ interface AnalysisSourcesOptions extends SearchTypeOptions, SourceRangeOptions {
384
+ tables?: string[] | string;
385
+ maxBytes?: number;
386
+ maxRows?: number;
387
+ maxFiles?: number;
388
+ }
389
+ declare const DEFAULT_SEARCH_TYPE: GscSearchType;
390
+ declare function withDefaultSearchType<T extends object>(value: T, searchType?: GscSearchType): T & SearchTypeOptions;
391
+ declare function withDefaultSearchType<T>(value: T, searchType?: GscSearchType): T;
392
+ declare function searchTypeQuery(searchType?: GscSearchType): Record<string, string>;
393
+ declare function dateRangeOptionsQuery(options: SourceRangeOptions | undefined): Record<string, string>;
394
+ declare function sourceInfoQuery(options: SourceInfoOptions | undefined): Record<string, string>;
395
+ declare function tablesQuery(tablesOrOptions: string[] | string | AnalysisSourcesOptions | undefined, options?: AnalysisSourcesOptions): Record<string, string>;
352
396
  interface IndexingIssueDetail {
353
397
  description: string;
354
398
  fix: string;
@@ -403,83 +447,18 @@ declare const issueTypeToGroup: Record<string, string>;
403
447
  declare function enrichIssueDetails(modules?: {
404
448
  name: string;
405
449
  }[]): Record<string, IndexingIssueDetail>;
406
- declare function analyticsStatusToSyncStatus(status: PartnerLifecycleSite$1['analytics']['status']): GscdumpUserSite$1['syncStatus'];
407
- declare function lifecycleSiteToUserSite(site: PartnerLifecycleSite$1): GscdumpUserSite$1;
408
- declare function lifecycleSiteToSyncStatus(site: PartnerLifecycleSite$1): GscdumpSyncStatusResponse$1;
409
- declare function findLifecycleSite(lifecycle: PartnerLifecycleResponse$1, siteIdOrPropertyUrl: string): PartnerLifecycleSite$1 | null;
410
- type PartnerRealtimeScope = 'partner' | 'user';
411
- type PartnerRealtimeStatus = 'idle' | 'connecting' | 'open' | 'authenticated' | 'closed' | 'error';
412
- type PartnerRealtimeHandler<T> = (value: T) => void;
413
- interface PartnerWebSocketLike {
414
- readyState: number;
415
- onopen: ((event: unknown) => void) | null;
416
- onmessage: ((event: {
417
- data: unknown;
418
- }) => void) | null;
419
- onerror: ((event: unknown) => void) | null;
420
- onclose: ((event: unknown) => void) | null;
421
- send: (data: string) => void;
422
- close: (code?: number, reason?: string) => void;
423
- }
424
- interface PartnerWebSocketConstructor {
425
- new (url: string, protocols?: string | string[]): PartnerWebSocketLike;
426
- }
427
- interface PartnerRealtimeReconnectOptions {
428
- /** Default `true`. Set `false` to disable automatic reconnection entirely. */
429
- enabled?: boolean;
430
- /** First-retry delay in ms; doubles each attempt. Default `1000`. */
431
- baseDelayMs?: number;
432
- /** Upper bound on the backoff delay in ms. Default `30000`. */
433
- maxDelayMs?: number;
434
- /** Stop after this many consecutive failed attempts. Default `Infinity`. */
435
- maxRetries?: number;
436
- /** Apply equal-jitter to each delay so many clients don't reconnect in lockstep. Default `true`. */
437
- jitter?: boolean;
438
- }
439
- interface PartnerRealtimeOptions {
440
- /**
441
- * HTTP API base used only to derive a same-origin websocket base when `wsBase`
442
- * is omitted. Prefer passing `wsBase` when the websocket origin differs.
443
- */
444
- apiBase?: string;
445
- /** WebSocket origin base, for example `wss://origin.example`. */
446
- wsBase?: string;
447
- /** Partner or user API key sent in the first auth message. */
448
- apiKey: string;
449
- /** `/ws/partner` or `/ws/user`. User scope supports partner key + user id. */
450
- scope?: PartnerRealtimeScope;
451
- /** Required by the hosted `/ws/user` route when authenticating with a partner API key. */
452
- userId?: number | string;
453
- /** Optional initial site filter sent after authentication succeeds. */
454
- siteIds?: string[];
455
- protocols?: string | string[];
456
- WebSocket?: PartnerWebSocketConstructor;
457
- /**
458
- * Automatic reconnection on unexpected close (network drop, server restart).
459
- * A raw WebSocket `error` Event carries no actionable detail, so rather than
460
- * surfacing it the client transparently reconnects with exponential backoff.
461
- * `true` (default) uses defaults; pass an object to tune; `false` disables.
462
- * The backoff counter resets once a reconnection reaches `authenticated`.
463
- */
464
- reconnect?: boolean | PartnerRealtimeReconnectOptions;
465
- /** Injected timer hooks (for tests). Defaults to global `setTimeout`/`clearTimeout`. */
466
- setTimeout?: (handler: () => void, ms: number) => unknown;
467
- clearTimeout?: (handle: unknown) => void;
468
- }
469
- interface PartnerRealtimeClient {
470
- readonly status: PartnerRealtimeStatus;
471
- readonly socket: PartnerWebSocketLike | null;
472
- connect: () => PartnerWebSocketLike;
473
- close: (code?: number, reason?: string) => void;
474
- ping: () => void;
475
- subscribe: (siteIds: string[]) => void;
476
- onStatus: (handler: PartnerRealtimeHandler<PartnerRealtimeStatus>) => () => void;
477
- onMessage: (handler: PartnerRealtimeHandler<PartnerRealtimeMessage$1>) => () => void;
478
- onEvent: (handler: PartnerRealtimeHandler<PartnerRealtimeEvent$1>) => () => void;
479
- onError: (handler: PartnerRealtimeHandler<unknown>) => () => void;
480
- }
481
- declare function createPartnerRealtimeClient(options: PartnerRealtimeOptions): PartnerRealtimeClient;
482
- declare const createGscdumpRealtimeClient: typeof createPartnerRealtimeClient;
450
+ /**
451
+ * Stable lifecycle fields shared by the legacy partner response and public v1.
452
+ * Keeping the adapters structural lets consumers migrate to v1 without
453
+ * re-introducing legacy-only fields such as `intId` or `lifecycleRevision`.
454
+ */
455
+ type LifecycleSiteLike = Pick<PartnerLifecycleSite$1, 'siteId' | 'externalSiteId' | 'requestedUrl' | 'gscPropertyUrl' | 'permissionLevel' | 'analytics' | 'indexing' | 'latestError' | 'updatedAt'>;
456
+ declare function analyticsStatusToSyncStatus(status: LifecycleSiteLike['analytics']['status']): GscdumpUserSite$1['syncStatus'];
457
+ declare function lifecycleSiteToUserSite(site: LifecycleSiteLike): GscdumpUserSite$1;
458
+ declare function lifecycleSiteToSyncStatus(site: LifecycleSiteLike): GscdumpSyncStatusResponse$1;
459
+ declare function findLifecycleSite<TSite extends LifecycleSiteLike>(lifecycle: {
460
+ sites: readonly TSite[];
461
+ }, siteIdOrPropertyUrl: string): TSite | null;
483
462
  type SearchConsoleStageKey = 'not_connected' | 'waiting_for_data' | 'weak_discovery' | 'discovery_backlog' | 'crawl_blocked' | 'indexability_blocked' | 'index_rejection' | 'partially_indexed' | 'indexed_invisible' | 'visible_not_clicked' | 'ranking_stalled' | 'declining_visibility' | 'healthy_growth_ready';
484
463
  type SearchConsoleStageSeverity = 'success' | 'error' | 'warning' | 'info' | 'neutral';
485
464
  interface SearchConsoleStageEvidence {
@@ -754,7 +733,6 @@ declare function parseWebhookPayload<TData extends Record<string, unknown> = Rec
754
733
  validateSignature?: boolean;
755
734
  }): Promise<WebhookEnvelope$1<TData>>;
756
735
  declare function readWebhookHeaders(headers: Headers | PartnerWebhookHeaders$1 | null | undefined): Required<PartnerWebhookHeaders$1>;
757
- type ARCHETYPE_EXECUTION_CLASS = import__gscdump_contracts_archetypes.ARCHETYPE_EXECUTION_CLASS;
758
736
  type ArbitrarySqlQuery = import__gscdump_contracts_archetypes.ArbitrarySqlQuery;
759
737
  type ArchetypeExecutionClass = import__gscdump_contracts_archetypes.ArchetypeExecutionClass;
760
738
  type ArchetypeFacet = import__gscdump_contracts_archetypes.ArchetypeFacet;
@@ -774,4 +752,5 @@ type SingleRowLookupQuery = import__gscdump_contracts_archetypes.SingleRowLookup
774
752
  type SiteDailyTimeseriesQuery = import__gscdump_contracts_archetypes.SiteDailyTimeseriesQuery;
775
753
  type TopNBreakdownQuery = import__gscdump_contracts_archetypes.TopNBreakdownQuery;
776
754
  type TwoDimensionDetailQuery = import__gscdump_contracts_archetypes.TwoDimensionDetailQuery;
777
- 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 IndexingDiagnosticsParams, 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 };
755
+ type WireDateRange = import__gscdump_contracts_archetypes.WireDateRange;
756
+ export { ARCHETYPE_EXECUTION_CLASS, type AddPartnerTeamMemberParams, type AnalysisSourcesOptions, 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, DEFAULT_SEARCH_TYPE, 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 IndexingDiagnosticsParams, type IndexingIssue, type IndexingIssueDetail, type IndexingUrlsParams, type InspectionHistoryResponse, type InspectionIndex, type IssueGroup, type IssueSeverity, type LifecycleSiteLike, 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 PartnerWebhookData, type PartnerWebhookHeaders, type PeerBaselineInput, type PeerConfidence, type PeerStanding, type Period, type PeriodOptions, type PeriodPreset, type QueryArchetype, type RawDailyRow, type ReachStage, type ReachVerdict, 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 SearchTypeOptions, type SingleRowLookupQuery, type SiteBaseline, type SiteDailyTimeseriesQuery, type SiteTriage, type SiteTriageInput, type SiteType, type SiteTypeBaseline, type SourceRangeOptions, 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, type WireDateRange, analyticsStatusToSyncStatus, andFilter, arbitrarySql, auxCloudOnly, classifyGscError, classifyHealthStage, classifyReachStage, classifySearchConsoleStage, classifySiteTriage, coerceRowMetrics, compareRange, countryName, coverageLabel, coverageLabels, createAnalyticsClient, createPartnerClient, cwvBucket, dateFilter, dateRangeOptionsQuery, defineGscAnalyzer, derivePeerStanding, deriveSiteBaseline, enrichIssueDetails, entityDailySparkline, entityDailyTimeseries, findLifecycleSite, formatPartnerError, getGscUnstableCutoffDate, gscConsoleUrl, investigationStatusConfig, isCustomPeriod, isPartnerError, issueDetails, issueGroups, issueTypeToGroup, lifecycleSiteToSyncStatus, lifecycleSiteToUserSite, multiSeriesStackedDaily, normalizeSiteType, nuxtSeoTips, parseCustomPeriod, parseWebhookPayload, parseWebhookPayloadResult, partnerErrorToException, periodToDateRange, periodToDays, positionFor, reachLivenessRatio, readWebhookHeaders, searchTypeQuery, serializeWebhookPayload, severityOrder, singleRowLookup, siteDailyTimeseries, siteTypeBaseline, siteUrlToHostname, sourceInfoQuery, splitOpportunityTitle, summarizeDailyRows, tablesQuery, toPartnerError, topNBreakdown, truncateQuery, twoDimensionDetail, verifyWebhookSignature, weightedAnonPct, withDefaultSearchType };
package/dist/index.mjs CHANGED
@@ -1,13 +1,13 @@
1
- import { __exportAll, __reExport } from "./_chunks/rolldown-runtime.mjs";
2
- import { query_exports } from "./query.mjs";
3
1
  import { analyticsEndpoints } from "@gscdump/contracts/analytics";
4
2
  import { err, ok, unwrapResult } from "gscdump/result";
5
3
  import { ofetch } from "ofetch";
6
- import { partnerEndpoints, partnerRoutes } from "@gscdump/contracts/partner";
4
+ import { ARCHETYPE_EXECUTION_CLASS as ARCHETYPE_EXECUTION_CLASS$1, arbitrarySql as arbitrarySql$1, auxCloudOnly as auxCloudOnly$1, entityDailySparkline as entityDailySparkline$1, entityDailyTimeseries as entityDailyTimeseries$1, multiSeriesStackedDaily as multiSeriesStackedDaily$1, singleRowLookup as singleRowLookup$1, siteDailyTimeseries as siteDailyTimeseries$1, topNBreakdown as topNBreakdown$1, twoDimensionDetail as twoDimensionDetail$1 } from "@gscdump/contracts/archetypes";
5
+ import { partnerEndpoints } from "@gscdump/contracts/partner";
7
6
  import { resolveWindow } from "@gscdump/engine/period";
8
7
  import { endOfMonth, format, startOfMonth, startOfQuarter, startOfWeek, subDays, subMonths } from "date-fns";
9
8
  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";
10
9
  export * from "@gscdump/contracts";
10
+ const DEFAULT_SEARCH_TYPE = "web";
11
11
  function isAnalysisSourcesOptions(value) {
12
12
  return !!value && typeof value === "object" && !Array.isArray(value);
13
13
  }
@@ -189,10 +189,10 @@ function formatPartnerError(error) {
189
189
  function partnerErrorToException(error) {
190
190
  return error;
191
191
  }
192
- const TRAILING_SLASH_RE$1 = /\/+$/;
192
+ const TRAILING_SLASH_RE = /\/+$/;
193
193
  const LEADING_SLASH_RE = /^\/+/;
194
194
  function trimApiBase(apiBase, fallback) {
195
- return (apiBase ?? fallback).replace(TRAILING_SLASH_RE$1, "");
195
+ return (apiBase ?? fallback).replace(TRAILING_SLASH_RE, "");
196
196
  }
197
197
  function buildPath(apiBase, path) {
198
198
  if (!apiBase) return path.startsWith("/") ? path : `/${path}`;
@@ -401,9 +401,16 @@ function weightedAnonPct(days, window = 28) {
401
401
  }
402
402
  return totalImpressions > 0 ? weighted / totalImpressions : null;
403
403
  }
404
- var archetypes_exports = /* @__PURE__ */ __exportAll({});
405
- import * as import__gscdump_contracts_archetypes from "@gscdump/contracts/archetypes";
406
- __reExport(archetypes_exports, import__gscdump_contracts_archetypes);
404
+ const ARCHETYPE_EXECUTION_CLASS = ARCHETYPE_EXECUTION_CLASS$1;
405
+ const arbitrarySql = arbitrarySql$1;
406
+ const auxCloudOnly = auxCloudOnly$1;
407
+ const entityDailySparkline = entityDailySparkline$1;
408
+ const entityDailyTimeseries = entityDailyTimeseries$1;
409
+ const multiSeriesStackedDaily = multiSeriesStackedDaily$1;
410
+ const singleRowLookup = singleRowLookup$1;
411
+ const siteDailyTimeseries = siteDailyTimeseries$1;
412
+ const topNBreakdown = topNBreakdown$1;
413
+ const twoDimensionDetail = twoDimensionDetail$1;
407
414
  function normalizeLifecycleUrl(url) {
408
415
  return (url || "").replace(/^sc-domain:/, "").replace(/^https?:\/\//, "").replace(/^www\./, "").replace(/\/$/, "").toLowerCase();
409
416
  }
@@ -861,7 +868,6 @@ function createPartnerClient(options = {}) {
861
868
  }
862
869
  };
863
870
  }
864
- const createGscdumpClient = createPartnerClient;
865
871
  const COUNTRY_NAMES = {
866
872
  US: "United States",
867
873
  GB: "United Kingdom",
@@ -968,10 +974,11 @@ function classifyGscError(e) {
968
974
  code,
969
975
  message
970
976
  };
971
- if (code === 429) {
972
- const retry = e?.data?.retryAfter;
977
+ if (code === 429 || code === 503) {
978
+ const data = e?.data;
979
+ const retry = data?.retryAfter ?? data?.retryAfterSeconds;
973
980
  return {
974
- status: "rate-limited",
981
+ status: code === 429 ? "rate-limited" : "network",
975
982
  code,
976
983
  message,
977
984
  retryAfter: typeof retry === "number" ? retry : void 0
@@ -1491,8 +1498,14 @@ function parseCustomPeriod(p) {
1491
1498
  end
1492
1499
  };
1493
1500
  }
1494
- function todayInPST() {
1495
- return /* @__PURE__ */ new Date(`${(0, query_exports.currentPstDate)()}T00:00:00`);
1501
+ function todayInTimezone(timezone = "America/Los_Angeles", now = /* @__PURE__ */ new Date()) {
1502
+ const date = new Intl.DateTimeFormat("en-CA", {
1503
+ timeZone: timezone,
1504
+ year: "numeric",
1505
+ month: "2-digit",
1506
+ day: "2-digit"
1507
+ }).format(now);
1508
+ return /* @__PURE__ */ new Date(`${date}T00:00:00`);
1496
1509
  }
1497
1510
  const ROLLING_TO_UPSTREAM = {
1498
1511
  "7d": "last-7d",
@@ -1534,7 +1547,9 @@ function buildResultFromIso(start, end) {
1534
1547
  days
1535
1548
  };
1536
1549
  }
1537
- function periodToDateRange(period, stableData = true) {
1550
+ function periodToDateRange(period, stableDataOrOptions = true) {
1551
+ const options = typeof stableDataOrOptions === "boolean" ? { stableData: stableDataOrOptions } : stableDataOrOptions;
1552
+ const stableData = options.stableData ?? true;
1538
1553
  const custom = parseCustomPeriod(period);
1539
1554
  if (custom) {
1540
1555
  const result = buildResultFromIso(custom.start, custom.end);
@@ -1547,7 +1562,7 @@ function periodToDateRange(period, stableData = true) {
1547
1562
  };
1548
1563
  return result;
1549
1564
  }
1550
- const today = todayInPST();
1565
+ const today = todayInTimezone(options.timezone, options.now);
1551
1566
  const end = stableData ? subDays(today, 3) : subDays(today, 1);
1552
1567
  const endIso = fmt(end);
1553
1568
  const upstreamPreset = ROLLING_TO_UPSTREAM[period] ?? CALENDAR_TO_UPSTREAM[period];
@@ -1574,8 +1589,8 @@ function periodToDateRange(period, stableData = true) {
1574
1589
  }
1575
1590
  return buildResultFromIso(fmt(start), endIso);
1576
1591
  }
1577
- function periodToDays(period) {
1578
- return periodToDateRange(period).days;
1592
+ function periodToDays(period, stableDataOrOptions = true) {
1593
+ return periodToDateRange(period, stableDataOrOptions).days;
1579
1594
  }
1580
1595
  function compareRange(range, mode) {
1581
1596
  if (mode === "none") return null;
@@ -1593,189 +1608,6 @@ function getGscUnstableCutoffDate() {
1593
1608
  const cutoff = new Date(y, m - 1, d - 3);
1594
1609
  return `${cutoff.getFullYear()}-${String(cutoff.getMonth() + 1).padStart(2, "0")}-${String(cutoff.getDate()).padStart(2, "0")}`;
1595
1610
  }
1596
- function resolveReconnect(reconnect) {
1597
- const opts = reconnect === false ? { enabled: false } : reconnect === true || reconnect == null ? {} : reconnect;
1598
- return {
1599
- enabled: opts.enabled ?? true,
1600
- baseDelayMs: opts.baseDelayMs ?? 1e3,
1601
- maxDelayMs: opts.maxDelayMs ?? 3e4,
1602
- maxRetries: opts.maxRetries ?? Number.POSITIVE_INFINITY,
1603
- jitter: opts.jitter ?? true
1604
- };
1605
- }
1606
- const HTTP_PROTOCOL_RE = /^http/i;
1607
- const API_SUFFIX_RE = /\/api\/?$/;
1608
- const TRAILING_SLASH_RE = /\/+$/;
1609
- function inferWsBase(options) {
1610
- if (options.wsBase) return options.wsBase.replace(TRAILING_SLASH_RE, "");
1611
- if (!options.apiBase) return "";
1612
- return options.apiBase.replace(API_SUFFIX_RE, "").replace(TRAILING_SLASH_RE, "").replace(HTTP_PROTOCOL_RE, (m) => m.toLowerCase() === "https" ? "wss" : "ws");
1613
- }
1614
- function wsPath(scope) {
1615
- return scope === "partner" ? partnerRoutes.realtime.partner : partnerRoutes.realtime.user;
1616
- }
1617
- function buildWsUrl(options) {
1618
- const scope = options.scope ?? "partner";
1619
- const base = inferWsBase(options);
1620
- if (!base) return wsPath(scope);
1621
- return `${base}${wsPath(scope)}`;
1622
- }
1623
- function parseMessage(raw) {
1624
- if (typeof raw !== "string") return null;
1625
- try {
1626
- return JSON.parse(raw);
1627
- } catch {
1628
- return null;
1629
- }
1630
- }
1631
- function isRealtimeEvent(message) {
1632
- return "event" in message && message.event !== "auth.required" && message.event !== "connected";
1633
- }
1634
- function getWebSocketCtor(options) {
1635
- const ctor = options.WebSocket ?? globalThis.WebSocket;
1636
- if (!ctor) throw new Error("WebSocket is not available; pass options.WebSocket");
1637
- return ctor;
1638
- }
1639
- function createPartnerRealtimeClient(options) {
1640
- let socket = null;
1641
- let status = "idle";
1642
- const reconnect = resolveReconnect(options.reconnect);
1643
- const setTimer = options.setTimeout ?? ((handler, ms) => setTimeout(handler, ms));
1644
- const clearTimer = options.clearTimeout ?? ((handle) => clearTimeout(handle));
1645
- let manualClose = false;
1646
- let reconnectAttempts = 0;
1647
- let reconnectTimer = null;
1648
- const statusHandlers = /* @__PURE__ */ new Set();
1649
- const messageHandlers = /* @__PURE__ */ new Set();
1650
- const eventHandlers = /* @__PURE__ */ new Set();
1651
- const errorHandlers = /* @__PURE__ */ new Set();
1652
- function setStatus(next) {
1653
- status = next;
1654
- for (const handler of statusHandlers) handler(next);
1655
- }
1656
- function sendJson(payload) {
1657
- if (!socket) throw new Error("Partner realtime client is not connected");
1658
- socket.send(JSON.stringify(payload));
1659
- }
1660
- function authPayload() {
1661
- const payload = {
1662
- type: "auth",
1663
- apiKey: options.apiKey
1664
- };
1665
- if (options.userId != null) payload.userId = options.userId;
1666
- return payload;
1667
- }
1668
- function subscribe(siteIds) {
1669
- sendJson({
1670
- type: "subscribe",
1671
- siteIds
1672
- });
1673
- }
1674
- function clearReconnectTimer() {
1675
- if (reconnectTimer != null) {
1676
- clearTimer(reconnectTimer);
1677
- reconnectTimer = null;
1678
- }
1679
- }
1680
- function backoffDelay(attempt) {
1681
- const exp = Math.min(reconnect.maxDelayMs, reconnect.baseDelayMs * 2 ** attempt);
1682
- if (!reconnect.jitter) return exp;
1683
- return Math.round(exp / 2 + Math.random() * (exp / 2));
1684
- }
1685
- function openSocket() {
1686
- if (socket) return socket;
1687
- clearReconnectTimer();
1688
- manualClose = false;
1689
- socket = new (getWebSocketCtor(options))(buildWsUrl(options), options.protocols);
1690
- setStatus("connecting");
1691
- socket.onopen = () => {
1692
- setStatus("open");
1693
- sendJson(authPayload());
1694
- };
1695
- socket.onmessage = (event) => {
1696
- const message = parseMessage(event.data);
1697
- if (!message) return;
1698
- if ("event" in message && message.event === "connected") {
1699
- reconnectAttempts = 0;
1700
- setStatus("authenticated");
1701
- if (options.siteIds?.length) subscribe(options.siteIds);
1702
- }
1703
- for (const handler of messageHandlers) handler(message);
1704
- if (isRealtimeEvent(message)) for (const handler of eventHandlers) handler(message);
1705
- };
1706
- socket.onerror = (event) => {
1707
- setStatus("error");
1708
- for (const handler of errorHandlers) handler(event);
1709
- };
1710
- socket.onclose = (event) => {
1711
- socket = null;
1712
- setStatus("closed");
1713
- for (const handler of messageHandlers) handler({
1714
- type: "error",
1715
- message: `WebSocket closed: ${JSON.stringify(event)}`
1716
- });
1717
- scheduleReconnect();
1718
- };
1719
- return socket;
1720
- }
1721
- function scheduleReconnect() {
1722
- if (!reconnect.enabled || manualClose || reconnectTimer != null) return;
1723
- if (reconnectAttempts >= reconnect.maxRetries) {
1724
- const err = /* @__PURE__ */ new Error(`Partner realtime reconnect exhausted after ${reconnectAttempts} attempts`);
1725
- for (const handler of errorHandlers) handler(err);
1726
- return;
1727
- }
1728
- const delay = backoffDelay(reconnectAttempts);
1729
- reconnectAttempts += 1;
1730
- setStatus("connecting");
1731
- reconnectTimer = setTimer(() => {
1732
- reconnectTimer = null;
1733
- openSocket();
1734
- }, delay);
1735
- }
1736
- return {
1737
- get status() {
1738
- return status;
1739
- },
1740
- get socket() {
1741
- return socket;
1742
- },
1743
- connect() {
1744
- return openSocket();
1745
- },
1746
- close(code, reason) {
1747
- manualClose = true;
1748
- clearReconnectTimer();
1749
- const ws = socket;
1750
- socket = null;
1751
- setStatus("closed");
1752
- if (!ws) return;
1753
- if (ws.readyState === 0) ws.onopen = () => ws.close(code, reason);
1754
- else ws.close(code, reason);
1755
- },
1756
- ping() {
1757
- sendJson({ type: "ping" });
1758
- },
1759
- subscribe,
1760
- onStatus(handler) {
1761
- statusHandlers.add(handler);
1762
- return () => statusHandlers.delete(handler);
1763
- },
1764
- onMessage(handler) {
1765
- messageHandlers.add(handler);
1766
- return () => messageHandlers.delete(handler);
1767
- },
1768
- onEvent(handler) {
1769
- eventHandlers.add(handler);
1770
- return () => eventHandlers.delete(handler);
1771
- },
1772
- onError(handler) {
1773
- errorHandlers.add(handler);
1774
- return () => errorHandlers.delete(handler);
1775
- }
1776
- };
1777
- }
1778
- const createGscdumpRealtimeClient = createPartnerRealtimeClient;
1779
1611
  function formatSearchConsoleCount(value) {
1780
1612
  return new Intl.NumberFormat("en").format(Math.max(0, Math.round(value)));
1781
1613
  }
@@ -2526,5 +2358,4 @@ function readWebhookHeaders(headers) {
2526
2358
  signature: headers.signature ?? null
2527
2359
  };
2528
2360
  }
2529
- var ARCHETYPE_EXECUTION_CLASS = archetypes_exports.ARCHETYPE_EXECUTION_CLASS;
2530
- 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 };
2361
+ 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, DEFAULT_SEARCH_TYPE, 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, arbitrarySql, auxCloudOnly, classifyGscError, classifyHealthStage, classifyReachStage, classifySearchConsoleStage, classifySiteTriage, coerceRowMetrics, compareRange, countryName, coverageLabel, coverageLabels, createAnalyticsClient, createPartnerClient, cwvBucket, dateFilter, dateRangeOptionsQuery, defineGscAnalyzer, derivePeerStanding, deriveSiteBaseline, enrichIssueDetails, entityDailySparkline, entityDailyTimeseries, findLifecycleSite, formatPartnerError, getGscUnstableCutoffDate, gscConsoleUrl, investigationStatusConfig, isCustomPeriod, isPartnerError, issueDetails, issueGroups, issueTypeToGroup, lifecycleSiteToSyncStatus, lifecycleSiteToUserSite, multiSeriesStackedDaily, normalizeSiteType, nuxtSeoTips, parseCustomPeriod, parseWebhookPayload, parseWebhookPayloadResult, partnerErrorToException, periodToDateRange, periodToDays, positionFor, reachLivenessRatio, readWebhookHeaders, searchTypeQuery, serializeWebhookPayload, severityOrder, singleRowLookup, siteDailyTimeseries, siteTypeBaseline, siteUrlToHostname, sourceInfoQuery, splitOpportunityTitle, summarizeDailyRows, tablesQuery, toPartnerError, topNBreakdown, truncateQuery, twoDimensionDetail, verifyWebhookSignature, weightedAnonPct, withDefaultSearchType };
package/dist/query.mjs CHANGED
@@ -1,6 +1,2 @@
1
- import { __exportAll, __reExport } from "./_chunks/rolldown-runtime.mjs";
2
1
  export * from "gscdump/query";
3
- var query_exports = /* @__PURE__ */ __exportAll({});
4
- import * as import_gscdump_query from "gscdump/query";
5
- __reExport(query_exports, import_gscdump_query);
6
- export { query_exports };
2
+ export {};
@@ -71,7 +71,21 @@ declare function isGscdumpV1Error(error: unknown): error is GscdumpV1Error;
71
71
  interface GscdumpV1Client {
72
72
  execute: <TId extends GscdumpV1OperationId>(operation: TId, input: GscdumpV1OperationInput<TId>, options?: GscdumpV1ExecuteOptions) => Promise<GscdumpV1OperationResponse<TId>>;
73
73
  getUserLifecycle: (input: GscdumpV1OperationInput<'partner.users.lifecycle.get'>, options?: GscdumpV1ExecuteOptions) => Promise<GscdumpV1OperationResponse<'partner.users.lifecycle.get'>>;
74
+ listAvailableSites: (input: GscdumpV1OperationInput<'partner.users.sites.available.list'>, options?: GscdumpV1ExecuteOptions) => Promise<GscdumpV1OperationResponse<'partner.users.sites.available.list'>>;
75
+ createSite: (input: GscdumpV1OperationInput<'partner.users.sites.create'>, options?: GscdumpV1ExecuteOptions) => Promise<GscdumpV1OperationResponse<'partner.users.sites.create'>>;
76
+ createUser: (input: GscdumpV1OperationInput<'partner.users.create'>, options?: GscdumpV1ExecuteOptions) => Promise<GscdumpV1OperationResponse<'partner.users.create'>>;
77
+ updateUserTokens: (input: GscdumpV1OperationInput<'partner.users.tokens.update'>, options?: GscdumpV1ExecuteOptions) => Promise<GscdumpV1OperationResponse<'partner.users.tokens.update'>>;
78
+ getSiteIndexing: (input: GscdumpV1OperationInput<'partner.sites.indexing.get'>, options?: GscdumpV1ExecuteOptions) => Promise<GscdumpV1OperationResponse<'partner.sites.indexing.get'>>;
79
+ listSiteIndexingUrls: (input: GscdumpV1OperationInput<'partner.sites.indexing.urls.list'>, options?: GscdumpV1ExecuteOptions) => Promise<GscdumpV1OperationResponse<'partner.sites.indexing.urls.list'>>;
80
+ getSiteIndexingDiagnostics: (input: GscdumpV1OperationInput<'partner.sites.indexing.diagnostics.get'>, options?: GscdumpV1ExecuteOptions) => Promise<GscdumpV1OperationResponse<'partner.sites.indexing.diagnostics.get'>>;
81
+ getSiteSitemaps: (input: GscdumpV1OperationInput<'partner.sites.sitemaps.get'>, options?: GscdumpV1ExecuteOptions) => Promise<GscdumpV1OperationResponse<'partner.sites.sitemaps.get'>>;
82
+ getSiteSitemapChanges: (input: GscdumpV1OperationInput<'partner.sites.sitemaps.changes.get'>, options?: GscdumpV1ExecuteOptions) => Promise<GscdumpV1OperationResponse<'partner.sites.sitemaps.changes.get'>>;
83
+ getSiteAnalysis: (input: GscdumpV1OperationInput<'partner.sites.analysis.get'>, options?: GscdumpV1ExecuteOptions) => Promise<GscdumpV1OperationResponse<'partner.sites.analysis.get'>>;
84
+ getSiteAnalysisBundle: (input: GscdumpV1OperationInput<'partner.sites.analysis.bundle.get'>, options?: GscdumpV1ExecuteOptions) => Promise<GscdumpV1OperationResponse<'partner.sites.analysis.bundle.get'>>;
85
+ deleteSite: (input: GscdumpV1OperationInput<'partner.sites.delete'>, options?: GscdumpV1ExecuteOptions) => Promise<GscdumpV1OperationResponse<'partner.sites.delete'>>;
74
86
  queryAnalyticsRows: (input: GscdumpV1OperationInput<'analytics.rows.query'>, options?: GscdumpV1ExecuteOptions) => Promise<GscdumpV1OperationResponse<'analytics.rows.query'>>;
87
+ queryAnalyticsReport: (input: GscdumpV1OperationInput<'analytics.reports.query'>, options?: GscdumpV1ExecuteOptions) => Promise<GscdumpV1OperationResponse<'analytics.reports.query'>>;
88
+ queryAnalyticsReportDetail: (input: GscdumpV1OperationInput<'analytics.reports.detail.query'>, options?: GscdumpV1ExecuteOptions) => Promise<GscdumpV1OperationResponse<'analytics.reports.detail.query'>>;
75
89
  getRealtimeStreamHead: (input?: GscdumpV1OperationInput<'realtime.stream.head.get'>, options?: GscdumpV1ExecuteOptions) => Promise<GscdumpV1OperationResponse<'realtime.stream.head.get'>>;
76
90
  createRealtimeTicket: (input: GscdumpV1OperationInput<'realtime.tickets.create'>, options?: GscdumpV1ExecuteOptions) => Promise<GscdumpV1OperationResponse<'realtime.tickets.create'>>;
77
91
  }
package/dist/v1/index.mjs CHANGED
@@ -363,7 +363,21 @@ function createGscdumpV1Client(options) {
363
363
  return {
364
364
  execute,
365
365
  getUserLifecycle: (input, executeOptions) => execute("partner.users.lifecycle.get", input, executeOptions),
366
+ listAvailableSites: (input, executeOptions) => execute("partner.users.sites.available.list", input, executeOptions),
367
+ createSite: (input, executeOptions) => execute("partner.users.sites.create", input, executeOptions),
368
+ createUser: (input, executeOptions) => execute("partner.users.create", input, executeOptions),
369
+ updateUserTokens: (input, executeOptions) => execute("partner.users.tokens.update", input, executeOptions),
370
+ getSiteIndexing: (input, executeOptions) => execute("partner.sites.indexing.get", input, executeOptions),
371
+ listSiteIndexingUrls: (input, executeOptions) => execute("partner.sites.indexing.urls.list", input, executeOptions),
372
+ getSiteIndexingDiagnostics: (input, executeOptions) => execute("partner.sites.indexing.diagnostics.get", input, executeOptions),
373
+ getSiteSitemaps: (input, executeOptions) => execute("partner.sites.sitemaps.get", input, executeOptions),
374
+ getSiteSitemapChanges: (input, executeOptions) => execute("partner.sites.sitemaps.changes.get", input, executeOptions),
375
+ getSiteAnalysis: (input, executeOptions) => execute("partner.sites.analysis.get", input, executeOptions),
376
+ getSiteAnalysisBundle: (input, executeOptions) => execute("partner.sites.analysis.bundle.get", input, executeOptions),
377
+ deleteSite: (input, executeOptions) => execute("partner.sites.delete", input, executeOptions),
366
378
  queryAnalyticsRows: (input, executeOptions) => execute("analytics.rows.query", input, executeOptions),
379
+ queryAnalyticsReport: (input, executeOptions) => execute("analytics.reports.query", input, executeOptions),
380
+ queryAnalyticsReportDetail: (input, executeOptions) => execute("analytics.reports.detail.query", input, executeOptions),
367
381
  getRealtimeStreamHead: (input = {}, executeOptions) => execute("realtime.stream.head.get", input, executeOptions),
368
382
  createRealtimeTicket: (input, executeOptions) => execute("realtime.tickets.create", input, executeOptions)
369
383
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@gscdump/sdk",
3
3
  "type": "module",
4
- "version": "0.39.0",
4
+ "version": "0.40.2",
5
5
  "description": "Consumer SDK for hosted gscdump.com integrations.",
6
6
  "author": {
7
7
  "name": "Harlan Wilton",
@@ -49,10 +49,10 @@
49
49
  "date-fns": "^4.4.0",
50
50
  "ofetch": "^1.5.1",
51
51
  "zod": "^4.4.3",
52
- "@gscdump/contracts": "0.39.0",
53
- "@gscdump/analysis": "0.39.0",
54
- "@gscdump/engine": "0.39.0",
55
- "gscdump": "0.39.0"
52
+ "@gscdump/contracts": "0.40.2",
53
+ "@gscdump/engine": "0.40.2",
54
+ "gscdump": "0.40.2",
55
+ "@gscdump/analysis": "0.40.2"
56
56
  },
57
57
  "devDependencies": {
58
58
  "typescript": "^6.0.3",
@@ -1,25 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __exportAll = (all, no_symbols) => {
6
- let target = {};
7
- for (var name in all) __defProp(target, name, {
8
- get: all[name],
9
- enumerable: true
10
- });
11
- if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
12
- return target;
13
- };
14
- var __copyProps = (to, from, except, desc) => {
15
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
16
- key = keys[i];
17
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
18
- get: ((k) => from[k]).bind(null, key),
19
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
20
- });
21
- }
22
- return to;
23
- };
24
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
25
- export { __exportAll, __reExport };