@blinkhost/cli 2.5.2 → 2.6.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/CHANGELOG.md CHANGED
@@ -2,6 +2,21 @@
2
2
 
3
3
  This file records customer-visible CLI changes. BlinkHost uses semantic versioning for the CLI, while security and migration impact are classified separately. A patch may therefore require prompt action, and a major release may coexist with an earlier supported line during its documented migration window.
4
4
 
5
+ ## 2.6.0 — SEO and AEO commands
6
+
7
+ Adds `seo local`, hosted audits and findings, baseline verification, cancellation,
8
+ diagnostics, field reports, normalized imports and documentation evaluation.
9
+ Adds public-deployment content indexing, scoped documentation retrieval, index
10
+ deletion, selected-model answer samples and prepaid Azure public research with
11
+ status, polling and cancellation. Search and model submissions require a stable
12
+ request UUID; model work uses ordinary Idam, and public research also requires
13
+ explicit consent and verified prepaid USD funds. Native owner imports support
14
+ Google Search Console CSV/ZIP and Bing Webmaster CSV exports.
15
+ Remediation passes the selected model, credit limit and request identity to
16
+ ordinary Idam. Hosted features depend on server rollout and subscription grants.
17
+ Queued audits must be polled to a terminal result before interpreting their gate.
18
+ Local checks cover title, description and canonical metadata only.
19
+
5
20
  ## 2.5.2 — Deployment request recovery
6
21
 
7
22
  Activate, promote, retry and rollback now require a saved `--idempotency-key`.
package/README.md CHANGED
@@ -7,13 +7,61 @@ The BlinkHost CLI brings project setup, local development, source control, previ
7
7
  Node.js 22.12 or newer is required.
8
8
 
9
9
  ```bash
10
- npm install --global @blinkhost/cli@2.5.2
10
+ npm install --global @blinkhost/cli@2.6.0
11
11
  blinkhost --version
12
12
  ```
13
13
 
14
14
  Signed release archives, checksums, the CycloneDX SBOM, and Sigstore verification bundle are available at <https://github.com/blinkhost-ltd/blinkhost-cli/releases>.
15
15
 
16
- ## Current release
16
+ ## 2.6.0 — SEO and AEO commands
17
+
18
+ Run `blinkhost seo local ./out --gate --json` to check local HTML metadata,
19
+ or `blinkhost seo audit PROJECT_UUID --pages 10 --json` for a hosted audit.
20
+ Use `blinkhost seo findings PROJECT_UUID AUDIT_UUID --json` until the audit is
21
+ terminal, then inspect its coverage and gate. `blinkhost seo --help` lists
22
+ verification, imports, reports and selected-model Idam remediation commands.
23
+ Hosted access requires an enabled server and an existing subscription allowance.
24
+ Upgrade from 2.5.2 to use these commands.
25
+
26
+ The same release adds these workflows:
27
+
28
+ | Workflow | Commands |
29
+ | --- | --- |
30
+ | Public deployment documentation | `content-status`, `content-index`, `content-search`, `content-result`, `content-delete` |
31
+ | Selected-model answer experiments | `sample`, `samples`, `sample-result`, `sample-delete` |
32
+ | Prepaid Azure public research | `research-status`, `research`, `research-result`, `research-cancel` |
33
+ | Owner search reports | `import-native PROJECT_UUID FORMAT EXPORT_FILE PROVENANCE.json` |
34
+
35
+ Search, sample and research submissions read a JSON request file. Give each new
36
+ request a UUID in `client_request_id`, retain that file when recovering a lost
37
+ response, and poll the returned ID. For example, `content-search` accepts:
38
+
39
+ ```json
40
+ {"client_request_id":"b3af715d-7276-42b7-908c-ea8c59ef019e","query":"How do I deploy?","count":5,"locale":"en"}
41
+ ```
42
+
43
+ `sample` accepts `model`, `maximum_units`, `question`, one to five public `paths`
44
+ and `required_facts`, alongside the request UUID. The chosen permitted model uses
45
+ ordinary Idam and its AI wallet. Results show documentation support and missing
46
+ facts for that experiment; they do not establish visibility in external AI apps.
47
+
48
+ `research` requires all six fields:
49
+
50
+ ```json
51
+ {"client_request_id":"8bfb3b6c-3b0a-41fd-80d7-af6879fb4036","model":"YOUR_PERMITTED_MODEL","maximum_units":100,"query":"Public documentation about sitemap indexes","max_reads":1,"public_query_consent":true}
52
+ ```
53
+
54
+ Use `research-status` to inspect available prepaid USD and the per-read hold.
55
+ Ordinary Idam model work uses the AI wallet; Azure public search and its grounding
56
+ model use the separate research allowance funded by verified checkout. Cancelling
57
+ prevents future reads; already sent reads still settle their actual cost.
58
+
59
+ Native imports accept `google-search-console-csv`, `google-search-console-zip`
60
+ and `bing-webmaster-csv`. Supply the authorized property, reporting period and
61
+ other provenance in the separate JSON file. The server validates report ownership
62
+ and supported dimensions before retaining it.
63
+
64
+ ## Earlier releases
17
65
 
