@power-seo/search-console 1.0.0
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 +377 -0
- package/dist/index.cjs +279 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +164 -0
- package/dist/index.d.ts +164 -0
- package/dist/index.js +266 -0
- package/dist/index.js.map +1 -0
- package/package.json +56 -0
package/README.md
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
# @power-seo/search-console — Google Search Console API Client for TypeScript — OAuth2, Service Account, URL Inspection & Auto-Paginated Analytics
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@power-seo/search-console)
|
|
4
|
+
[](https://www.npmjs.com/package/@power-seo/search-console)
|
|
5
|
+
[](../../LICENSE)
|
|
6
|
+
[](https://www.typescriptlang.org/)
|
|
7
|
+
[](#)
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Overview
|
|
12
|
+
|
|
13
|
+
**@power-seo/search-console** is a production-ready Google Search Console API client for TypeScript that helps you query search analytics, inspect URLs, and manage sitemaps — without writing OAuth2 token refresh boilerplate or pagination loops.
|
|
14
|
+
|
|
15
|
+
**What it does**
|
|
16
|
+
- ✅ **OAuth2 and service account auth** — `createTokenManager()` handles token refresh cycles and JWT signing automatically
|
|
17
|
+
- ✅ **Search analytics queries** — clicks, impressions, CTR, and position by query, page, country, device, date
|
|
18
|
+
- ✅ **Auto-paginated full fetch** — `querySearchAnalyticsAll()` transparently pages through the 25,000-row GSC API limit
|
|
19
|
+
- ✅ **URL inspection** — indexing verdict, last crawl time, canonical URL, mobile usability, rich result status
|
|
20
|
+
- ✅ **Sitemap management** — list, submit, and delete sitemaps from verified GSC properties
|
|
21
|
+
|
|
22
|
+
**What it is not**
|
|
23
|
+
- ❌ **Not a reporting dashboard** — returns raw data; use `@power-seo/analytics` to merge and visualize
|
|
24
|
+
- ❌ **Not a site verification tool** — requires a property already verified in Google Search Console
|
|
25
|
+
|
|
26
|
+
**Recommended for**
|
|
27
|
+
- **SEO automation pipelines**, **CI/CD keyword tracking**, **SaaS analytics dashboards**, and **reporting scripts** using GSC data
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## Why @power-seo/search-console Matters
|
|
32
|
+
|
|
33
|
+
**The problem**
|
|
34
|
+
- **OAuth2 token refresh is complex** — access tokens expire every hour; service account JWT signing requires crypto operations
|
|
35
|
+
- **GSC returns only 25,000 rows per request** — sites with many queries need pagination loops that every team reimplements
|
|
36
|
+
- **URL inspection data is inaccessible without auth** — no simple way to check indexing status programmatically
|
|
37
|
+
|
|
38
|
+
**Why developers care**
|
|
39
|
+
- **SEO:** Programmatic access to real click/impression data enables data-driven content decisions
|
|
40
|
+
- **Performance:** Auto-paginated `querySearchAnalyticsAll` eliminates boilerplate that slows down analytics pipelines
|
|
41
|
+
- **UX:** URL inspection in CI enables instant indexing health checks after deployments
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## Key Features
|
|
46
|
+
|
|
47
|
+
- **OAuth2 authentication** — `createTokenManager({ type: 'oauth' })` handles token refresh automatically
|
|
48
|
+
- **Service account JWT authentication** — `createTokenManager({ type: 'service-account' })` signs JWTs for server-to-server access
|
|
49
|
+
- **Low-level auth primitives** — `exchangeRefreshToken()` and `getServiceAccountToken()` for custom auth flows
|
|
50
|
+
- **Typed GSC client** — `createGSCClient(config)` returns a `GSCClient` scoped to a specific site URL
|
|
51
|
+
- **Search analytics** — `querySearchAnalytics()` supports all 6 dimensions: `query`, `page`, `country`, `device`, `date`, `searchAppearance`
|
|
52
|
+
- **All search types** — `web`, `image`, `video`, and `news` search types
|
|
53
|
+
- **Auto-paginated full fetch** — `querySearchAnalyticsAll()` merges all pages into a single `SearchAnalyticsRow[]` array
|
|
54
|
+
- **URL inspection** — `inspectUrl()` returns verdict, indexing state, last crawl time, mobile usability, and rich result status
|
|
55
|
+
- **Direct URL inspection** — `inspectUrlDirect()` for the direct URL inspection endpoint
|
|
56
|
+
- **Sitemap listing** — `listSitemaps()` with status, last download time, and error counts
|
|
57
|
+
- **Sitemap submission and deletion** — `submitSitemap()` and `deleteSitemap()`
|
|
58
|
+
- **Typed error handling** — `GSCApiError` class with `status`, `code`, and `message`
|
|
59
|
+
- **Type-safe throughout** — full TypeScript types for all request and response shapes
|
|
60
|
+
|
|
61
|
+
---
|
|
62
|
+
|
|
63
|
+
## Benefits of Using @power-seo/search-console
|
|
64
|
+
|
|
65
|
+
- **Faster analytics pipelines**: No token refresh boilerplate; token manager handles expiry transparently
|
|
66
|
+
- **Complete datasets**: `querySearchAnalyticsAll` fetches all rows regardless of API page limit
|
|
67
|
+
- **Safer integration**: `GSCApiError` structured error class enables reliable error handling in production
|
|
68
|
+
- **Faster delivery**: Connect to GSC in minutes; no OAuth2 library research required
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## Quick Start
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
import { createTokenManager, createGSCClient, querySearchAnalyticsAll } from '@power-seo/search-console';
|
|
76
|
+
|
|
77
|
+
// 1. Create a token manager (OAuth2)
|
|
78
|
+
const tokenManager = createTokenManager({
|
|
79
|
+
type: 'oauth',
|
|
80
|
+
clientId: process.env.GSC_CLIENT_ID!,
|
|
81
|
+
clientSecret: process.env.GSC_CLIENT_SECRET!,
|
|
82
|
+
refreshToken: process.env.GSC_REFRESH_TOKEN!,
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
// 2. Create a client scoped to your site
|
|
86
|
+
const client = createGSCClient({
|
|
87
|
+
siteUrl: 'https://example.com',
|
|
88
|
+
tokenManager,
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
// 3. Fetch all search analytics data (auto-paginated)
|
|
92
|
+
const rows = await querySearchAnalyticsAll(client, {
|
|
93
|
+
startDate: '2026-01-01',
|
|
94
|
+
endDate: '2026-01-31',
|
|
95
|
+
dimensions: ['query', 'page'],
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
rows.forEach(({ keys, clicks, impressions, ctr, position }) => {
|
|
99
|
+
console.log(`Query: "${keys[0]}", Page: ${keys[1]}`);
|
|
100
|
+
console.log(` ${clicks} clicks, ${impressions} impressions, pos ${position.toFixed(1)}`);
|
|
101
|
+
});
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
**What you should see**
|
|
105
|
+
- A merged `SearchAnalyticsRow[]` array with all query-page combinations for the date range
|
|
106
|
+
- `clicks`, `impressions`, `ctr`, and `position` for each row
|
|
107
|
+
|
|
108
|
+
---
|
|
109
|
+
|
|
110
|
+
## Installation
|
|
111
|
+
|
|
112
|
+
```bash
|
|
113
|
+
npm i @power-seo/search-console
|
|
114
|
+
# or
|
|
115
|
+
yarn add @power-seo/search-console
|
|
116
|
+
# or
|
|
117
|
+
pnpm add @power-seo/search-console
|
|
118
|
+
# or
|
|
119
|
+
bun add @power-seo/search-console
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
---
|
|
123
|
+
|
|
124
|
+
## Framework Compatibility
|
|
125
|
+
|
|
126
|
+
**Supported**
|
|
127
|
+
- ✅ Next.js (App Router / Pages Router) — use in API routes or server actions
|
|
128
|
+
- ✅ Remix — use in loader functions and server-side actions
|
|
129
|
+
- ✅ Node.js 18+ — pure TypeScript client with `fetch` API
|
|
130
|
+
- ✅ CI/CD pipelines — run as standalone Node scripts in GitHub Actions or similar
|
|
131
|
+
|
|
132
|
+
**Environment notes**
|
|
133
|
+
- **SSR/SSG:** Fully supported — all operations are server-side
|
|
134
|
+
- **Edge runtime:** Not supported (requires crypto for JWT signing)
|
|
135
|
+
- **Browser-only usage:** Not supported — exposes credentials; server-side only
|
|
136
|
+
|
|
137
|
+
---
|
|
138
|
+
|
|
139
|
+
## Use Cases
|
|
140
|
+
|
|
141
|
+
- **Automated keyword ranking reports** — fetch all queries weekly and diff against previous week
|
|
142
|
+
- **Indexing health monitoring** — `inspectUrl` after deployments to verify new pages are indexed
|
|
143
|
+
- **Content gap analysis** — merge GSC data with `@power-seo/analytics` to find high-impression, low-click pages
|
|
144
|
+
- **Sitemap automation** — submit new sitemaps programmatically after content migrations
|
|
145
|
+
- **CI/CD SEO checks** — fail pipelines when key pages drop below position threshold
|
|
146
|
+
- **Multi-site SaaS dashboards** — aggregate GSC data across multiple client properties
|
|
147
|
+
- **Image and news search analytics** — query `image` and `news` search types separately
|
|
148
|
+
- **Country and device breakdowns** — segment click data by country or device for regional SEO
|
|
149
|
+
|
|
150
|
+
---
|
|
151
|
+
|
|
152
|
+
## Example (Before / After)
|
|
153
|
+
|
|
154
|
+
```text
|
|
155
|
+
Before:
|
|
156
|
+
- Manual OAuth2 token refresh: 50+ lines of token exchange code per project
|
|
157
|
+
- Pagination loop: separate rowOffset counter, multiple fetch calls, manual array merging
|
|
158
|
+
- URL inspection: no programmatic access → check Google Search Console UI manually
|
|
159
|
+
|
|
160
|
+
After (@power-seo/search-console):
|
|
161
|
+
- createTokenManager({ type: 'oauth', ... }) → tokens auto-refresh before every request
|
|
162
|
+
- querySearchAnalyticsAll(client, { dimensions: ['query'] }) → one call, complete dataset
|
|
163
|
+
- inspectUrl(client, url) → { verdict: 'PASS', lastCrawlTime: '...', mobileUsabilityResult: {...} }
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
---
|
|
167
|
+
|
|
168
|
+
## Implementation Best Practices
|
|
169
|
+
|
|
170
|
+
- **Use service accounts for CI/CD** — service accounts don't expire and don't require user interaction
|
|
171
|
+
- **Cache `querySearchAnalyticsAll` results** — GSC data is delayed by ~2 days; daily fetches are sufficient
|
|
172
|
+
- **Use `sc-domain:` prefix for domain properties** — e.g. `sc-domain:example.com` for domain-level verification
|
|
173
|
+
- **Add service account email as GSC user** — Settings → Users and permissions → Add user
|
|
174
|
+
- **Handle `GSCApiError` status 429** — implement exponential backoff for rate-limited requests
|
|
175
|
+
|
|
176
|
+
---
|
|
177
|
+
|
|
178
|
+
## Architecture Overview
|
|
179
|
+
|
|
180
|
+
**Where it runs**
|
|
181
|
+
- **Build-time**: Fetch GSC data for static site revalidation or build-time content ranking
|
|
182
|
+
- **Runtime**: Query analytics in serverless functions for real-time dashboard data
|
|
183
|
+
- **CI/CD**: Check indexing status and keyword positions in automated pipelines
|
|
184
|
+
|
|
185
|
+
**Data flow**
|
|
186
|
+
1. **Input**: OAuth2 credentials or service account key + site URL + query parameters
|
|
187
|
+
2. **Analysis**: Token manager handles auth; client sends typed requests to GSC API
|
|
188
|
+
3. **Output**: Typed `SearchAnalyticsRow[]`, `InspectionResult`, `SitemapListResponse`
|
|
189
|
+
4. **Action**: Feed into `@power-seo/analytics` for dashboards, or export as CSV/JSON reports
|
|
190
|
+
|
|
191
|
+
---
|
|
192
|
+
|
|
193
|
+
## Features Comparison with Popular Packages
|
|
194
|
+
|
|
195
|
+
| Capability | google-auth-library | googleapis | custom fetch | @power-seo/search-console |
|
|
196
|
+
|---|---:|---:|---:|---:|
|
|
197
|
+
| OAuth2 token auto-refresh | ✅ | ✅ | ❌ | ✅ |
|
|
198
|
+
| Service account JWT signing | ✅ | ✅ | ❌ | ✅ |
|
|
199
|
+
| Auto-paginated analytics fetch | ❌ | ❌ | ❌ | ✅ |
|
|
200
|
+
| Typed GSC-specific response shapes | ❌ | ⚠️ | ❌ | ✅ |
|
|
201
|
+
| URL inspection support | ❌ | ⚠️ | ❌ | ✅ |
|
|
202
|
+
| Sitemap management | ❌ | ⚠️ | ❌ | ✅ |
|
|
203
|
+
|
|
204
|
+
---
|
|
205
|
+
|
|
206
|
+
## @power-seo Ecosystem
|
|
207
|
+
|
|
208
|
+
All 17 packages are independently installable — use only what you need.
|
|
209
|
+
|
|
210
|
+
| Package | Install | Description |
|
|
211
|
+
|---------|---------|-------------|
|
|
212
|
+
| [`@power-seo/core`](https://www.npmjs.com/package/@power-seo/core) | `npm i @power-seo/core` | Framework-agnostic utilities, types, validators, and constants |
|
|
213
|
+
| [`@power-seo/react`](https://www.npmjs.com/package/@power-seo/react) | `npm i @power-seo/react` | React SEO components — meta, Open Graph, Twitter Card, breadcrumbs |
|
|
214
|
+
| [`@power-seo/meta`](https://www.npmjs.com/package/@power-seo/meta) | `npm i @power-seo/meta` | SSR meta helpers for Next.js App Router, Remix v2, and generic SSR |
|
|
215
|
+
| [`@power-seo/schema`](https://www.npmjs.com/package/@power-seo/schema) | `npm i @power-seo/schema` | Type-safe JSON-LD structured data — 20 builders + 18 React components |
|
|
216
|
+
| [`@power-seo/content-analysis`](https://www.npmjs.com/package/@power-seo/content-analysis) | `npm i @power-seo/content-analysis` | Yoast-style SEO content scoring engine with React components |
|
|
217
|
+
| [`@power-seo/readability`](https://www.npmjs.com/package/@power-seo/readability) | `npm i @power-seo/readability` | Readability scoring — Flesch-Kincaid, Gunning Fog, Coleman-Liau, ARI |
|
|
218
|
+
| [`@power-seo/preview`](https://www.npmjs.com/package/@power-seo/preview) | `npm i @power-seo/preview` | SERP, Open Graph, and Twitter/X Card preview generators |
|
|
219
|
+
| [`@power-seo/sitemap`](https://www.npmjs.com/package/@power-seo/sitemap) | `npm i @power-seo/sitemap` | XML sitemap generation, streaming, index splitting, and validation |
|
|
220
|
+
| [`@power-seo/redirects`](https://www.npmjs.com/package/@power-seo/redirects) | `npm i @power-seo/redirects` | Redirect engine with Next.js, Remix, and Express adapters |
|
|
221
|
+
| [`@power-seo/links`](https://www.npmjs.com/package/@power-seo/links) | `npm i @power-seo/links` | Link graph analysis — orphan detection, suggestions, equity scoring |
|
|
222
|
+
| [`@power-seo/audit`](https://www.npmjs.com/package/@power-seo/audit) | `npm i @power-seo/audit` | Full SEO audit engine — meta, content, structure, performance rules |
|
|
223
|
+
| [`@power-seo/images`](https://www.npmjs.com/package/@power-seo/images) | `npm i @power-seo/images` | Image SEO — alt text, lazy loading, format analysis, image sitemaps |
|
|
224
|
+
| [`@power-seo/ai`](https://www.npmjs.com/package/@power-seo/ai) | `npm i @power-seo/ai` | LLM-agnostic AI prompt templates and parsers for SEO tasks |
|
|
225
|
+
| [`@power-seo/analytics`](https://www.npmjs.com/package/@power-seo/analytics) | `npm i @power-seo/analytics` | Merge GSC + audit data, trend analysis, ranking insights, dashboard |
|
|
226
|
+
| [`@power-seo/search-console`](https://www.npmjs.com/package/@power-seo/search-console) | `npm i @power-seo/search-console` | Google Search Console API — OAuth2, service account, URL inspection |
|
|
227
|
+
| [`@power-seo/integrations`](https://www.npmjs.com/package/@power-seo/integrations) | `npm i @power-seo/integrations` | Semrush and Ahrefs API clients with rate limiting and pagination |
|
|
228
|
+
| [`@power-seo/tracking`](https://www.npmjs.com/package/@power-seo/tracking) | `npm i @power-seo/tracking` | GA4, Clarity, PostHog, Plausible, Fathom — scripts + consent management |
|
|
229
|
+
|
|
230
|
+
### Ecosystem vs alternatives
|
|
231
|
+
|
|
232
|
+
| Need | Common approach | @power-seo approach |
|
|
233
|
+
|---|---|---|
|
|
234
|
+
| GSC search analytics | `googleapis` (verbose) | `@power-seo/search-console` — typed, auto-paginated |
|
|
235
|
+
| Analytics dashboards | Google Looker Studio | `@power-seo/analytics` — merge GSC + audit data |
|
|
236
|
+
| Sitemap submission | Manual GSC UI | `@power-seo/search-console` — `submitSitemap()` |
|
|
237
|
+
| SEO auditing | Third-party tools | `@power-seo/audit` — in-code, CI-friendly |
|
|
238
|
+
|
|
239
|
+
---
|
|
240
|
+
|
|
241
|
+
## Enterprise Integration
|
|
242
|
+
|
|
243
|
+
**Multi-tenant SaaS**
|
|
244
|
+
- **Per-client GSC properties**: Instantiate one `GSCClient` per client site; use service accounts for automation
|
|
245
|
+
- **Aggregated dashboards**: Loop over multiple `siteUrl` values and merge analytics into a multi-site report
|
|
246
|
+
- **Scheduled data sync**: Run `querySearchAnalyticsAll` on a daily cron for all client properties
|
|
247
|
+
|
|
248
|
+
**ERP / internal portals**
|
|
249
|
+
- Use URL inspection to verify that portal public pages are correctly indexed
|
|
250
|
+
- Track keyword positions for internal knowledge base articles
|
|
251
|
+
- Automate sitemap submission after content management system publishes
|
|
252
|
+
|
|
253
|
+
**Recommended integration pattern**
|
|
254
|
+
- Use **service accounts** in CI/CD — no user interaction, no token expiry
|
|
255
|
+
- Run `querySearchAnalyticsAll` in **weekly scheduled jobs**
|
|
256
|
+
- Feed data into `@power-seo/analytics` for **trend analysis** and **ranking insights**
|
|
257
|
+
- Export results as **JSON** to Jira/Notion/Slack for content team review
|
|
258
|
+
|
|
259
|
+
---
|
|
260
|
+
|
|
261
|
+
## Scope and Limitations
|
|
262
|
+
|
|
263
|
+
**This package does**
|
|
264
|
+
- ✅ Authenticate with GSC API via OAuth2 and service account
|
|
265
|
+
- ✅ Fetch search analytics data with auto-pagination
|
|
266
|
+
- ✅ Inspect URL indexing status, mobile usability, and rich result status
|
|
267
|
+
- ✅ Submit, list, and delete sitemaps from verified GSC properties
|
|
268
|
+
|
|
269
|
+
**This package does not**
|
|
270
|
+
- ❌ Verify properties in GSC — property must already be verified
|
|
271
|
+
- ❌ Provide reporting UI — use `@power-seo/analytics` for dashboards
|
|
272
|
+
- ❌ Access Google Analytics data — use `@power-seo/tracking` for GA4 API access
|
|
273
|
+
|
|
274
|
+
---
|
|
275
|
+
|
|
276
|
+
## API Reference
|
|
277
|
+
|
|
278
|
+
### `createTokenManager(config)`
|
|
279
|
+
|
|
280
|
+
| Parameter | Type | Description |
|
|
281
|
+
|-----------|------|-------------|
|
|
282
|
+
| `config.type` | `'oauth' \| 'service-account'` | Authentication method |
|
|
283
|
+
| `config.clientId` | `string` | Google OAuth2 client ID (OAuth2 only) |
|
|
284
|
+
| `config.clientSecret` | `string` | Google OAuth2 client secret (OAuth2 only) |
|
|
285
|
+
| `config.refreshToken` | `string` | OAuth2 refresh token (OAuth2 only) |
|
|
286
|
+
| `config.clientEmail` | `string` | Service account email (service account only) |
|
|
287
|
+
| `config.privateKey` | `string` | Service account private key PEM (service account only) |
|
|
288
|
+
| `config.scopes` | `string[]` | OAuth2 scopes to request (service account only) |
|
|
289
|
+
|
|
290
|
+
Returns `TokenManager`: `{ getAccessToken(): Promise<TokenResult> }`.
|
|
291
|
+
|
|
292
|
+
### `createGSCClient(config)`
|
|
293
|
+
|
|
294
|
+
| Parameter | Type | Description |
|
|
295
|
+
|-----------|------|-------------|
|
|
296
|
+
| `config.siteUrl` | `string` | Verified GSC property URL (`sc-domain:` prefix for domain properties) |
|
|
297
|
+
| `config.tokenManager` | `TokenManager` | Token manager from `createTokenManager` |
|
|
298
|
+
|
|
299
|
+
Returns `GSCClient`.
|
|
300
|
+
|
|
301
|
+
### `querySearchAnalytics(client, request)`
|
|
302
|
+
|
|
303
|
+
| Parameter | Type | Default | Description |
|
|
304
|
+
|-----------|------|---------|-------------|
|
|
305
|
+
| `request.startDate` | `string` | required | `YYYY-MM-DD` |
|
|
306
|
+
| `request.endDate` | `string` | required | `YYYY-MM-DD` |
|
|
307
|
+
| `request.dimensions` | `Dimension[]` | `[]` | `'query'`, `'page'`, `'country'`, `'device'`, `'date'`, `'searchAppearance'` |
|
|
308
|
+
| `request.searchType` | `SearchType` | `'web'` | `'web'`, `'image'`, `'video'`, `'news'` |
|
|
309
|
+
| `request.rowLimit` | `number` | `1000` | Rows per request (max 25,000) |
|
|
310
|
+
| `request.dimensionFilterGroups` | `object[]` | `[]` | Filter groups to narrow results |
|
|
311
|
+
|
|
312
|
+
### `querySearchAnalyticsAll(client, request)`
|
|
313
|
+
|
|
314
|
+
Same as `querySearchAnalytics` but `rowLimit` and `startRow` are managed automatically. Returns `Promise<SearchAnalyticsRow[]>`.
|
|
315
|
+
|
|
316
|
+
### `inspectUrl(client, url)` / `inspectUrlDirect(client, url)`
|
|
317
|
+
|
|
318
|
+
Returns `Promise<InspectionResult>`: `{ verdict, indexingState, lastCrawlTime, mobileUsabilityResult, richResultsResult, ... }`.
|
|
319
|
+
|
|
320
|
+
### `listSitemaps(client)` / `submitSitemap(client, url)` / `deleteSitemap(client, url)`
|
|
321
|
+
|
|
322
|
+
`listSitemaps` returns `Promise<SitemapListResponse>`. `submitSitemap` and `deleteSitemap` return `Promise<void>`.
|
|
323
|
+
|
|
324
|
+
### Types
|
|
325
|
+
|
|
326
|
+
```ts
|
|
327
|
+
import type {
|
|
328
|
+
OAuthCredentials, ServiceAccountCredentials, TokenResult, TokenManager,
|
|
329
|
+
GSCClientConfig, GSCClient,
|
|
330
|
+
SearchType, Dimension,
|
|
331
|
+
SearchAnalyticsRequest, SearchAnalyticsRow, SearchAnalyticsResponse,
|
|
332
|
+
InspectionResult,
|
|
333
|
+
SitemapEntry, SitemapListResponse,
|
|
334
|
+
} from '@power-seo/search-console';
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
---
|
|
338
|
+
|
|
339
|
+
## Contributing
|
|
340
|
+
|
|
341
|
+
- Issues: [github.com/cybercraftbd/power-seo/issues](https://github.com/cybercraftbd/power-seo/issues)
|
|
342
|
+
- PRs: [github.com/cybercraftbd/power-seo/pulls](https://github.com/cybercraftbd/power-seo/pulls)
|
|
343
|
+
- Development setup:
|
|
344
|
+
1. `pnpm i`
|
|
345
|
+
2. `pnpm build`
|
|
346
|
+
3. `pnpm test`
|
|
347
|
+
|
|
348
|
+
**Release workflow**
|
|
349
|
+
- `npm version patch|minor|major`
|
|
350
|
+
- `npm publish --access public`
|
|
351
|
+
|
|
352
|
+
---
|
|
353
|
+
|
|
354
|
+
## About CyberCraft Bangladesh
|
|
355
|
+
|
|
356
|
+
**CyberCraft Bangladesh** is a Bangladesh-based enterprise-grade software engineering company specializing in ERP system development, AI-powered SaaS and business applications, full-stack SEO services, custom website development, and scalable eCommerce platforms. We design and develop intelligent, automation-driven SaaS and enterprise solutions that help startups, SMEs, NGOs, educational institutes, and large organizations streamline operations, enhance digital visibility, and accelerate growth through modern cloud-native technologies.
|
|
357
|
+
|
|
358
|
+
| | |
|
|
359
|
+
|---|---|
|
|
360
|
+
| **Website** | [ccbd.dev](https://ccbd.dev) |
|
|
361
|
+
| **GitHub** | [github.com/cybercraftbd](https://github.com/cybercraftbd) |
|
|
362
|
+
| **npm Organization** | [npmjs.com/org/power-seo](https://www.npmjs.com/org/power-seo) |
|
|
363
|
+
| **Email** | [info@ccbd.dev](mailto:info@ccbd.dev) |
|
|
364
|
+
|
|
365
|
+
---
|
|
366
|
+
|
|
367
|
+
## License
|
|
368
|
+
|
|
369
|
+
**MIT**
|
|
370
|
+
|
|
371
|
+
---
|
|
372
|
+
|
|
373
|
+
## Keywords
|
|
374
|
+
|
|
375
|
+
```text
|
|
376
|
+
seo, google-search-console, gsc, search-analytics, url-inspection, sitemap, oauth2, service-account, typescript, nextjs, analytics, keyword-tracking, click-through-rate, impressions
|
|
377
|
+
```
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var core = require('@power-seo/core');
|
|
4
|
+
|
|
5
|
+
// src/types.ts
|
|
6
|
+
var GSCApiError = class extends Error {
|
|
7
|
+
status;
|
|
8
|
+
code;
|
|
9
|
+
retryable;
|
|
10
|
+
constructor(message, status, code) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = "GSCApiError";
|
|
13
|
+
this.status = status;
|
|
14
|
+
this.code = code;
|
|
15
|
+
this.retryable = status === 429 || status >= 500;
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
// src/auth.ts
|
|
20
|
+
var TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
21
|
+
var GSC_SCOPE = "https://www.googleapis.com/auth/webmasters.readonly";
|
|
22
|
+
var TOKEN_BUFFER_MS = 6e4;
|
|
23
|
+
async function exchangeRefreshToken(credentials) {
|
|
24
|
+
const body = new globalThis.URLSearchParams({
|
|
25
|
+
client_id: credentials.clientId,
|
|
26
|
+
client_secret: credentials.clientSecret,
|
|
27
|
+
refresh_token: credentials.refreshToken,
|
|
28
|
+
grant_type: "refresh_token"
|
|
29
|
+
});
|
|
30
|
+
const response = await globalThis.fetch(TOKEN_URL, {
|
|
31
|
+
method: "POST",
|
|
32
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
33
|
+
body: body.toString()
|
|
34
|
+
});
|
|
35
|
+
if (!response.ok) {
|
|
36
|
+
const text = await response.text();
|
|
37
|
+
throw new GSCApiError(
|
|
38
|
+
`Token exchange failed: ${text}`,
|
|
39
|
+
response.status,
|
|
40
|
+
"TOKEN_EXCHANGE_ERROR"
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
const data = await response.json();
|
|
44
|
+
return {
|
|
45
|
+
accessToken: data.access_token,
|
|
46
|
+
expiresAt: Date.now() + data.expires_in * 1e3
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
async function getServiceAccountToken(credentials) {
|
|
50
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
51
|
+
const payload = {
|
|
52
|
+
iss: credentials.clientEmail,
|
|
53
|
+
scope: GSC_SCOPE,
|
|
54
|
+
aud: TOKEN_URL,
|
|
55
|
+
exp: now + 3600,
|
|
56
|
+
iat: now
|
|
57
|
+
};
|
|
58
|
+
const assertion = await credentials.signJwt(payload);
|
|
59
|
+
const body = new globalThis.URLSearchParams({
|
|
60
|
+
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
|
|
61
|
+
assertion
|
|
62
|
+
});
|
|
63
|
+
const response = await globalThis.fetch(TOKEN_URL, {
|
|
64
|
+
method: "POST",
|
|
65
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
66
|
+
body: body.toString()
|
|
67
|
+
});
|
|
68
|
+
if (!response.ok) {
|
|
69
|
+
const text = await response.text();
|
|
70
|
+
throw new GSCApiError(
|
|
71
|
+
`Service account token failed: ${text}`,
|
|
72
|
+
response.status,
|
|
73
|
+
"SERVICE_ACCOUNT_ERROR"
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
const data = await response.json();
|
|
77
|
+
return {
|
|
78
|
+
accessToken: data.access_token,
|
|
79
|
+
expiresAt: Date.now() + data.expires_in * 1e3
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
function createTokenManager(fetchToken) {
|
|
83
|
+
let cached = null;
|
|
84
|
+
let pending = null;
|
|
85
|
+
return {
|
|
86
|
+
async getToken() {
|
|
87
|
+
if (cached && cached.expiresAt > Date.now() + TOKEN_BUFFER_MS) {
|
|
88
|
+
return cached.accessToken;
|
|
89
|
+
}
|
|
90
|
+
if (pending) {
|
|
91
|
+
return pending;
|
|
92
|
+
}
|
|
93
|
+
pending = fetchToken().then((result) => {
|
|
94
|
+
cached = result;
|
|
95
|
+
pending = null;
|
|
96
|
+
return result.accessToken;
|
|
97
|
+
});
|
|
98
|
+
return pending;
|
|
99
|
+
},
|
|
100
|
+
invalidate() {
|
|
101
|
+
cached = null;
|
|
102
|
+
pending = null;
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
var DEFAULT_BASE_URL = "https://searchconsole.googleapis.com/webmasters/v3";
|
|
107
|
+
var DEFAULT_RATE_LIMIT = 1200;
|
|
108
|
+
var DEFAULT_MAX_RETRIES = 3;
|
|
109
|
+
function createGSCClient(config) {
|
|
110
|
+
const baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
|
|
111
|
+
const maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
|
|
112
|
+
const bucket = core.createTokenBucket(config.rateLimitPerMinute ?? DEFAULT_RATE_LIMIT);
|
|
113
|
+
async function request(path, options) {
|
|
114
|
+
const waitTime = core.getWaitTime(bucket);
|
|
115
|
+
if (waitTime > 0) {
|
|
116
|
+
await core.sleep(waitTime);
|
|
117
|
+
}
|
|
118
|
+
core.consumeToken(bucket);
|
|
119
|
+
const token = await config.auth.getToken();
|
|
120
|
+
const url = `${baseUrl}${path}`;
|
|
121
|
+
let lastError = null;
|
|
122
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
123
|
+
try {
|
|
124
|
+
const response = await globalThis.fetch(url, {
|
|
125
|
+
method: options?.method ?? "GET",
|
|
126
|
+
headers: {
|
|
127
|
+
Authorization: `Bearer ${token}`,
|
|
128
|
+
"Content-Type": "application/json"
|
|
129
|
+
},
|
|
130
|
+
body: options?.body ? JSON.stringify(options.body) : void 0,
|
|
131
|
+
signal: options?.signal
|
|
132
|
+
});
|
|
133
|
+
if (response.ok) {
|
|
134
|
+
return await response.json();
|
|
135
|
+
}
|
|
136
|
+
const text = await response.text();
|
|
137
|
+
const error = new GSCApiError(
|
|
138
|
+
`GSC API error: ${response.status} ${text}`,
|
|
139
|
+
response.status,
|
|
140
|
+
`HTTP_${response.status}`
|
|
141
|
+
);
|
|
142
|
+
if (!error.retryable || attempt === maxRetries) {
|
|
143
|
+
throw error;
|
|
144
|
+
}
|
|
145
|
+
lastError = error;
|
|
146
|
+
const backoff = Math.min(1e3 * Math.pow(2, attempt), 3e4);
|
|
147
|
+
await core.sleep(backoff);
|
|
148
|
+
} catch (err) {
|
|
149
|
+
if (err instanceof GSCApiError) {
|
|
150
|
+
if (!err.retryable || attempt === maxRetries) {
|
|
151
|
+
throw err;
|
|
152
|
+
}
|
|
153
|
+
lastError = err;
|
|
154
|
+
const backoff = Math.min(1e3 * Math.pow(2, attempt), 3e4);
|
|
155
|
+
await core.sleep(backoff);
|
|
156
|
+
} else {
|
|
157
|
+
throw err;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
throw lastError ?? new GSCApiError("Request failed", 500, "UNKNOWN");
|
|
162
|
+
}
|
|
163
|
+
return {
|
|
164
|
+
request,
|
|
165
|
+
siteUrl: config.siteUrl
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// src/analytics.ts
|
|
170
|
+
var MAX_ROW_LIMIT = 25e3;
|
|
171
|
+
var DEFAULT_ROW_LIMIT = 1e3;
|
|
172
|
+
async function querySearchAnalytics(client, request) {
|
|
173
|
+
const siteUrl = encodeURIComponent(client.siteUrl);
|
|
174
|
+
const body = {
|
|
175
|
+
...request,
|
|
176
|
+
rowLimit: Math.min(request.rowLimit ?? DEFAULT_ROW_LIMIT, MAX_ROW_LIMIT)
|
|
177
|
+
};
|
|
178
|
+
return client.request(
|
|
179
|
+
`/sites/${siteUrl}/searchAnalytics/query`,
|
|
180
|
+
{ method: "POST", body }
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
async function querySearchAnalyticsAll(client, request) {
|
|
184
|
+
const allRows = [];
|
|
185
|
+
let startRow = 0;
|
|
186
|
+
while (true) {
|
|
187
|
+
const response = await querySearchAnalytics(client, {
|
|
188
|
+
...request,
|
|
189
|
+
rowLimit: MAX_ROW_LIMIT,
|
|
190
|
+
startRow
|
|
191
|
+
});
|
|
192
|
+
const rows = response.rows ?? [];
|
|
193
|
+
allRows.push(...rows);
|
|
194
|
+
if (rows.length < MAX_ROW_LIMIT) {
|
|
195
|
+
break;
|
|
196
|
+
}
|
|
197
|
+
startRow += rows.length;
|
|
198
|
+
}
|
|
199
|
+
return allRows;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// src/inspection.ts
|
|
203
|
+
var INSPECTION_BASE = "https://searchconsole.googleapis.com/v1/urlInspection/index:inspect";
|
|
204
|
+
async function inspectUrl(client, request) {
|
|
205
|
+
const body = {
|
|
206
|
+
inspectionUrl: request.inspectionUrl,
|
|
207
|
+
siteUrl: client.siteUrl,
|
|
208
|
+
languageCode: request.languageCode ?? "en"
|
|
209
|
+
};
|
|
210
|
+
const token = await client.request(
|
|
211
|
+
"",
|
|
212
|
+
{
|
|
213
|
+
method: "POST",
|
|
214
|
+
body
|
|
215
|
+
}
|
|
216
|
+
);
|
|
217
|
+
return token.inspectionResult;
|
|
218
|
+
}
|
|
219
|
+
async function inspectUrlDirect(getToken, siteUrl, inspectionUrl, languageCode) {
|
|
220
|
+
const token = await getToken();
|
|
221
|
+
const response = await globalThis.fetch(INSPECTION_BASE, {
|
|
222
|
+
method: "POST",
|
|
223
|
+
headers: {
|
|
224
|
+
Authorization: `Bearer ${token}`,
|
|
225
|
+
"Content-Type": "application/json"
|
|
226
|
+
},
|
|
227
|
+
body: JSON.stringify({
|
|
228
|
+
inspectionUrl,
|
|
229
|
+
siteUrl,
|
|
230
|
+
languageCode: languageCode ?? "en"
|
|
231
|
+
})
|
|
232
|
+
});
|
|
233
|
+
if (!response.ok) {
|
|
234
|
+
const text = await response.text();
|
|
235
|
+
throw new Error(`URL Inspection API error: ${response.status} ${text}`);
|
|
236
|
+
}
|
|
237
|
+
const data = await response.json();
|
|
238
|
+
return data.inspectionResult;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// src/sitemaps.ts
|
|
242
|
+
async function listSitemaps(client) {
|
|
243
|
+
const siteUrl = encodeURIComponent(client.siteUrl);
|
|
244
|
+
const response = await client.request(
|
|
245
|
+
`/sites/${siteUrl}/sitemaps`
|
|
246
|
+
);
|
|
247
|
+
return response.sitemap ?? [];
|
|
248
|
+
}
|
|
249
|
+
async function submitSitemap(client, feedpath) {
|
|
250
|
+
const siteUrl = encodeURIComponent(client.siteUrl);
|
|
251
|
+
const encodedFeed = encodeURIComponent(feedpath);
|
|
252
|
+
await client.request(
|
|
253
|
+
`/sites/${siteUrl}/sitemaps/${encodedFeed}`,
|
|
254
|
+
{ method: "PUT" }
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
async function deleteSitemap(client, feedpath) {
|
|
258
|
+
const siteUrl = encodeURIComponent(client.siteUrl);
|
|
259
|
+
const encodedFeed = encodeURIComponent(feedpath);
|
|
260
|
+
await client.request(
|
|
261
|
+
`/sites/${siteUrl}/sitemaps/${encodedFeed}`,
|
|
262
|
+
{ method: "DELETE" }
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
exports.GSCApiError = GSCApiError;
|
|
267
|
+
exports.createGSCClient = createGSCClient;
|
|
268
|
+
exports.createTokenManager = createTokenManager;
|
|
269
|
+
exports.deleteSitemap = deleteSitemap;
|
|
270
|
+
exports.exchangeRefreshToken = exchangeRefreshToken;
|
|
271
|
+
exports.getServiceAccountToken = getServiceAccountToken;
|
|
272
|
+
exports.inspectUrl = inspectUrl;
|
|
273
|
+
exports.inspectUrlDirect = inspectUrlDirect;
|
|
274
|
+
exports.listSitemaps = listSitemaps;
|
|
275
|
+
exports.querySearchAnalytics = querySearchAnalytics;
|
|
276
|
+
exports.querySearchAnalyticsAll = querySearchAnalyticsAll;
|
|
277
|
+
exports.submitSitemap = submitSitemap;
|
|
278
|
+
//# sourceMappingURL=index.cjs.map
|
|
279
|
+
//# sourceMappingURL=index.cjs.map
|