search-console-axi 0.1.0 → 0.1.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
@@ -1,13 +1,12 @@
1
1
  # search-console-axi
2
2
 
3
- [![CI](https://github.com/Dematom1/search-console-axi/actions/workflows/ci.yml/badge.svg)](https://github.com/Dematom1/search-console-axi/actions/workflows/ci.yml) [![Platform: Linux and macOS](https://img.shields.io/badge/platform-Linux%20%7C%20macOS-blue)](#)
3
+ [![CI](https://github.com/Dematom1/search-console-axi/actions/workflows/ci.yml/badge.svg)](https://github.com/Dematom1/search-console-axi/actions/workflows/ci.yml) [![Platform: Linux and macOS](https://img.shields.io/badge/platform-Linux%20%7C%20macOS-blue)](#) [![npm weekly downloads](https://img.shields.io/npm/dw/search-console-axi)](https://www.npmjs.com/package/search-console-axi)
4
4
 
5
- Read-only Google Search Console reporting and URL inspection for agents. `search-console-axi` is an [AXI](https://github.com/kunchenguid/axi) CLI. Output uses compact [TOON](https://toonformat.dev/) format. Requires Node.js 22.12 or newer.
5
+ Google Search Console reporting, URL inspection, and preview-gated Indexing API notifications for agents. `search-console-axi` is an [AXI](https://github.com/kunchenguid/axi) CLI. Output uses compact [TOON](https://toonformat.dev/) format. Requires Node.js 22.12 or newer.
6
6
 
7
7
  ```sh
8
- npm install
9
- npm run build
10
- node dist/bin/search-console-axi.js --help
8
+ npm i -g search-console-axi
9
+ search-console-axi --help
11
10
  ```
12
11
 
13
12
  ## Authentication
@@ -21,12 +20,44 @@ The CLI validates credential JSON locally and authenticates through `google-auth
21
20
  3. Load its JSON key from your secret manager into `SEARCH_CONSOLE_AXI_SA_KEY`. Never commit the key.
22
21
  4. In Search Console, add the service-account email under **Settings > Users and permissions** with Restricted access.
23
22
 
24
- For local key files, set `GOOGLE_APPLICATION_CREDENTIALS` or run `node dist/bin/search-console-axi.js setup service-account <key.json>`. Credential precedence is `SEARCH_CONSOLE_AXI_SA_KEY`, `GOOGLE_APPLICATION_CREDENTIALS` (with `google_application_credentials` as a fallback alias), the saved path configured by `setup service-account`, then user ADC. Credential files must contain `authorized_user` or `service_account` JSON; service-account registration and `SEARCH_CONSOLE_AXI_SA_KEY` require `service_account` JSON. To switch from a saved key to ADC, run `node dist/bin/search-console-axi.js setup uninstall`; this also removes the CLI's saved quota-project setting. Set the ADC quota project with `gcloud auth application-default set-quota-project <project>` or use `GOOGLE_CLOUD_QUOTA_PROJECT`.
23
+ For local key files, set `GOOGLE_APPLICATION_CREDENTIALS` or run `search-console-axi setup service-account <key.json>`. Credential precedence is `SEARCH_CONSOLE_AXI_SA_KEY`, `GOOGLE_APPLICATION_CREDENTIALS` (with `google_application_credentials` as a fallback alias), the saved path configured by `setup service-account`, then user ADC. Credential files must contain `authorized_user` or `service_account` JSON; service-account registration and `SEARCH_CONSOLE_AXI_SA_KEY` require `service_account` JSON. To switch from a saved key to ADC, run `search-console-axi setup uninstall`; this also removes the CLI's saved quota-project setting. Set the ADC quota project with `gcloud auth application-default set-quota-project <project>` or use `GOOGLE_CLOUD_QUOTA_PROJECT`.
25
24
 
26
- Run `node dist/bin/search-console-axi.js setup` to check credentials and accessible sites. `node dist/bin/search-console-axi.js setup status` reports local credential configuration, not API access or token validity. It includes the credential type and available account email, never credential contents. `node dist/bin/search-console-axi.js setup uninstall` removes only the CLI's local configuration. Registration, saved quota-project updates, and removal re-read the configuration before reporting success.
25
+ Run `search-console-axi setup` to check credentials and accessible sites. `search-console-axi setup status` reports local credential configuration, not API access or token validity. It includes the credential type and available account email, never credential contents. `search-console-axi setup uninstall` removes only the CLI's local configuration. Registration, saved quota-project updates, and removal re-read the configuration before reporting success.
27
26
 
28
- Invalid setup arguments, malformed config, and malformed or unsupported credential data produce `VALIDATION_ERROR` with exit code 2. Config I/O failures produce `CONFIG_ERROR`; missing or unreadable credential-file paths produce `AUTH_CONFIG_ERROR`, both with exit code 1 and repair guidance. `setup status` instead reports invalid config or credentials as `auth.status: invalid` with exit code 0; config I/O failures remain errors. Missing credentials produce setup guidance with `auth.status: not configured` for `setup`, `setup check`, and `setup status`. The default command also reports credential status when credentials cannot be loaded.
27
+ Invalid setup arguments, malformed config, and malformed or unsupported credential data produce `VALIDATION_ERROR` with exit code 2. Config I/O failures produce `CONFIG_ERROR`; missing or unreadable credential-file paths produce `AUTH_CONFIG_ERROR`, both with exit code 1 and repair guidance. `setup status` instead reports invalid config or credentials as `auth.status: invalid` with exit code 0; config I/O failures remain errors. Missing credentials produce setup guidance with `auth.status: not configured` for `setup`, `setup check`, and `setup status`.
29
28
 
30
29
  ## Read Search Console
31
30
 
32
- Run `node dist/bin/search-console-axi.js` for the default site's last seven complete days of clicks, impressions, CTR, position, top queries and pages, and low-CTR opportunities. Use `node dist/bin/search-console-axi.js inspect <url> --site <site-url>` to inspect indexing for a URL. Reporting and inspection do not modify Search Console data; setup may write or remove local configuration.
31
+ Run `search-console-axi` for the default site's last seven complete days of clicks, impressions, CTR, position, top queries and pages, and low-CTR opportunities. Set a default site with `search-console-axi setup site <site-url>`. Reports resolve the site from `--site`, `SEARCH_CONSOLE_AXI_SITE`, the saved default, then the first verified site. Use `search-console-axi inspect <url>` to inspect indexing for a URL; `--site` is optional and uses the same resolution order. Reporting and inspection do not modify Search Console data; setup may write or remove local configuration.
32
+
33
+ ## Send Indexing API notifications
34
+
35
+ Google supports the [Indexing API](https://developers.google.com/search/apis/indexing-api/v3/using-api) only for pages with `JobPosting` or `BroadcastEvent` embedded in `VideoObject` structured data. Job-posting pages fit this scope. It is not a general-purpose indexing API. A successful submission acknowledges a notification, not a crawl or index guarantee.
36
+
37
+ Enable the Indexing API in your Google Cloud project. The service account must be an **owner** of the Search Console property, not merely a Restricted or Full user. The same credential precedence and local configuration apply. Notification commands request `https://www.googleapis.com/auth/indexing`; reporting still requests only `webmasters.readonly`. For user ADC, reauthorize your own Desktop OAuth client with the indexing scope as well as the reporting scopes above. Existing refresh tokens cannot gain scopes automatically.
38
+
39
+ ```sh
40
+ search-console-axi indexing publish https://example.com/jobs/1 --type updated
41
+ search-console-axi indexing publish https://example.com/jobs/1 --type updated --confirm
42
+ search-console-axi indexing publish https://example.com/jobs/1 --type deleted
43
+ search-console-axi indexing status https://example.com/jobs/1
44
+ search-console-axi indexing batch urls.txt --type updated
45
+ search-console-axi indexing batch - --type deleted --confirm < urls.txt
46
+ search-console-axi indexing quota
47
+ ```
48
+
49
+ `publish` and `batch` are local previews until `--confirm`. Previews list every explicit URL target, the notification count, and the HTTP request count without loading credentials or calling Google. Batch input contains one absolute HTTP or HTTPS URL per line; blank lines are ignored. Duplicate URLs remain separate requests. URLs with embedded credentials, fragments, or whitespace are rejected. All input is validated before any submission. Each multipart batch contains at most 100 notifications, and each notification consumes quota separately.
50
+
51
+ Before `--type deleted`, the page must return HTTP 404 or 410 or contain a `noindex` directive. `status` reads `urlNotifications.getMetadata`: the last notification times, not the page's indexing status. Use `inspect` for index status.
52
+
53
+ Confirmed batches report every URL as `submitted`, `failed`, or `unknown`, with an HTTP status where available. Any failed or unknown result sets exit code 1. Authentication, API, and transport errors omit raw server messages and credential contents. A 403 explains the owner, API enablement, and scope requirements; a 429 explains quota exhaustion. Requests are not automatically retried. An unknown outcome may already have reached Google; check notification status before retrying. Successful URLs in a partially failed batch must not be resubmitted blindly.
54
+
55
+ ### Read project quota
56
+
57
+ The Indexing API has no usage endpoint. `indexing quota` reads effective limits from Service Usage and today's observed request counts from Cloud Monitoring. The selected project is the configured quota project sent with requests, or the credential's `project_id` if no override exists. The output identifies that project and the source. User ADC without either project requires `setup --quota-project <project>`.
58
+
59
+ Quota reads request `cloud-platform.read-only` and `monitoring.read` OAuth scopes. User ADC with `cloud-platform` also supports both endpoints. Limits require `serviceusage.quotas.get`; usage requires `monitoring.timeSeries.list` on the selected project. These optional IAM permissions are separate from Search Console ownership. The Service Usage and Cloud Monitoring APIs must be enabled.
60
+
61
+ Usage covers midnight Pacific Time through the query time. Counts include completed requests and failures, grouped by API method, and may lag up to 30 minutes. These are observed requests, not authoritative daily publish quota consumption. Empty time series mean unknown, not zero. Unreadable limits or usage identify the required permission rather than inventing a number. A readable half remains available if the other fails.
62
+
63
+ The [documented defaults](https://developers.google.com/search/apis/indexing-api/v3/quota-pricing) are labelled separately: 200 publish requests per day, 180 metadata requests per minute, and 380 total requests per minute. They are not reported as your project's actual limit or remaining allowance.
package/dist/bin/auth.js CHANGED
@@ -172,7 +172,7 @@ export async function getAuthClient(options = {}) {
172
172
  keyId: fileCredentials.private_key_id,
173
173
  projectId: fileCredentials.project_id,
174
174
  universeDomain: fileCredentials.universe_domain,
175
- scopes: SCOPES,
175
+ scopes: options.scopes ?? SCOPES,
176
176
  })
177
177
  : new UserRefreshClient({
178
178
  clientId: fileCredentials.client_id,
@@ -191,7 +191,7 @@ export async function getAuthClient(options = {}) {
191
191
  };
192
192
  }
193
193
  const auth = (options.authFactory ?? ((opts) => new GoogleAuth(opts)))({
194
- scopes: SCOPES,
194
+ scopes: options.scopes ?? SCOPES,
195
195
  ...(quotaOverride ? { clientOptions: { quotaProjectId: quotaOverride } } : {}),
196
196
  });
197
197
  let credential;
@@ -0,0 +1,428 @@
1
+ import { AxiError } from "axi-sdk-js";
2
+ import { encode } from "@toon-format/toon";
3
+ import { readFileSync } from "node:fs";
4
+ import { randomUUID } from "node:crypto";
5
+ import { getAuthClient } from "./auth.js";
6
+ const base = "https://indexing.googleapis.com";
7
+ export const indexingScopes = ["https://www.googleapis.com/auth/indexing"];
8
+ const help = `Indexing API: JobPosting or BroadcastEvent embedded in VideoObject pages only.
9
+ Service accounts must be Search Console property owners. Notifications do not guarantee indexing.
10
+ Usage:
11
+ search-console-axi indexing publish <url> --type updated|deleted [--confirm]
12
+ search-console-axi indexing status <url>
13
+ search-console-axi indexing batch <file|-> --type updated|deleted [--confirm]
14
+ search-console-axi indexing quota
15
+ Batch input: one HTTP(S) URL per line; '-' reads stdin. Preview lists every URL and request count.
16
+ Writes preview without credentials; --confirm submits. Each URL is the explicit writable target.
17
+ Deleted pages must first return 404/410 or contain noindex. No automatic retries.
18
+ Quota uses the configured quota project (sent with requests), then the credential project_id.
19
+ Examples:
20
+ search-console-axi indexing publish https://example.com/jobs/1 --type updated
21
+ search-console-axi indexing batch urls.txt --type deleted --confirm
22
+ search-console-axi indexing status https://example.com/jobs/1`;
23
+ const invalid = (message) => {
24
+ throw new AxiError(message, "VALIDATION_ERROR", [help]);
25
+ };
26
+ function isObject(value) {
27
+ return value !== null && typeof value === "object" && !Array.isArray(value);
28
+ }
29
+ function object(value) {
30
+ return isObject(value) ? value : {};
31
+ }
32
+ function statusCode(error) {
33
+ const response = object(object(error).response);
34
+ return typeof response.status === "number" ? response.status : 0;
35
+ }
36
+ function reasons(error) {
37
+ const body = object(object(object(error).response).data);
38
+ const info = object(body.error);
39
+ return [...(Array.isArray(info.details) ? info.details : []), ...(Array.isArray(info.errors) ? info.errors : [])].map((item) => object(item).reason);
40
+ }
41
+ function failure(status) {
42
+ if (status === 403)
43
+ return "Access denied: verify the service account is an owner of the Search Console property, the Indexing API is enabled, and credentials grant the indexing scope";
44
+ if (status === 429)
45
+ return "Indexing API quota exceeded; wait for quota reset or request a quota increase";
46
+ if (status === 401)
47
+ return "Authentication failed; check configured credentials and indexing scope";
48
+ if (status === 404)
49
+ return "No notification metadata found for this URL";
50
+ return status
51
+ ? `Indexing API request failed (HTTP ${status})`
52
+ : "Indexing API authentication or network request failed";
53
+ }
54
+ async function request(auth, options) {
55
+ try {
56
+ return await auth.client.request({ ...options, retry: false });
57
+ }
58
+ catch (error) {
59
+ const why = reasons(error);
60
+ const message = why.includes("SERVICE_DISABLED") || why.includes("accessNotConfigured")
61
+ ? "Enable the Google Indexing API in the request's consumer project"
62
+ : why.includes("ACCESS_TOKEN_SCOPE_INSUFFICIENT")
63
+ ? "Credentials lack the https://www.googleapis.com/auth/indexing OAuth scope; reauthorize user ADC or check the service-account configuration"
64
+ : failure(statusCode(error));
65
+ throw new AxiError(message, "INDEXING_ERROR", [
66
+ "Check `search-console-axi indexing --help`; do not blindly retry a submission with an unknown outcome",
67
+ ]);
68
+ }
69
+ }
70
+ function urlInput(value) {
71
+ try {
72
+ const url = new URL(value);
73
+ if (Buffer.byteLength(JSON.stringify(value), "utf8") > 1_000_000 - 1024)
74
+ return invalid("URL exceeds the batch part size limit of 1 MB");
75
+ if (!/^https?:\/\//i.test(value) ||
76
+ !["http:", "https:"].includes(url.protocol) ||
77
+ url.username ||
78
+ url.password ||
79
+ url.hash ||
80
+ /[\\#\s]/.test(value) ||
81
+ [...value].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127))
82
+ return invalid("URLs must be absolute HTTP(S) URLs without credentials, fragments, or whitespace");
83
+ return value;
84
+ }
85
+ catch (error) {
86
+ if (error instanceof AxiError)
87
+ throw error;
88
+ return invalid("Expected an absolute HTTP(S) URL without credentials");
89
+ }
90
+ }
91
+ function metadata(value) {
92
+ const data = object(value);
93
+ const notification = (value) => {
94
+ const item = object(value);
95
+ return {
96
+ ...(item.type === "URL_UPDATED" || item.type === "URL_DELETED" ? { type: item.type } : {}),
97
+ ...(typeof item.notifyTime === "string" && /^\d{4}-\d\d-\d\dT[\d:.]+Z$/.test(item.notifyTime)
98
+ ? { notify_time: item.notifyTime }
99
+ : {}),
100
+ };
101
+ };
102
+ return { latest_update: notification(data.latestUpdate), latest_remove: notification(data.latestRemove) };
103
+ }
104
+ export function parseBatch(body, contentType, urls) {
105
+ const boundary = /boundary=(?:"([^"]+)"|([^;\s]+))/i.exec(contentType);
106
+ const delimiter = boundary?.[1] ?? boundary?.[2];
107
+ const parts = delimiter ? body.split(`--${delimiter}`).slice(1, -1) : [];
108
+ const byId = new Map();
109
+ const duplicates = new Set();
110
+ for (const part of parts) {
111
+ const id = /Content-ID:\s*<(?:response-)?item-(\d+)>/i.exec(part)?.[1];
112
+ const http = /HTTP\/1\.[01]\s+(\d{3})[^\r\n]*\r?\n/.exec(part);
113
+ if (id === undefined || !http)
114
+ continue;
115
+ const index = Number(id);
116
+ const status = Number(http[1]);
117
+ if (byId.has(index))
118
+ duplicates.add(index);
119
+ const payload = part
120
+ .slice((http.index ?? 0) + http[0].length)
121
+ .split(/\r?\n\r?\n/)
122
+ .slice(1)
123
+ .join("\n\n")
124
+ .trim();
125
+ let data;
126
+ try {
127
+ data = JSON.parse(payload);
128
+ }
129
+ catch {
130
+ data = undefined;
131
+ }
132
+ byId.set(index, {
133
+ status: status >= 200 && status < 300 && data === undefined ? 0 : status,
134
+ metadata: metadata(object(data).urlNotificationMetadata ?? data),
135
+ });
136
+ }
137
+ return urls.map((url, index) => {
138
+ const item = byId.get(index);
139
+ if (!item || duplicates.has(index) || !item.status)
140
+ return {
141
+ url,
142
+ status: "unknown",
143
+ http_status: 0,
144
+ error: "Missing or malformed batch result; check status before retrying",
145
+ };
146
+ return item.status >= 200 && item.status < 300
147
+ ? { url, status: "submitted", http_status: item.status, ...item.metadata }
148
+ : { url, status: "failed", http_status: item.status, error: failure(item.status) };
149
+ });
150
+ }
151
+ export async function indexingCommand(args, suppliedAuth) {
152
+ if (args.includes("--help") || args.includes("-h"))
153
+ return help;
154
+ const [action, ...rest] = args;
155
+ if (!["publish", "status", "batch", "quota"].includes(action ?? ""))
156
+ return invalid("Expected indexing publish, status, batch, or quota");
157
+ const writing = action === "publish" || action === "batch";
158
+ const positionals = [];
159
+ let type;
160
+ let confirm = false;
161
+ for (let index = 0; index < rest.length; index++) {
162
+ const arg = rest[index];
163
+ if (arg === "--confirm" && writing && !confirm)
164
+ confirm = true;
165
+ else if (arg === "--type" && writing && type === undefined) {
166
+ const value = rest[++index];
167
+ if (value !== "updated" && value !== "deleted")
168
+ return invalid("--type requires updated or deleted");
169
+ type = value === "updated" ? "URL_UPDATED" : "URL_DELETED";
170
+ }
171
+ else if (arg?.startsWith("-") && arg !== "-")
172
+ return invalid(`Unknown or repeated indexing option '${arg}'; valid flags: ${writing ? "--type, --confirm, " : ""}--help`);
173
+ else if (arg)
174
+ positionals.push(arg);
175
+ }
176
+ if (positionals.length !== (action === "quota" ? 0 : 1) || (writing && !type))
177
+ return invalid("Invalid arguments; writes require one target and --type updated|deleted");
178
+ const target = positionals[0] ?? "";
179
+ let urls = [];
180
+ if (action === "batch") {
181
+ let text;
182
+ try {
183
+ text = readFileSync(target === "-" ? 0 : target, "utf8");
184
+ }
185
+ catch {
186
+ return invalid("Could not read batch input; check the supplied file path or stdin");
187
+ }
188
+ urls = text
189
+ .split(/\r?\n/)
190
+ .map((line) => line.trim())
191
+ .filter(Boolean)
192
+ .map(urlInput);
193
+ if (!urls.length)
194
+ return invalid("Batch input contains no URLs");
195
+ }
196
+ else if (action !== "quota")
197
+ urls = [urlInput(target)];
198
+ if (writing && !confirm)
199
+ return encode({
200
+ mode: "preview",
201
+ type,
202
+ request_count: urls.length,
203
+ http_request_count: action === "batch" ? Math.ceil(urls.length / 100) : 1,
204
+ urls,
205
+ help: ["Repeat the same command with --confirm to submit these exact targets"],
206
+ });
207
+ let auth = suppliedAuth;
208
+ if (!auth) {
209
+ try {
210
+ auth = await getAuthClient({
211
+ scopes: action === "quota"
212
+ ? [
213
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
214
+ "https://www.googleapis.com/auth/monitoring.read",
215
+ ]
216
+ : indexingScopes,
217
+ });
218
+ }
219
+ catch (error) {
220
+ if (error instanceof AxiError)
221
+ throw error;
222
+ throw new AxiError("Could not load configured Google credentials", "AUTH_CONFIG_ERROR", [
223
+ "Check credential paths and variables with search-console-axi setup status",
224
+ ]);
225
+ }
226
+ }
227
+ if (action === "quota")
228
+ return quota(auth);
229
+ if (action === "status") {
230
+ const response = await request(auth, {
231
+ url: `${base}/v3/urlNotifications/metadata`,
232
+ params: { url: target },
233
+ method: "GET",
234
+ });
235
+ return encode({
236
+ url: target,
237
+ ...metadata(response.data),
238
+ note: "Notification receipt only; not crawl or index status",
239
+ });
240
+ }
241
+ if (action === "publish") {
242
+ const response = await request(auth, {
243
+ url: `${base}/v3/urlNotifications:publish`,
244
+ method: "POST",
245
+ headers: { "Content-Type": "application/json" },
246
+ data: { url: target, type },
247
+ });
248
+ return encode({
249
+ mode: "submitted",
250
+ request_count: 1,
251
+ results: [{ url: target, status: "submitted", ...metadata(object(response.data).urlNotificationMetadata) }],
252
+ });
253
+ }
254
+ const results = [];
255
+ for (let start = 0; start < urls.length; start += 100) {
256
+ const chunk = urls.slice(start, start + 100);
257
+ const boundary = `axi_${randomUUID()}`;
258
+ const data = chunk
259
+ .map((url, index) => `--${boundary}\r\nContent-Type: application/http\r\nContent-ID: <item-${index}>\r\n\r\nPOST /v3/urlNotifications:publish HTTP/1.1\r\nContent-Type: application/json\r\n\r\n${JSON.stringify({ url, type })}\r\n`)
260
+ .join("") + `--${boundary}--\r\n`;
261
+ try {
262
+ const response = await request(auth, {
263
+ url: `${base}/batch`,
264
+ method: "POST",
265
+ headers: { "Content-Type": `multipart/mixed; boundary=${boundary}` },
266
+ data,
267
+ responseType: "text",
268
+ });
269
+ results.push(...parseBatch(typeof response.data === "string" ? response.data : "", response.headers.get("content-type") ?? "", chunk));
270
+ }
271
+ catch (error) {
272
+ // A batch transport failure can occur after acceptance; never retry automatically.
273
+ results.push(...chunk.map((url) => ({
274
+ url,
275
+ status: "unknown",
276
+ http_status: 0,
277
+ error: error instanceof AxiError ? error.message : "Batch outcome unknown; check status before retrying",
278
+ })));
279
+ }
280
+ }
281
+ const failed = results.filter((item) => item.status !== "submitted").length;
282
+ if (failed)
283
+ process.exitCode = 1;
284
+ return encode({ mode: "submitted", request_count: urls.length, submitted: results.length - failed, failed, results });
285
+ }
286
+ function pacificMidnight(now) {
287
+ const date = new Intl.DateTimeFormat("en-CA", {
288
+ timeZone: "America/Los_Angeles",
289
+ year: "numeric",
290
+ month: "2-digit",
291
+ day: "2-digit",
292
+ }).format(now);
293
+ const midnight = Date.parse(`${date}T00:00:00Z`);
294
+ let instant = midnight;
295
+ for (let i = 0; i < 3; i++) {
296
+ const offset = new Intl.DateTimeFormat("en", { timeZone: "America/Los_Angeles", timeZoneName: "shortOffset" })
297
+ .formatToParts(new Date(instant))
298
+ .find((part) => part.type === "timeZoneName")?.value;
299
+ const hours = Number(/GMT([+-]\d+)/.exec(offset ?? "")?.[1] ?? 0);
300
+ instant = midnight - hours * 3_600_000;
301
+ }
302
+ return new Date(instant).toISOString();
303
+ }
304
+ function quotaFailure(error, service) {
305
+ const why = reasons(error);
306
+ if (why.includes("SERVICE_DISABLED") || why.includes("accessNotConfigured"))
307
+ return `Enable the ${service} API in the selected project; no measurement is available`;
308
+ const scope = service === "Service Usage" ? "cloud-platform.read-only or cloud-platform" : "monitoring.read or cloud-platform";
309
+ if (why.includes("ACCESS_TOKEN_SCOPE_INSUFFICIENT"))
310
+ return `Credentials lack a required OAuth scope: ${scope}`;
311
+ const permission = service === "Service Usage" ? "serviceusage.quotas.get" : "monitoring.timeSeries.list";
312
+ return statusCode(error) === 403
313
+ ? `Access denied: requires ${permission} on the selected project and ${scope} OAuth scope`
314
+ : `${service} unavailable; check API enablement and configured credentials`;
315
+ }
316
+ async function quota(auth) {
317
+ const documented_defaults = {
318
+ source: "https://developers.google.com/search/apis/indexing-api/v3/quota-pricing",
319
+ publish_per_day: 200,
320
+ metadata_per_minute: 180,
321
+ requests_per_minute: 380,
322
+ note: "Documentation only; not this project's measured limits",
323
+ };
324
+ const projectId = auth.quotaProjectId ?? auth.projectId;
325
+ if (!projectId)
326
+ return encode({
327
+ limits: "unavailable: no quota project or credential project_id",
328
+ usage_today: "unavailable: configure a quota project with search-console-axi setup --quota-project <project>",
329
+ documented_defaults,
330
+ });
331
+ const project = encodeURIComponent(projectId);
332
+ const now = new Date();
333
+ const start = pacificMidnight(now);
334
+ const limits = [];
335
+ const usage = [];
336
+ let limitsError;
337
+ let usageError;
338
+ try {
339
+ let pageToken;
340
+ do {
341
+ const response = await auth.client.request({
342
+ url: `https://serviceusage.googleapis.com/v1beta1/projects/${project}/services/indexing.googleapis.com/consumerQuotaMetrics`,
343
+ params: { view: "FULL", pageSize: 200, ...(pageToken ? { pageToken } : {}) },
344
+ retry: false,
345
+ });
346
+ const data = object(response.data);
347
+ for (const value of Array.isArray(data.metrics) ? data.metrics : []) {
348
+ const metric = object(value);
349
+ for (const value of Array.isArray(metric.consumerQuotaLimits) ? metric.consumerQuotaLimits : []) {
350
+ const limit = object(value);
351
+ for (const value of Array.isArray(limit.quotaBuckets) ? limit.quotaBuckets : []) {
352
+ const bucket = object(value);
353
+ if (typeof metric.metric === "string" &&
354
+ typeof limit.unit === "string" &&
355
+ (typeof bucket.effectiveLimit === "string" || typeof bucket.effectiveLimit === "number"))
356
+ limits.push({
357
+ metric: metric.metric,
358
+ unit: limit.unit,
359
+ effective_limit: String(bucket.effectiveLimit),
360
+ dimensions: object(bucket.dimensions),
361
+ });
362
+ }
363
+ }
364
+ }
365
+ pageToken = typeof data.nextPageToken === "string" && data.nextPageToken ? data.nextPageToken : undefined;
366
+ } while (pageToken);
367
+ }
368
+ catch (error) {
369
+ limitsError = quotaFailure(error, "Service Usage");
370
+ }
371
+ try {
372
+ let pageToken;
373
+ do {
374
+ const response = await auth.client.request({
375
+ url: `https://monitoring.googleapis.com/v3/projects/${project}/timeSeries`,
376
+ params: {
377
+ filter: 'metric.type="serviceruntime.googleapis.com/api/request_count" AND resource.type="consumed_api" AND resource.labels.service="indexing.googleapis.com"',
378
+ "interval.startTime": start,
379
+ "interval.endTime": now.toISOString(),
380
+ view: "FULL",
381
+ pageSize: 100000,
382
+ ...(pageToken ? { pageToken } : {}),
383
+ },
384
+ retry: false,
385
+ });
386
+ const data = object(response.data);
387
+ for (const value of Array.isArray(data.timeSeries) ? data.timeSeries : []) {
388
+ const series = object(value);
389
+ const labels = object(object(series.resource).labels);
390
+ if (!Array.isArray(series.points) || !series.points.length)
391
+ continue;
392
+ let requests = 0;
393
+ for (const point of series.points) {
394
+ const count = object(object(point).value).int64Value;
395
+ if (typeof count !== "string" || !/^\d+$/.test(count) || !Number.isSafeInteger(Number(count)))
396
+ throw new Error("Invalid count");
397
+ requests += Number(count);
398
+ }
399
+ usage.push({ method: typeof labels.method === "string" ? labels.method : "unspecified", requests });
400
+ }
401
+ pageToken = typeof data.nextPageToken === "string" && data.nextPageToken ? data.nextPageToken : undefined;
402
+ } while (pageToken);
403
+ }
404
+ catch (error) {
405
+ usageError = quotaFailure(error, "Cloud Monitoring");
406
+ }
407
+ const counts = new Map();
408
+ for (const item of usage)
409
+ counts.set(item.method, (counts.get(item.method) ?? 0) + item.requests);
410
+ const by_method = [...counts].map(([method, requests]) => ({ method, requests }));
411
+ return encode({
412
+ project: projectId,
413
+ project_source: auth.quotaProjectId ? "quota_project" : "credential_project",
414
+ limits: limitsError ?? (limits.length ? limits : "No quota limits returned; unknown, not zero"),
415
+ usage_today: {
416
+ start,
417
+ end: now.toISOString(),
418
+ timezone: "America/Los_Angeles",
419
+ source: "Cloud Monitoring serviceruntime.googleapis.com/api/request_count",
420
+ status: usageError ?? (usage.length ? "observed" : "No time series returned; unknown, not zero"),
421
+ ...(usageError || !usage.length
422
+ ? {}
423
+ : { total_observed_requests: by_method.reduce((sum, item) => sum + item.requests, 0), by_method }),
424
+ note: "Observed completed API requests, including failures; not authoritative publish quota consumption. Metrics may lag up to 30 minutes",
425
+ },
426
+ documented_defaults,
427
+ });
428
+ }
@@ -1,26 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import { runAxiCli } from "axi-sdk-js";
3
- import { readFileSync } from "node:fs";
4
- import { getAuthClient, setupCommand } from "./auth.js";
5
- import { runHome } from "./setup-check.js";
6
- const version = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
7
- const description = "Read-only Google Search Console reporting and URL inspection for agents";
8
- const args = process.argv.slice(2);
9
- await runAxiCli({
10
- description,
11
- version,
12
- argv: args,
13
- topLevelHelp: `${description}\n\nUsage: search-console-axi [--help] [--version]\n\nCommands:\n setup Configure, inspect, or remove authentication\n inspect Inspect a URL's index status`,
14
- commands: {
15
- setup: setupCommand,
16
- inspect: (args) => setupCommand(["inspect", ...args]),
17
- },
18
- home: async () => {
19
- try {
20
- return await runHome(await getAuthClient());
21
- }
22
- catch {
23
- return setupCommand(["status"]);
24
- }
25
- },
26
- });
2
+ import { runAxiCli } from "../src/cli.js";
3
+ await runAxiCli();
@@ -13,7 +13,7 @@ export const setupGuide = [
13
13
  },
14
14
  {
15
15
  step: 5,
16
- instruction: "For personal access, use your own Desktop OAuth client and run gcloud auth application-default login --client-id-file=client.json --scopes=https://www.googleapis.com/auth/webmasters.readonly,https://www.googleapis.com/auth/cloud-platform.",
16
+ instruction: "For personal access, use your own Desktop OAuth client. Search Console reporting uses https://www.googleapis.com/auth/webmasters.readonly; Indexing API commands use https://www.googleapis.com/auth/indexing, and quota reads use https://www.googleapis.com/auth/cloud-platform. Include the needed scopes with gcloud auth application-default login --client-id-file=client.json --scopes=... .",
17
17
  },
18
18
  ];
19
19
  function apiDisabledMessage(error) {
@@ -0,0 +1,33 @@
1
+ import { AxiError } from "axi-sdk-js";
2
+ export function parseArgs(args, valueFlags, booleanFlags = []) {
3
+ const values = new Set(valueFlags);
4
+ const booleans = new Set(booleanFlags);
5
+ const positionals = [];
6
+ const flags = new Map();
7
+ for (let i = 0; i < args.length; i++) {
8
+ const token = args[i];
9
+ if (token === "-" || !token.startsWith("-")) {
10
+ positionals.push(token);
11
+ continue;
12
+ }
13
+ const equal = token.indexOf("=");
14
+ const name = equal < 0 ? token : token.slice(0, equal);
15
+ const inline = equal < 0 ? undefined : token.slice(equal + 1);
16
+ if (flags.has(name))
17
+ throw usage(`Repeated option '${name}'`);
18
+ if (values.has(name)) {
19
+ const value = inline ?? args[++i];
20
+ if (value === undefined || value === "" || (inline === undefined && value.startsWith("--")))
21
+ throw usage(`${name} requires a value`);
22
+ flags.set(name, value);
23
+ }
24
+ else if (booleans.has(name) && inline === undefined)
25
+ flags.set(name, true);
26
+ else
27
+ throw usage(`Unknown option '${name}'`);
28
+ }
29
+ return { positionals, flags };
30
+ }
31
+ export function usage(message) {
32
+ throw new AxiError(message, "VALIDATION_ERROR", ["Run `search-console-axi --help` for valid commands and options"]);
33
+ }