18
66
  ### 2.5.2 — deployment request recovery
19
67
 
@@ -231,6 +279,23 @@ blinkhost help create
231
279
 
232
280
  `quickstart` is local, read-only, and makes no network requests. It checks Node.js, Git, the operating-system credential service, the selected directory, and any existing BlinkHost manifest. It never signs in, uploads source, creates a cloud resource, or incurs usage. The bundled `docs` reference is offline and matches the installed CLI version; use the linked web documentation for longer guides.
233
281
 
282
+ ## SEO and AEO request retries
283
+
284
+ Hosted audits, verification and Idam remediation accept `--request-id REQUEST_UUID`:
285
+
286
+ ```bash
287
+ blinkhost seo audit PROJECT_UUID --pages 100 --request-id REQUEST_UUID
288
+ blinkhost seo verify PROJECT_UUID AUDIT_UUID --request-id REQUEST_UUID
289
+ blinkhost seo remediate PROJECT_UUID AUDIT_UUID --model MODEL --max-units 100 --findings FINDING_KEY --request-id REQUEST_UUID
290
+ ```
291
+
292
+ Choose a UUID for each new task and keep it with the command. After a timeout or
293
+ lost response, retry the same command with the same UUID and unchanged inputs.
294
+ This lets the server reuse the original task and wallet hold. Changing the model,
295
+ wallet limit, findings or audit options requires a fresh UUID for a new task.
296
+ If omitted, the CLI generates an ID and includes it as `SEO request ID` in a
297
+ submission error, so you can supply it with `--request-id` when retrying.
298
+
234
299
  ## Connect an account
235
300
 
236
301
  ```bash
package/dist/cli.js CHANGED
@@ -11,6 +11,7 @@ import { createScaffold } from './templates.js';
11
11
  import { ApiClient } from './api.js';
12
12
  import { login, logout } from './auth.js';
13
13
  import { runAssistant } from './assistant.js';
14
+ import { runSeo } from './seo.js';
14
15
  import { exportProject } from './project-export.js';
15
16
  import { activeProfile, readConfig, validateProfileName, writeConfig } from './config.js';
16
17
  import { openPreview, projectStatus, rawApi, readProjectLink, runFunctions, runRemote, runSecrets, syncProject, unlinkProject, uploadAsset, waitForRemote, writeProjectLink } from './remote.js';
@@ -319,6 +320,13 @@ export async function main(argv = process.argv.slice(2)) {
319
320
  const result = await runAssistant(args, profile);
320
321
  emit({ ok: true, command: 'ai', ...result }, json);
321
322
  }
323
+ else if (command === 'seo') {
324
+ const data = await runSeo(args, profile);
325
+ emit({ ok: true, command, message: 'SEO evidence loaded.', data }, json);
326
+ const gate = data.summary?.gate ?? data.gate;
327
+ if (gate && !gate.passed)
328
+ return EXIT.validation;
329
+ }
322
330
  else if (command === 'auth') {
323
331
  const action = args.shift() || 'status';
324
332
  if (action === 'login') {
@@ -8,7 +8,7 @@ export interface DocumentationTopic {
8
8
  related: string[];
9
9
  url: string;
10
10
  }
11
- export declare const TOP_LEVEL_COMMANDS: ("plugins" | "profile" | "modules" | "dev" | "databases" | "secrets" | "manifest" | "projects" | "repositories" | "connections" | "previews" | "builds" | "deployments" | "bindings" | "assets" | "organizations" | "templates" | "approvals" | "handoffs" | "policies" | "workloads" | "create" | "update" | "ai" | "auth" | "quickstart" | "init" | "doctor" | "validate" | "test" | "ci" | "functions" | "logs" | "support" | "metrics" | "analytics" | "completion" | "api" | "docs")[];
11
+ export declare const TOP_LEVEL_COMMANDS: ("plugins" | "profile" | "modules" | "dev" | "databases" | "secrets" | "manifest" | "projects" | "repositories" | "connections" | "previews" | "builds" | "deployments" | "bindings" | "assets" | "organizations" | "templates" | "approvals" | "handoffs" | "policies" | "workloads" | "create" | "update" | "seo" | "ai" | "ci" | "auth" | "quickstart" | "init" | "doctor" | "validate" | "test" | "functions" | "logs" | "support" | "metrics" | "analytics" | "completion" | "api" | "docs")[];
12
12
  export declare function documentationIndex(): {
13
13
  schema: string;
14
14
  cli_version: string;
package/dist/guidance.js CHANGED
@@ -27,6 +27,12 @@ const resource = (name, summary, extra = []) => ({
27
27
  url: DOCUMENTATION_URL,
28
28
  });
29
29
  const TOPICS = {
30
+ seo: {
31
+ name: 'seo', title: 'SEO and AEO audits', summary: 'Check local HTML or published public deployments, then verify selected fixes.', url: `${DOCUMENTATION_URL}/seo`,
32
+ usage: ['blinkhost seo local DIRECTORY [--gate]', 'blinkhost seo audit PROJECT_UUID [--pages N] [--browser-pages N] [--gate] [--request-id REQUEST_UUID]', 'blinkhost seo findings PROJECT_UUID AUDIT_UUID', 'blinkhost seo verify PROJECT_UUID AUDIT_UUID [--gate] [--request-id REQUEST_UUID]', 'blinkhost seo cancel PROJECT_UUID AUDIT_UUID', 'blinkhost seo diagnostics PROJECT_UUID', 'blinkhost seo field PROJECT_UUID', 'blinkhost seo import PROJECT_UUID FILE.json', 'blinkhost seo import-native PROJECT_UUID FORMAT EXPORT_FILE PROVENANCE.json', 'blinkhost seo docs-evaluate PROJECT_UUID FILE.json', 'blinkhost seo content-status PROJECT_UUID', 'blinkhost seo content-index PROJECT_UUID', 'blinkhost seo content-delete PROJECT_UUID', 'blinkhost seo content-search PROJECT_UUID REQUEST.json', 'blinkhost seo content-result PROJECT_UUID QUERY_UUID', 'blinkhost seo sample PROJECT_UUID REQUEST.json', 'blinkhost seo samples PROJECT_UUID', 'blinkhost seo sample-result PROJECT_UUID SAMPLE_UUID', 'blinkhost seo sample-delete PROJECT_UUID SAMPLE_UUID', 'blinkhost seo research PROJECT_UUID REQUEST.json', 'blinkhost seo research-status PROJECT_UUID', 'blinkhost seo research-result PROJECT_UUID EXPERIMENT_UUID', 'blinkhost seo research-cancel PROJECT_UUID EXPERIMENT_UUID', 'blinkhost seo remediate PROJECT_UUID AUDIT_UUID --model MODEL --max-units N --findings KEY,KEY [--request-id REQUEST_UUID]'],
33
+ details: ['Use --json for machine output. A failed completed gate exits the validation code; queued jobs must be polled before checking their gate.', 'Audit, verification and remediation accept --request-id REQUEST_UUID. Retry with the same UUID and unchanged inputs after an uncertain submission. Errors include the SEO request ID, including when one was generated automatically; use a fresh UUID for a new task.', 'Audit accepts --changed to prioritize changed routes and template representatives, --paths /,/docs for an explicit public selection, and --baseline AUDIT_UUID for compatible comparisons. Removed routes remain unverified.', 'Local HTML checks cover title, description and canonical only; hosted checks record explicit network and rendering coverage.', 'Remediation uses ordinary Idam model entitlement and wallet controls. Imports and documentation tasks use bounded JSON contracts.', 'Search and model experiments require a stable client_request_id in their JSON request. Reuse the same file on retry; poll the returned ID. Experiments use the selected permitted model and ordinary wallet. Public documentation retrieval and controlled experiments do not measure answers in external AI products.', 'Public research requires public_query_consent: true, an explicit query, max_reads from 1 to 5, a permitted model and maximum_units. Model work uses the ordinary wallet; Azure search and its grounding model use verified prepaid USD research funds. Check research-status for the per-read hold and available balance. Cancellation stops future reads; sent reads still need their cost receipts.'],
34
+ examples: ['blinkhost seo local ./out --gate --json'], related: ['ai', 'ci'],
35
+ },
30
36
  ai: {
31
37
  name: 'ai', title: 'Idam assistant — limited preview', summary: 'Inspect tasks and explicitly review source proposals through the BlinkHost control plane.',
32
38
  usage: ['blinkhost ai start --request @request.json', 'blinkhost ai list --project PROJECT_UUID',
@@ -230,7 +236,7 @@ const COMMANDS = [
230
236
  'quickstart', 'docs', 'create', 'init', 'validate', 'manifest', 'doctor', 'test', 'auth', 'ai', 'profile', 'projects',
231
237
  'repositories', 'connections', 'previews', 'builds', 'deployments', 'modules', 'functions', 'databases', 'bindings', 'assets',
232
238
  'secrets', 'organizations', 'templates', 'approvals', 'handoffs', 'policies', 'workloads', 'dev', 'logs', 'metrics',
233
- 'analytics', 'support', 'completion', 'update', 'ci', 'plugins', 'api',
239
+ 'analytics', 'seo', 'support', 'completion', 'update', 'ci', 'plugins', 'api',
234
240
  ];
235
241
  export const TOP_LEVEL_COMMANDS = [...COMMANDS];
236
242
  export function documentationIndex() {
package/dist/seo.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ export declare const SEO_VERSION = "blinkhost-seo/v1";
2
+ export declare const SEO_RULESET = "2026-10-05.1";
3
+ export interface LocalFinding {
4
+ key: string;
5
+ rule: string;
6
+ rule_version: string;
7
+ path: string;
8
+ severity: string;
9
+ confidence: string;
10
+ evidence: Record<string, unknown>;
11
+ remedy: string;
12
+ source: string;
13
+ state: string;
14
+ content_is_untrusted: boolean;
15
+ }
16
+ export declare function checkLocalHtml(html: string, path: string, source: string): LocalFinding[];
17
+ export declare function localAudit(directory: string, gate?: boolean): Promise<Record<string, unknown>>;
18
+ export declare function runSeo(args: string[], profile?: string): Promise<Record<string, unknown>>;
package/dist/seo.js ADDED
@@ -0,0 +1,312 @@
1
+ import { readFile, readdir, lstat, open } from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
3
+ import { resolve, join, relative } from 'node:path';
4
+ import { createHash, randomUUID } from 'node:crypto';
5
+ import { ApiClient } from './api.js';
6
+ import { CliError, EXIT } from './errors.js';
7
+ export const SEO_VERSION = 'blinkhost-seo/v1';
8
+ export const SEO_RULESET = '2026-10-05.1';
9
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
10
+ function requestIdentity(value, repeated) {
11
+ if (!value || !uuid.test(value) || repeated)
12
+ throw new CliError('Provide --request-id UUID exactly once.', EXIT.usage, 'seo_request_id_invalid');
13
+ return value;
14
+ }
15
+ async function boundedFile(file, maximum = 100000) {
16
+ const handle = await open(resolve(file), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
17
+ try {
18
+ const stat = await handle.stat();
19
+ if (!stat.isFile() || stat.size > maximum)
20
+ throw new CliError(`Use an ordinary file up to ${maximum} bytes.`, EXIT.validation, 'seo_document_limit');
21
+ const buffer = Buffer.alloc(maximum + 1);
22
+ let size = 0;
23
+ while (size < buffer.length) {
24
+ const { bytesRead } = await handle.read(buffer, size, buffer.length - size, null);
25
+ if (!bytesRead)
26
+ break;
27
+ size += bytesRead;
28
+ }
29
+ if (size > maximum)
30
+ throw new CliError('File exceeds the size limit.', EXIT.validation, 'seo_document_limit');
31
+ return buffer.subarray(0, size);
32
+ }
33
+ finally {
34
+ await handle.close();
35
+ }
36
+ }
37
+ async function boundedJson(file, maximum = 100000) {
38
+ try {
39
+ const value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(await boundedFile(file, maximum)));
40
+ if (!value || typeof value !== 'object' || Array.isArray(value))
41
+ throw new Error('not an object');
42
+ return value;
43
+ }
44
+ catch (error) {
45
+ if (error instanceof CliError)
46
+ throw error;
47
+ throw new CliError('Provide a valid UTF-8 JSON object.', EXIT.validation, 'seo_json_invalid');
48
+ }
49
+ }
50
+ function validPublicPath(value) {
51
+ if (typeof value !== 'string' || value.length > 512 || !value.startsWith('/') || value.startsWith('//') || /[?#%\\\x00-\x20\x7f]/.test(value))
52
+ return false;
53
+ return !value.split('/').some(part => part === '.' || part === '..');
54
+ }
55
+ function validateSubmission(body, kind) {
56
+ if (kind === 'research') {
57
+ const fields = ['client_request_id', 'model', 'maximum_units', 'query', 'max_reads', 'public_query_consent'];
58
+ const invalid = Object.keys(body).length !== fields.length || Object.keys(body).some(key => !fields.includes(key))
59
+ || typeof body.client_request_id !== 'string' || !uuid.test(body.client_request_id)
60
+ || typeof body.model !== 'string' || !body.model || body.model.length > 40
61
+ || !Number.isInteger(body.maximum_units) || Number(body.maximum_units) < 1 || Number(body.maximum_units) > 2000
62
+ || typeof body.query !== 'string' || !body.query || body.query !== body.query.trim()
63
+ || Buffer.byteLength(body.query) > 512 || /\p{C}/u.test(body.query)
64
+ || !Number.isInteger(body.max_reads) || Number(body.max_reads) < 1 || Number(body.max_reads) > 5
65
+ || body.public_query_consent !== true;
66
+ if (invalid)
67
+ throw new CliError('Use an explicit public query, consent and spending limits. Keep client_request_id unchanged when retrying.', EXIT.validation, 'seo_submission_invalid');
68
+ return;
69
+ }
70
+ const fields = kind === 'search' ? ['client_request_id', 'query', 'count', 'locale'] : ['client_request_id', 'model', 'maximum_units', 'question', 'paths', 'required_facts'];
71
+ const text = body[kind === 'search' ? 'query' : 'question'];
72
+ let invalid = Object.keys(body).some(key => !fields.includes(key)) || typeof body.client_request_id !== 'string' || !uuid.test(body.client_request_id)
73
+ || typeof text !== 'string' || !text.trim() || Buffer.byteLength(text) > 1000 || /[\x00-\x1f\x7f]/.test(text);
74
+ if (kind === 'search') {
75
+ invalid ||= body.count !== undefined && (!Number.isInteger(body.count) || Number(body.count) < 1 || Number(body.count) > 10);
76
+ invalid ||= body.locale !== undefined && body.locale !== null && (typeof body.locale !== 'string' || body.locale.length > 63 || !/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(body.locale));
77
+ }
78
+ else {
79
+ invalid ||= typeof body.model !== 'string' || !body.model || body.model.length > 40
80
+ || !Number.isInteger(body.maximum_units) || Number(body.maximum_units) < 1 || Number(body.maximum_units) > 2000
81
+ || !Array.isArray(body.paths) || body.paths.length < 1 || body.paths.length > 5 || body.paths.some(path => !validPublicPath(path)) || new Set(body.paths).size !== body.paths.length
82
+ || !Array.isArray(body.required_facts) || body.required_facts.length > 20 || body.required_facts.some(fact => typeof fact !== 'string' || !fact.trim() || Buffer.byteLength(fact) > 300 || /[\x00-\x1f\x7f]/.test(fact));
83
+ }
84
+ if (invalid)
85
+ throw new CliError(`Invalid ${kind} request. Keep client_request_id unchanged when retrying.`, EXIT.validation, 'seo_submission_invalid');
86
+ }
87
+ function attributes(tag) {
88
+ return Object.fromEntries([...tag.matchAll(/([^\s=<>]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g)]
89
+ .map(match => [(match[1] ?? '').toLowerCase(), match[2] ?? match[3] ?? match[4] ?? '']));
90
+ }
91
+ function privateDocument(html) {
92
+ return [...html.matchAll(/<meta\b[^>]*>/gi)].some(match => {
93
+ const attrs = attributes(match[0]);
94
+ return (attrs.name?.toLowerCase() === 'robots' && /\bnoindex\b/i.test(attrs.content ?? '')) ||
95
+ (attrs.name?.toLowerCase() === 'blinkhost:visibility' && attrs.content?.toLowerCase() === 'private');
96
+ });
97
+ }
98
+ export function checkLocalHtml(html, path, source) {
99
+ const findings = [];
100
+ const add = (rule, severity, evidence, remedy) => {
101
+ const key = createHash('sha256').update(JSON.stringify([rule, path])).digest('hex');
102
+ findings.push({ key, rule, rule_version: SEO_RULESET, path, severity, confidence: 'high', evidence, remedy, source, state: 'open', content_is_untrusted: true });
103
+ };
104
+ // Local parser intentionally bounds coverage. Hosted audits use an HTML parser
105
+ // and network/render evidence. Private/noindex intent isn't guessed locally.
106
+ const titles = [...html.matchAll(/<title\b[^>]*>([\s\S]*?)<\/title\s*>/gi)];
107
+ if (titles.length !== 1 || !titles[0]?.[1]?.trim())
108
+ add('metadata.title', 'warning', { titles: titles.length }, 'Give this page one descriptive title.');
109
+ const metas = [...html.matchAll(/<meta\b[^>]*>/gi)].map(match => match[0]);
110
+ if (!metas.some(tag => /\bname\s*=\s*["']description["']/i.test(tag) && /\bcontent\s*=\s*["'][^"']+/i.test(tag)))
111
+ add('metadata.description', 'warning', { present: false }, 'Add a concise description of this page.');
112
+ const canonicals = [...html.matchAll(/<link\b[^>]*>/gi)].filter(match => /\brel\s*=\s*["']canonical["']/i.test(match[0]));
113
+ if (canonicals.length !== 1)
114
+ add('metadata.canonical', 'error', { canonicals: canonicals.length }, 'Use one absolute canonical URL for the intended public page.');
115
+ else {
116
+ const href = /\bhref\s*=\s*["']([^"']*)["']/i.exec(canonicals[0]?.[0] ?? '')?.[1] ?? '';
117
+ try {
118
+ const url = new URL(href);
119
+ if (!['https:', 'http:'].includes(url.protocol) || url.username || url.hash)
120
+ throw new Error();
121
+ }
122
+ catch {
123
+ add('metadata.canonical', 'error', { canonical: href }, 'Use one absolute canonical URL for the intended public page.');
124
+ }
125
+ }
126
+ return findings;
127
+ }
128
+ export async function localAudit(directory, gate = false) {
129
+ const root = resolve(directory);
130
+ const files = [];
131
+ let visited = 0;
132
+ async function visit(dir) {
133
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
134
+ if (++visited > 10000)
135
+ throw new CliError('Local scan exceeds 10,000 entries.', EXIT.validation, 'seo_scan_limit');
136
+ if (entry.isSymbolicLink() || entry.name.startsWith('.') || entry.name.startsWith('_') || ['node_modules', 'vendor'].includes(entry.name))
137
+ continue;
138
+ const path = join(dir, entry.name);
139
+ if (entry.isDirectory())
140
+ await visit(path);
141
+ else if (entry.isFile() && entry.name.endsWith('.html') && !['404.html', '500.html'].includes(entry.name))
142
+ files.push(path);
143
+ }
144
+ }
145
+ if ((await lstat(root)).isSymbolicLink())
146
+ throw new CliError('Scan an ordinary directory.', EXIT.validation, 'seo_symlink');
147
+ await visit(root);
148
+ const findings = [];
149
+ let checked = 0;
150
+ for (const file of files) {
151
+ if ((await lstat(file)).size > 1048576)
152
+ throw new CliError('HTML exceeds the local 1 MiB limit.', EXIT.validation, 'seo_document_limit');
153
+ const source = relative(root, file).replaceAll('\\', '/');
154
+ const path = '/' + (source.endsWith('index.html') ? source.slice(0, -10) : source.slice(0, -5));
155
+ const html = await readFile(file, 'utf8');
156
+ if (privateDocument(html))
157
+ continue;
158
+ checked++;
159
+ findings.push(...checkLocalHtml(html, path, source));
160
+ }
161
+ const blocking = findings.filter(item => item.severity === 'error').map(item => item.key);
162
+ return { version: SEO_VERSION, ruleset: SEO_RULESET, findings,
163
+ coverage: { mode: 'local-html', files: checked, excluded: files.length - checked, rules: ['metadata.title', 'metadata.description', 'metadata.canonical'], unsupported: ['network status', 'rendering', 'dynamic route enumeration', 'intent validation'] },
164
+ gate: { enabled: gate, passed: !gate || (checked > 0 && !blocking.length), incomplete: checked === 0, blocking: gate ? blocking : [] } };
165
+ }
166
+ export async function runSeo(args, profile) {
167
+ const action = args.shift();
168
+ if (action === 'local') {
169
+ const gate = args.includes('--gate');
170
+ const remaining = args.filter(arg => arg !== '--gate');
171
+ if (remaining.length > 1)
172
+ throw new CliError('Use seo local DIRECTORY [--gate].', EXIT.usage, 'seo_usage');
173
+ return localAudit(remaining[0] ?? '.', gate);
174
+ }
175
+ const projectId = args.shift();
176
+ if (!projectId || !uuid.test(projectId))
177
+ throw new CliError('Provide the project UUID.', EXIT.usage, 'seo_project_required');
178
+ const base = `/api/seo/projects/${projectId}/audits/`;
179
+ let client;
180
+ const request = async (path, options) => {
181
+ client ??= await ApiClient.create(profile);
182
+ return client.request(path, options);
183
+ };
184
+ const projectBase = `/api/seo/projects/${projectId}/`;
185
+ const post = async (path, body) => await request(path, { method: 'POST', body: JSON.stringify(body) });
186
+ const submitTask = async (path, body) => {
187
+ try {
188
+ const result = await post(path, body);
189
+ if (!result || typeof result !== 'object' || Array.isArray(result) || typeof result.id !== 'string' || !uuid.test(result.id)) {
190
+ throw new CliError('The BlinkHost API did not confirm the SEO task. Its response was invalid.', EXIT.remote, 'seo_response_invalid');
191
+ }
192
+ return result;
193
+ }
194
+ catch (error) {
195
+ if (error instanceof CliError)
196
+ throw new CliError(error.message, error.exitCode, error.code, [
197
+ ...error.details, `SEO request ID: ${body.client_request_id}`,
198
+ `If submission is uncertain, retry the unchanged command with --request-id ${body.client_request_id}.`,
199
+ ]);
200
+ throw error;
201
+ }
202
+ };
203
+ if (['content-status', 'content-index', 'content-delete', 'samples', 'research-status'].includes(action ?? '') && !args.length) {
204
+ const path = `${projectBase}${action === 'samples' ? 'samples' : action === 'research-status' ? 'research' : 'content/index'}/`;
205
+ if (action === 'content-index')
206
+ return post(path, {});
207
+ return await request(path, action === 'content-delete' ? { method: 'DELETE' } : undefined);
208
+ }
209
+ if (['content-search', 'sample', 'research'].includes(action ?? '') && args.length === 1) {
210
+ const body = await boundedJson(args[0]);
211
+ validateSubmission(body, action === 'sample' ? 'sample' : action === 'research' ? 'research' : 'search');
212
+ return post(`${projectBase}${action === 'sample' ? 'samples' : action === 'research' ? 'research' : 'content/search'}/`, body);
213
+ }
214
+ if (['content-result', 'sample-result', 'sample-delete', 'research-result', 'research-cancel'].includes(action ?? '') && args.length === 1 && uuid.test(args[0])) {
215
+ const path = `${projectBase}${action === 'content-result' ? 'content/search' : action?.startsWith('research-') ? 'research' : 'samples'}/${args[0]}/`;
216
+ return await request(path, action === 'sample-delete' || action === 'research-cancel' ? { method: 'DELETE' } : undefined);
217
+ }
218
+ if ((action === 'diagnostics' || action === 'field') && !args.length)
219
+ return await request(`${projectBase}${action}/`);
220
+ if (action === 'import-native' && args.length === 3) {
221
+ const [format, exportFile, metadataFile] = args;
222
+ if (!['google-search-console-csv', 'google-search-console-zip', 'bing-webmaster-csv'].includes(format))
223
+ throw new CliError('Choose a supported native export format.', EXIT.usage, 'seo_import_format');
224
+ const provenance = await boundedJson(metadataFile, 10000);
225
+ const data = await boundedFile(exportFile, 1_450_000);
226
+ let content;
227
+ try {
228
+ content = format.endsWith('-zip') ? data.toString('base64') : new TextDecoder('utf-8', { fatal: true }).decode(data);
229
+ }
230
+ catch {
231
+ throw new CliError('CSV must be UTF-8.', EXIT.validation, 'seo_import_encoding');
232
+ }
233
+ const body = { version: SEO_VERSION, native_format: format, provenance, content };
234
+ if (Buffer.byteLength(JSON.stringify(body)) > 2_000_000)
235
+ throw new CliError('Report exceeds 2 MB.', EXIT.validation, 'seo_document_limit');
236
+ return post(`${projectBase}imports/`, body);
237
+ }
238
+ if ((action === 'import' || action === 'docs-evaluate') && args.length === 1) {
239
+ const body = await boundedJson(args[0], 2_000_000);
240
+ return post(`${projectBase}${action === 'import' ? 'imports' : 'docs/evaluate'}/`, body);
241
+ }
242
+ if (action === 'audit' || action === 'verify') {
243
+ const auditId = action === 'verify' ? args.shift() : undefined;
244
+ if (action === 'verify' && (!auditId || !uuid.test(auditId)))
245
+ throw new CliError('Provide the audit UUID.', EXIT.usage, 'seo_audit_required');
246
+ const options = { client_request_id: randomUUID(), page_limit: 100 };
247
+ let explicitRequestId = false;
248
+ while (args.length) {
249
+ const flag = args.shift();
250
+ if (flag === '--gate')
251
+ options.gate = true;
252
+ else if (flag === '--request-id') {
253
+ options.client_request_id = requestIdentity(args.shift(), explicitRequestId);
254
+ explicitRequestId = true;
255
+ }
256
+ else if (flag === '--changed')
257
+ options.scope = 'changed';
258
+ else if (flag === '--paths') {
259
+ const value = args.shift()?.split(',');
260
+ if (!value?.length || value.some(path => !path.startsWith('/') || path.startsWith('//') || /[?#\\\x00-\x20]/.test(path)))
261
+ throw new CliError('Provide comma-separated public route paths.', EXIT.usage, 'seo_paths');
262
+ options.paths = value;
263
+ }
264
+ else if (flag === '--baseline') {
265
+ const value = args.shift();
266
+ if (!value || !uuid.test(value))
267
+ throw new CliError('Provide the baseline audit UUID.', EXIT.usage, 'seo_baseline');
268
+ options.baseline_id = value;
269
+ }
270
+ else if (flag === '--pages' || flag === '--browser-pages') {
271
+ const value = Number(args.shift());
272
+ if (!Number.isInteger(value) || value < (flag === '--pages' ? 1 : 0) || value > (flag === '--pages' ? 1000 : 10))
273
+ throw new CliError('Invalid scan bounds.', EXIT.usage, 'seo_bounds');
274
+ options[flag === '--pages' ? 'page_limit' : 'browser_limit'] = value;
275
+ }
276
+ else
277
+ throw new CliError('Unknown SEO option.', EXIT.usage, 'seo_usage');
278
+ }
279
+ if (Array.isArray(options.paths) && options.paths.length > Number(options.page_limit))
280
+ throw new CliError('Paths exceed the page limit.', EXIT.usage, 'seo_paths');
281
+ return submitTask(action === 'audit' ? base : `${base}${auditId}/verify/`, options);
282
+ }
283
+ if (action === 'findings' && args.length === 1 && uuid.test(args[0] ?? ""))
284
+ return await request(`${base}${args[0]}/`);
285
+ if (action === 'cancel' && args.length === 1 && uuid.test(args[0] ?? ""))
286
+ return post(`${base}${args[0]}/cancel/`, {});
287
+ if (action === 'remediate') {
288
+ const auditId = args.shift();
289
+ const body = { client_request_id: randomUUID() };
290
+ let explicitRequestId = false;
291
+ while (args.length) {
292
+ const flag = args.shift(), value = args.shift();
293
+ if (flag === '--model')
294
+ body.model = value;
295
+ else if (flag === '--request-id') {
296
+ body.client_request_id = requestIdentity(value, explicitRequestId);
297
+ explicitRequestId = true;
298
+ }
299
+ else if (flag === '--max-units')
300
+ body.maximum_units = Number(value);
301
+ else if (flag === '--findings')
302
+ body.finding_keys = value?.split(',');
303
+ else
304
+ throw new CliError('Unknown remediation option.', EXIT.usage, 'seo_usage');
305
+ }
306
+ if ((!auditId || !uuid.test(auditId)) || typeof body.model !== 'string' || !body.model || !Number.isInteger(body.maximum_units) || Number(body.maximum_units) < 1 || Number(body.maximum_units) > 2000 || !Array.isArray(body.finding_keys) || !body.finding_keys.length || body.finding_keys.length > 10 || body.finding_keys.some(key => !/^[0-9a-f]{64}$/.test(String(key))))
307
+ throw new CliError('Use seo remediate PROJECT AUDIT --model MODEL --max-units N --findings KEY,KEY.', EXIT.usage, 'seo_model_budget_required');
308
+ return submitTask(`${base}${auditId}/remediate/`, body);
309
+ }
310
+ throw new CliError('See blinkhost help seo for audit, documentation search and model experiment commands.', EXIT.usage, 'seo_usage');
311
+ }
312
+ //# sourceMappingURL=seo.js.map
package/dist/version.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "2.5.2";
1
+ export declare const VERSION = "2.6.0";
2
2
  export declare const DOCUMENTATION_URL = "https://app.blinkhost.me/docs/source-control/cli";
3
3
  export declare const RELEASES_URL = "https://github.com/blinkhost-ltd/blinkhost-cli/releases";
4
4
  export declare function supportedNodeVersion(version?: string): boolean;
package/dist/version.js CHANGED
@@ -1,4 +1,4 @@
1
- export const VERSION = '2.5.2';
1
+ export const VERSION = '2.6.0';
2
2
  export const DOCUMENTATION_URL = 'https://app.blinkhost.me/docs/source-control/cli';
3
3
  export const RELEASES_URL = 'https://github.com/blinkhost-ltd/blinkhost-cli/releases';
4
4
  export function supportedNodeVersion(version = process.versions.node) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blinkhost/cli",
3
- "version": "2.5.2",
3
+ "version": "2.6.0",
4
4
  "description": "Secure local and remote developer workflows for BlinkHost",
5
5
  "keywords": ["blinkhost", "deployment", "hosting", "cloud", "cli", "developer-tools"],
6
6
  "homepage": "https://app.blinkhost.me/docs/source-control/cli",