mirror of
https://github.com/kemalai/FreeCrawl-SEO-Tool.git
synced 2026-12-02 08:29:14 +01:00
fix: external link checks, agent secrets, pause and image filters
This commit is contained in:
1 parent
27110745eb
commit
833c9912c8
25 files changed
+747
-257
No files matched your search
@@ -28,7 +28,7 @@ A high-performance website crawler built for serious SEO audits. Targets <kbd>1M
|
||||
<br />
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **v1.0.0 is the full release.** Everything planned for 1.0 ships in this build, and it is ready for daily audit work. Development does not stop here: further updates will follow based on user feedback and bug reports, so if something gets in your way, [open an issue](https://github.com/kemalai/FreeCrawl-SEO-Tool/issues).
|
||||
> **The core of FreeCrawl was completed in v1.0.** For a smooth, trouble-free experience, always use the [latest release](https://github.com/kemalai/FreeCrawl-SEO-Tool/releases/latest). Development continues based on user feedback and bug reports, so if something gets in your way, [open an issue](https://github.com/kemalai/FreeCrawl-SEO-Tool/issues).
|
||||
|
||||
<br />
|
||||
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ upgrading is the recommended remediation path.
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | ------------------ |
|
||||
| Latest stable (currently `1.1.4`) | Yes |
|
||||
| Latest stable (currently `1.1.5`) | Yes |
|
||||
| Older releases | No |
|
||||
|
||||
Release artifacts are published at:
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* Type-checks a CrawlConfig an MCP agent sends to `set_crawl_config`.
|
||||
*
|
||||
* An MCP client only sends real JSON types for properties the tool schema
|
||||
* declares; anything else may arrive as a string — `"false"`, `"20"`,
|
||||
* `"[{...}]"`. Saved as-is, `"false"` is truthy (a setting the agent
|
||||
* switched off reads as on) and a stringified list breaks every reader.
|
||||
* So each field is held to the type of its default: a string that encodes
|
||||
* the right type is decoded, anything else is refused with the field
|
||||
* named. Fields without a default (optional ones) pass through.
|
||||
*
|
||||
* Pure (no Electron) so it can be tested directly.
|
||||
*/
|
||||
import { DEFAULT_CRAWL_CONFIG, type CrawlConfig } from '@freecrawl/shared-types';
|
||||
|
||||
type Kind = 'string' | 'number' | 'boolean' | 'array' | 'object' | 'null' | 'other';
|
||||
|
||||
function kindOf(value: unknown): Kind {
|
||||
if (value === null) return 'null';
|
||||
if (Array.isArray(value)) return 'array';
|
||||
const t = typeof value;
|
||||
return t === 'string' || t === 'number' || t === 'boolean' || t === 'object' ? t : 'other';
|
||||
}
|
||||
|
||||
/** `raw` decoded as `kind`, or `undefined` when it does not encode one. */
|
||||
function decode(raw: string, kind: Kind): unknown {
|
||||
const text = raw.trim();
|
||||
if (kind === 'boolean') return text === 'true' ? true : text === 'false' ? false : undefined;
|
||||
if (kind === 'number') {
|
||||
const n = text === '' ? NaN : Number(text);
|
||||
return Number.isFinite(n) ? n : undefined;
|
||||
}
|
||||
if (kind === 'array' || kind === 'object') {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(text);
|
||||
return kindOf(parsed) === kind ? parsed : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const DEFAULTS = DEFAULT_CRAWL_CONFIG as unknown as Record<string, unknown>;
|
||||
|
||||
export function coerceAgentConfig(input: unknown): Partial<CrawlConfig> {
|
||||
if (kindOf(input) !== 'object') throw new Error('A CrawlConfig object is required.');
|
||||
const out: Record<string, unknown> = {};
|
||||
const problems: string[] = [];
|
||||
for (const [key, value] of Object.entries(input as Record<string, unknown>)) {
|
||||
const expected = Object.hasOwn(DEFAULTS, key) ? kindOf(DEFAULTS[key]) : null;
|
||||
const got = kindOf(value);
|
||||
if (expected === null || got === expected) {
|
||||
out[key] = value;
|
||||
continue;
|
||||
}
|
||||
const decoded = got === 'string' ? decode(value as string, expected) : undefined;
|
||||
if (decoded !== undefined) {
|
||||
out[key] = decoded;
|
||||
continue;
|
||||
}
|
||||
problems.push(`\`${key}\` must be ${expected === 'array' || expected === 'object' ? 'an' : 'a'} ${expected} (got ${got})`);
|
||||
}
|
||||
if (problems.length > 0) {
|
||||
throw new Error(`Invalid CrawlConfig — nothing was saved: ${problems.join('; ')}.`);
|
||||
}
|
||||
return out as Partial<CrawlConfig>;
|
||||
}
|
||||
@@ -20,7 +20,8 @@
|
||||
* the loop, so a tab switch can't strand a half-finished tool round.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type { ProjectDb } from '@freecrawl/db';
|
||||
import { resolveUrlCategory, type ProjectDb } from '@freecrawl/db';
|
||||
import { rankIssues } from '@freecrawl/shared-types';
|
||||
import type {
|
||||
AiProvider,
|
||||
AssistantEvent,
|
||||
@@ -135,7 +136,7 @@ const BUILTIN_TOOLS: BuiltinTool[] = [
|
||||
{
|
||||
name: 'top_issues',
|
||||
description:
|
||||
'Ranked list of non-empty SEO issue categories in the open crawl, biggest first. Use it to answer "what is wrong with this site?" before drilling into a category.',
|
||||
'Ranked list of non-empty SEO issue checks in the open crawl, biggest first. Use it to answer "what is wrong with this site?" before drilling into a category. Pass `category` to query_urls unchanged. `unit` says what `count` counts: "urls" (pages), "images" (image usages — query_urls lists the pages carrying them) or "links" (broken link rows, not listed by query_urls).',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
@@ -144,14 +145,8 @@ const BUILTIN_TOOLS: BuiltinTool[] = [
|
||||
},
|
||||
run: (args, db) => {
|
||||
const limit = clamp(args['limit'], 1, 100, 20);
|
||||
const counts = db.getOverviewCounts() as unknown as Record<string, unknown>;
|
||||
const issues = (counts['issues'] as Record<string, number>) ?? {};
|
||||
const ranked = Object.entries(issues)
|
||||
.filter(([, n]) => n > 0)
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.slice(0, limit)
|
||||
.map(([category, count]) => ({ category: `issues:${category}`, count }));
|
||||
return { issues: ranked };
|
||||
const ranked = rankIssues(db.getOverviewCounts().issues, db.getDisabledIssues());
|
||||
return { issues: ranked.slice(0, limit) };
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -180,9 +175,9 @@ const BUILTIN_TOOLS: BuiltinTool[] = [
|
||||
const limit = clamp(args['limit'], 1, 200, 25);
|
||||
const offset = clamp(args['offset'], 0, 1_000_000, 0);
|
||||
const { rows, total } = db.queryUrls({
|
||||
category: (typeof args['category'] === 'string'
|
||||
? args['category']
|
||||
: 'all') as Parameters<ProjectDb['queryUrls']>[0]['category'],
|
||||
// Throws on an unknown name, which the loop feeds back to the model
|
||||
// as a tool error, rather than answering with the whole crawl.
|
||||
category: resolveUrlCategory(args['category']),
|
||||
search: typeof args['search'] === 'string' ? args['search'] : undefined,
|
||||
limit,
|
||||
offset,
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
/**
|
||||
* Credential fields of a `CrawlConfig`, split out of the config so they can
|
||||
* be encrypted at rest (preferences.json, the project's `lastCrawlConfig`),
|
||||
* blanked in the shareable settings export, and kept out of every reply to
|
||||
* an MCP agent, whose context goes to its model provider.
|
||||
*
|
||||
* Pure (no Electron) so the rules can be tested directly. The list here is
|
||||
* the whole boundary: a field that holds a credential and is missing from
|
||||
* it is stored in plaintext and handed to agents. Proxy profile URLs were
|
||||
* (2026-11-07: an agent's `start_crawl` reply carried three proxy
|
||||
* passwords), as were form-login field values and custom header values.
|
||||
*/
|
||||
import type { CrawlConfig, FormLoginStep } from '@freecrawl/shared-types';
|
||||
|
||||
type FormLoginField = FormLoginStep['fields'][number];
|
||||
type ProxyProfile = CrawlConfig['proxyProfiles'][number];
|
||||
|
||||
/** A form-login value that is only a `{{var}}` reference to a captured
|
||||
* value (a CSRF token) — a template, not a credential. */
|
||||
const TEMPLATE_ONLY = /^\s*\{\{\s*[\w.-]+\s*\}\}\s*$/;
|
||||
|
||||
/**
|
||||
* The entries of a config list, or none when the field is not a list of
|
||||
* objects. These helpers also run on configs read back from disk and
|
||||
* from settings imports; a hand-edited or older file with an odd shape
|
||||
* must not crash startup — its malformed part simply holds no secrets.
|
||||
*/
|
||||
function entries<T extends object>(list: unknown): T[] {
|
||||
return Array.isArray(list)
|
||||
? (list.filter((e) => e !== null && typeof e === 'object') as T[])
|
||||
: [];
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Secret keys for a list of named entries. Names identify the entry (the
|
||||
* active proxy profile is chosen by name; a header or form field is its
|
||||
* name), so the key survives reordering; a repeated name gets its
|
||||
* occurrence number so two entries can't share one key.
|
||||
*/
|
||||
function namedKeys(prefix: string, names: readonly string[]): string[] {
|
||||
const seen = new Map<string, number>();
|
||||
return names.map((name) => {
|
||||
const n = seen.get(name) ?? 0;
|
||||
seen.set(name, n + 1);
|
||||
return `${prefix}${n}:${name}`;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The secret values of a config as a flat record, and a deep copy of the
|
||||
* config with those values blanked.
|
||||
*/
|
||||
export function splitConfigSecrets(config: CrawlConfig): {
|
||||
clean: CrawlConfig;
|
||||
secrets: Record<string, string>;
|
||||
} {
|
||||
const clean: CrawlConfig = JSON.parse(JSON.stringify(config)) as CrawlConfig;
|
||||
const secrets: Record<string, string> = {};
|
||||
// A credential-bearing field in the wrong shape (a stringified list, a
|
||||
// hand-edited file) can't be searched for its secrets, so it is dropped
|
||||
// from the clean copy instead of passed through whole — fail closed.
|
||||
const loose = clean as unknown as Record<string, unknown>;
|
||||
for (const field of ['auth', 'formLogin'] as const) {
|
||||
if (loose[field] !== undefined && !isRecord(loose[field])) delete loose[field];
|
||||
}
|
||||
if (loose['customHeaders'] !== undefined && !isRecord(loose['customHeaders'])) clean.customHeaders = {};
|
||||
if (loose['proxyProfiles'] !== undefined) clean.proxyProfiles = entries<ProxyProfile>(loose['proxyProfiles']);
|
||||
if (clean.formLogin && clean.formLogin.steps !== undefined) {
|
||||
clean.formLogin.steps = entries<FormLoginStep>(clean.formLogin.steps);
|
||||
for (const step of clean.formLogin.steps) {
|
||||
if (step.fields !== undefined) step.fields = entries<FormLoginField>(step.fields);
|
||||
}
|
||||
}
|
||||
if (clean.auth) {
|
||||
if (clean.auth.password) {
|
||||
secrets['auth.password'] = clean.auth.password;
|
||||
clean.auth.password = '';
|
||||
}
|
||||
if (clean.auth.token) {
|
||||
secrets['auth.token'] = clean.auth.token;
|
||||
clean.auth.token = '';
|
||||
}
|
||||
}
|
||||
const pv = clean.formLogin?.browser?.passwordValue;
|
||||
if (pv) {
|
||||
secrets['formLogin.browser.passwordValue'] = pv;
|
||||
clean.formLogin!.browser!.passwordValue = '';
|
||||
}
|
||||
// The values a login step POSTs are the username and password. Only a
|
||||
// value that merely references a captured variable stays readable.
|
||||
entries<FormLoginStep>(clean.formLogin?.steps).forEach((step, i) => {
|
||||
const fields = entries<FormLoginField>(step.fields);
|
||||
const keys = namedKeys(`formLogin.steps.${i}.fields.`, fields.map((f) => f.name));
|
||||
fields.forEach((field, j) => {
|
||||
if (typeof field.value !== 'string' || !field.value || TEMPLATE_ONLY.test(field.value)) return;
|
||||
secrets[keys[j]!] = field.value;
|
||||
field.value = '';
|
||||
});
|
||||
});
|
||||
if (clean.proxyUrl) {
|
||||
secrets['proxyUrl'] = clean.proxyUrl;
|
||||
clean.proxyUrl = '';
|
||||
}
|
||||
// Saved proxy profiles carry the same `user:pass@` URLs as the proxy
|
||||
// field; the active one is still known by its name.
|
||||
const profiles = entries<ProxyProfile>(clean.proxyProfiles);
|
||||
const profileKeys = namedKeys('proxyProfiles.', profiles.map((p) => p.name));
|
||||
profiles.forEach((profile, i) => {
|
||||
if (typeof profile.url !== 'string' || !profile.url) return;
|
||||
secrets[profileKeys[i]!] = profile.url;
|
||||
profile.url = '';
|
||||
});
|
||||
// Custom headers are how sites take a bypass token or an Authorization
|
||||
// header — the crawler already refuses to send them to any other host.
|
||||
// Names stay visible; values are credentials.
|
||||
if (isRecord(clean.customHeaders)) {
|
||||
for (const [name, value] of Object.entries(clean.customHeaders)) {
|
||||
if (typeof value !== 'string' || !value) continue;
|
||||
secrets[`customHeaders.${name}`] = value;
|
||||
clean.customHeaders[name] = '';
|
||||
}
|
||||
}
|
||||
// A Slack / Discord / Teams webhook URL is bearer-equivalent: anyone
|
||||
// holding it can post into the channel. Same treatment as a password —
|
||||
// encrypted at rest, blanked in the settings export and for MCP agents.
|
||||
if (clean.webhookUrl) {
|
||||
secrets['webhookUrl'] = clean.webhookUrl;
|
||||
clean.webhookUrl = '';
|
||||
}
|
||||
return { clean, secrets };
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-apply previously split secrets onto a (cleaned) config, in place. A
|
||||
* list entry is filled only where the config still has it, so a profile,
|
||||
* header or form field removed since the split stays removed.
|
||||
*/
|
||||
export function applyConfigSecrets(
|
||||
config: CrawlConfig,
|
||||
secrets: Record<string, string>,
|
||||
): CrawlConfig {
|
||||
if (secrets['auth.password'] !== undefined && config.auth) {
|
||||
config.auth.password = secrets['auth.password'];
|
||||
}
|
||||
if (secrets['auth.token'] !== undefined && config.auth) {
|
||||
config.auth.token = secrets['auth.token'];
|
||||
}
|
||||
if (
|
||||
secrets['formLogin.browser.passwordValue'] !== undefined &&
|
||||
config.formLogin?.browser
|
||||
) {
|
||||
config.formLogin.browser.passwordValue = secrets['formLogin.browser.passwordValue'];
|
||||
}
|
||||
entries<FormLoginStep>(config.formLogin?.steps).forEach((step, i) => {
|
||||
const fields = entries<FormLoginField>(step.fields);
|
||||
const keys = namedKeys(`formLogin.steps.${i}.fields.`, fields.map((f) => f.name));
|
||||
fields.forEach((field, j) => {
|
||||
const value = secrets[keys[j]!];
|
||||
if (value !== undefined && !field.value) field.value = value;
|
||||
});
|
||||
});
|
||||
if (secrets['proxyUrl'] !== undefined) {
|
||||
config.proxyUrl = secrets['proxyUrl'];
|
||||
}
|
||||
const profiles = entries<ProxyProfile>(config.proxyProfiles);
|
||||
const profileKeys = namedKeys('proxyProfiles.', profiles.map((p) => p.name));
|
||||
profiles.forEach((profile, i) => {
|
||||
const value = secrets[profileKeys[i]!];
|
||||
if (value !== undefined && !profile.url) profile.url = value;
|
||||
});
|
||||
if (isRecord(config.customHeaders)) {
|
||||
for (const name of Object.keys(config.customHeaders)) {
|
||||
const value = secrets[`customHeaders.${name}`];
|
||||
if (value !== undefined && !config.customHeaders[name]) config.customHeaders[name] = value;
|
||||
}
|
||||
}
|
||||
if (secrets['webhookUrl'] !== undefined) {
|
||||
config.webhookUrl = secrets['webhookUrl'];
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
/** A copy of the config with every secret blanked — for the shareable
|
||||
* settings-export, which must never carry credentials. Accepts a loose
|
||||
* record because the export IPC types its payload as `Record<string,
|
||||
* unknown>`; the JSON round-trip inside `splitConfigSecrets` tolerates
|
||||
* partial/extra fields. */
|
||||
export function redactConfigSecrets(config: Record<string, unknown>): Record<string, unknown> {
|
||||
return splitConfigSecrets(config as unknown as CrawlConfig).clean as unknown as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
}
|
||||
|
||||
/** `config` with its secrets blanked, for replies to an MCP agent: an
|
||||
* agent's context goes to its model provider, so the user's passwords,
|
||||
* tokens and proxy credentials must never be in it. */
|
||||
export function configForAgent(config: CrawlConfig): CrawlConfig {
|
||||
return splitConfigSecrets(config).clean;
|
||||
}
|
||||
|
||||
/** `next` with every secret it leaves blank taken from `current`. An agent
|
||||
* only ever sees blanked secrets (`configForAgent`), so a read-modify-write
|
||||
* of the config sends them back blank — that must keep the stored values,
|
||||
* not wipe them. */
|
||||
export function keepStoredSecrets(next: CrawlConfig, current: CrawlConfig | null): CrawlConfig {
|
||||
if (!current) return next;
|
||||
const stored = splitConfigSecrets(current).secrets;
|
||||
const given = splitConfigSecrets(next).secrets;
|
||||
const keep: Record<string, string> = {};
|
||||
for (const [field, value] of Object.entries(stored)) {
|
||||
if (!given[field]) keep[field] = value;
|
||||
}
|
||||
if (Object.keys(keep).length === 0) return next;
|
||||
return applyConfigSecrets(JSON.parse(JSON.stringify(next)) as CrawlConfig, keep);
|
||||
}
|
||||
+16
-108
@@ -336,6 +336,14 @@ import {
|
||||
} from '@freecrawl/core';
|
||||
import { fetch as undiciFetch } from 'undici';
|
||||
import { apiFetch } from './api-fetch.js';
|
||||
import {
|
||||
applyConfigSecrets,
|
||||
configForAgent,
|
||||
keepStoredSecrets,
|
||||
redactConfigSecrets,
|
||||
splitConfigSecrets,
|
||||
} from './config-secrets.js';
|
||||
import { coerceAgentConfig } from './agent-config-input.js';
|
||||
import { ProjectDb, EXPENSIVE_ISSUE_DEFINITIONS } from '@freecrawl/db';
|
||||
import { buildAppMenu } from './menu.js';
|
||||
import {
|
||||
@@ -2464,87 +2472,12 @@ function getDb(): ProjectDb {
|
||||
|
||||
// ── Crawl-config secret handling ───────────────────────────────────────────
|
||||
//
|
||||
// `CrawlConfig` carries credentials — HTTP-auth password/token, the browser
|
||||
// form-login password, and a proxy URL that can embed `user:pass@`. These
|
||||
// `CrawlConfig` carries credentials — HTTP-auth password/token, form-login
|
||||
// values, proxy URLs that can embed `user:pass@`, custom header tokens. These
|
||||
// must not sit in plaintext in preferences.json or the .seoproject, nor be
|
||||
// handed to a colleague in a shared settings-export. `configSecretFields`
|
||||
// enumerates them; the helpers below either blank them (export) or split
|
||||
// them out for at-rest encryption (prefs / project meta).
|
||||
|
||||
/** Return the secret values from a config as a flat record, and a deep-ish
|
||||
* copy of the config with those values blanked. */
|
||||
function splitConfigSecrets(config: CrawlConfig): {
|
||||
clean: CrawlConfig;
|
||||
secrets: Record<string, string>;
|
||||
} {
|
||||
const clean: CrawlConfig = JSON.parse(JSON.stringify(config)) as CrawlConfig;
|
||||
const secrets: Record<string, string> = {};
|
||||
if (clean.auth) {
|
||||
if (clean.auth.password) {
|
||||
secrets['auth.password'] = clean.auth.password;
|
||||
clean.auth.password = '';
|
||||
}
|
||||
if (clean.auth.token) {
|
||||
secrets['auth.token'] = clean.auth.token;
|
||||
clean.auth.token = '';
|
||||
}
|
||||
}
|
||||
const pv = clean.formLogin?.browser?.passwordValue;
|
||||
if (pv) {
|
||||
secrets['formLogin.browser.passwordValue'] = pv;
|
||||
clean.formLogin!.browser!.passwordValue = '';
|
||||
}
|
||||
if (clean.proxyUrl) {
|
||||
secrets['proxyUrl'] = clean.proxyUrl;
|
||||
clean.proxyUrl = '';
|
||||
}
|
||||
// A Slack / Discord / Teams webhook URL is bearer-equivalent: anyone
|
||||
// holding it can post into the channel. Same treatment as a password —
|
||||
// encrypted at rest, blanked in the settings export and for MCP agents.
|
||||
if (clean.webhookUrl) {
|
||||
secrets['webhookUrl'] = clean.webhookUrl;
|
||||
clean.webhookUrl = '';
|
||||
}
|
||||
return { clean, secrets };
|
||||
}
|
||||
|
||||
/** Re-apply previously split secrets onto a (cleaned) config, in place. */
|
||||
function applyConfigSecrets(
|
||||
config: CrawlConfig,
|
||||
secrets: Record<string, string>,
|
||||
): CrawlConfig {
|
||||
if (secrets['auth.password'] !== undefined && config.auth) {
|
||||
config.auth.password = secrets['auth.password'];
|
||||
}
|
||||
if (secrets['auth.token'] !== undefined && config.auth) {
|
||||
config.auth.token = secrets['auth.token'];
|
||||
}
|
||||
if (
|
||||
secrets['formLogin.browser.passwordValue'] !== undefined &&
|
||||
config.formLogin?.browser
|
||||
) {
|
||||
config.formLogin.browser.passwordValue = secrets['formLogin.browser.passwordValue'];
|
||||
}
|
||||
if (secrets['proxyUrl'] !== undefined) {
|
||||
config.proxyUrl = secrets['proxyUrl'];
|
||||
}
|
||||
if (secrets['webhookUrl'] !== undefined) {
|
||||
config.webhookUrl = secrets['webhookUrl'];
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
/** A copy of the config with every secret blanked — for the shareable
|
||||
* settings-export, which must never carry credentials. Accepts a loose
|
||||
* record because the export IPC types its payload as `Record<string,
|
||||
* unknown>`; the JSON round-trip inside `splitConfigSecrets` tolerates
|
||||
* partial/extra fields. */
|
||||
function redactConfigSecrets(config: Record<string, unknown>): Record<string, unknown> {
|
||||
return splitConfigSecrets(config as unknown as CrawlConfig).clean as unknown as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
}
|
||||
// handed to a colleague in a shared settings-export or to an MCP agent.
|
||||
// `./config-secrets.ts` enumerates them and splits / blanks / restores them;
|
||||
// the helpers below handle the at-rest envelope (prefs / project meta).
|
||||
|
||||
/** An MCP agent's list-mode URLs, cleaned the way the desktop's list
|
||||
* editor cleans pasted text: trimmed, blank and `#` comment lines dropped,
|
||||
@@ -2571,29 +2504,6 @@ function cleanBridgeUrlList(raw: unknown): string[] {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** `config` with its secrets blanked, for replies to an MCP agent: an
|
||||
* agent's context goes to its model provider, so the user's passwords,
|
||||
* tokens and proxy credentials must never be in it. */
|
||||
function configForAgent(config: CrawlConfig): CrawlConfig {
|
||||
return splitConfigSecrets(config).clean;
|
||||
}
|
||||
|
||||
/** `next` with every secret it leaves blank taken from `current`. An agent
|
||||
* only ever sees blanked secrets (`configForAgent`), so a read-modify-write
|
||||
* of the config sends them back blank — that must keep the stored values,
|
||||
* not wipe them. */
|
||||
function keepStoredSecrets(next: CrawlConfig, current: CrawlConfig | null): CrawlConfig {
|
||||
if (!current) return next;
|
||||
const stored = splitConfigSecrets(current).secrets;
|
||||
const given = splitConfigSecrets(next).secrets;
|
||||
const keep: Record<string, string> = {};
|
||||
for (const [field, value] of Object.entries(stored)) {
|
||||
if (!given[field]) keep[field] = value;
|
||||
}
|
||||
if (Object.keys(keep).length === 0) return next;
|
||||
return applyConfigSecrets(JSON.parse(JSON.stringify(next)) as CrawlConfig, keep);
|
||||
}
|
||||
|
||||
/** Serialize a config for at-rest storage: secrets are pulled out and the
|
||||
* whole secret bundle is encrypted into one field, the rest stays plain
|
||||
* (and human-diffable). Returns the JSON string to persist. */
|
||||
@@ -9252,11 +9162,9 @@ function registerIpc(): void {
|
||||
// is intentionally loose (full CrawlConfig) because the desktop's
|
||||
// Settings dialog has dozens of fields and gating MCP narrower
|
||||
// than the UI would be arbitrary. The crawler itself validates
|
||||
// ranges at launch time.
|
||||
const cfg = input as CrawlConfig;
|
||||
if (!cfg || typeof cfg !== 'object') {
|
||||
throw new Error('CrawlConfig object required.');
|
||||
}
|
||||
// ranges at launch time; field *types* are checked here, because a
|
||||
// client may send undeclared values as strings ("false" is truthy).
|
||||
const cfg = coerceAgentConfig(input);
|
||||
currentSession().lastCrawlConfig = keepStoredSecrets(
|
||||
{ ...DEFAULT_CRAWL_CONFIG, ...cfg },
|
||||
currentSession().lastCrawlConfig,
|
||||
|
||||
@@ -2216,7 +2216,7 @@ function SpiderCrawlPanel({ form, update }: PanelProps) {
|
||||
/>
|
||||
<CrawlRow
|
||||
label="External Links"
|
||||
info="Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here means fully crawling those pages, following their links onward too. Store keeps outbound links in the link graph."
|
||||
info="Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here also fetches each external page in full (GET) for its status and title; external pages are never crawled through — their links are not followed. Store keeps outbound links in the link graph."
|
||||
example="Crawl off (default) — status-check externals without spidering the whole web."
|
||||
crawl={{ checked: form.crawlExternal, onChange: (v) => update('crawlExternal', v) }}
|
||||
store={{
|
||||
|
||||
@@ -570,8 +570,8 @@ export const AZ_INFO_TIPS: Record<string, string> = {
|
||||
'Eyni saytdakı <a href> hədəfləri. Tara söndürülü işi sabit səhifə dəstinin auditinə çevirir — sitemap-lər, kanoniklər və aşağıdakı digər bəyan edilmiş alternativlər kəşfi yenə qidalandırır. Saxla söndürülü keçid qrafını boşaldır: daxil olan keçidlər, çıxış keçidləri, lövbər mətni hesabatları və keçid balı onunla birlikdə gedir.',
|
||||
['Leave both on. Crawl off only when a sitemap or URL list already defines the exact set you want.']:
|
||||
'Hər ikisini aktiv saxlayın. Tara-nı yalnız sitemap və ya URL siyahısı artıq istədiyiniz dəqiq dəsti müəyyən edirsə söndürün.',
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here means fully crawling those pages, following their links onward too. Store keeps outbound links in the link graph.']:
|
||||
'Başqa hostlara çıxış keçidləri həmişə status yoxlanır (hər biri bir HEAD) ki, Qırıq keçidlər ölü xariciləri tutsun — bu, bu sətirdən asılı deyil. Burada Tara həmin səhifələri tam taramaq, onların keçidlərini də irəli izləmək deməkdir. Saxla çıxış keçidlərini keçid qrafında saxlayır.',
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here also fetches each external page in full (GET) for its status and title; external pages are never crawled through — their links are not followed. Store keeps outbound links in the link graph.']:
|
||||
'Başqa hostlara çıxış keçidləri həmişə status yoxlanır (hər biri bir HEAD) ki, Qırıq keçidlər ölü xariciləri tutsun — bu, bu sətirdən asılı deyil. Burada Tara hər xarici səhifəni statusu və başlığı üçün tam (GET) yükləyir; xarici səhifələr heç vaxt daha dərindən taranmır — onların keçidləri izlənmir. Saxla çıxış keçidlərini keçid qrafında saxlayır.',
|
||||
['Crawl off (default) — status-check externals without spidering the whole web.']:
|
||||
'Tara söndürülü (standart) — bütün vebi taramadan xaricilərin statusunu yoxla.',
|
||||
['<link rel=canonical> and its HTTP Link: header form. Crawl also enqueues the canonical target, treating it as a navigation hint. Store feeds the Canonicals tab and every canonical issue filter.']:
|
||||
|
||||
@@ -573,8 +573,8 @@ export const ES_INFO_TIPS: Record<string, string> = {
|
||||
'Destinos de <a href> en el mismo sitio. Rastrear desactivado convierte la ejecución en una auditoría de un conjunto fijo de páginas — los sitemaps, canonicals y demás alternativas declaradas abajo siguen alimentando el descubrimiento. Almacenar desactivado vacía el grafo de enlaces: enlaces entrantes, salientes, informes de texto ancla y puntuación de enlaces desaparecen con él.',
|
||||
['Leave both on. Crawl off only when a sitemap or URL list already defines the exact set you want.']:
|
||||
'Deja ambos activados. Rastrear desactivado solo cuando un sitemap o una lista de URL ya define el conjunto exacto que quieres.',
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here means fully crawling those pages, following their links onward too. Store keeps outbound links in the link graph.']:
|
||||
'Los enlaces salientes a otros hosts siempre se comprueban por estado (un HEAD cada uno) para que Enlaces rotos detecte externos muertos — eso no depende de esta fila. Rastrear aquí significa rastrear por completo esas páginas, siguiendo también sus enlaces. Almacenar conserva los enlaces salientes en el grafo de enlaces.',
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here also fetches each external page in full (GET) for its status and title; external pages are never crawled through — their links are not followed. Store keeps outbound links in the link graph.']:
|
||||
'Los enlaces salientes a otros hosts siempre se comprueban por estado (un HEAD cada uno) para que Enlaces rotos detecte externos muertos — eso no depende de esta fila. Rastrear aquí además descarga cada página externa completa (GET) para obtener su estado y título; las páginas externas nunca se rastrean a fondo: sus enlaces no se siguen. Almacenar conserva los enlaces salientes en el grafo de enlaces.',
|
||||
['Crawl off (default) — status-check externals without spidering the whole web.']:
|
||||
'Rastrear desactivado (por defecto) — comprobar el estado de los externos sin rastrear toda la web.',
|
||||
['<link rel=canonical> and its HTTP Link: header form. Crawl also enqueues the canonical target, treating it as a navigation hint. Store feeds the Canonicals tab and every canonical issue filter.']:
|
||||
|
||||
@@ -573,8 +573,8 @@ export const FR_INFO_TIPS: Record<string, string> = {
|
||||
"Cibles de <a href> sur le même site. Explorer désactivé transforme l'exécution en audit d'un ensemble fixe de pages — les sitemaps, canoniques et autres alternatives déclarées ci-dessous alimentent toujours la découverte. Stocker désactivé vide le graphe de liens : liens entrants, sortants, rapports de textes d'ancre et score de liens disparaissent avec lui.",
|
||||
['Leave both on. Crawl off only when a sitemap or URL list already defines the exact set you want.']:
|
||||
"Laissez les deux activés. Explorer désactivé seulement lorsqu'un sitemap ou une liste d'URL définit déjà l'ensemble exact voulu.",
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here means fully crawling those pages, following their links onward too. Store keeps outbound links in the link graph.']:
|
||||
"Les liens sortants vers d'autres hôtes ont toujours leur statut vérifié (un HEAD chacun) pour que Liens cassés détecte les externes morts — cela ne dépend pas de cette ligne. Explorer ici signifie explorer entièrement ces pages, en suivant aussi leurs liens. Stocker conserve les liens sortants dans le graphe de liens.",
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here also fetches each external page in full (GET) for its status and title; external pages are never crawled through — their links are not followed. Store keeps outbound links in the link graph.']:
|
||||
"Les liens sortants vers d'autres hôtes ont toujours leur statut vérifié (un HEAD chacun) pour que Liens cassés détecte les externes morts — cela ne dépend pas de cette ligne. Explorer ici télécharge en plus chaque page externe en entier (GET) pour son statut et son titre ; les pages externes ne sont jamais explorées plus loin — leurs liens ne sont pas suivis. Stocker conserve les liens sortants dans le graphe de liens.",
|
||||
['Crawl off (default) — status-check externals without spidering the whole web.']:
|
||||
'Explorer désactivé (par défaut) — vérifier le statut des externes sans explorer tout le web.',
|
||||
['<link rel=canonical> and its HTTP Link: header form. Crawl also enqueues the canonical target, treating it as a navigation hint. Store feeds the Canonicals tab and every canonical issue filter.']:
|
||||
|
||||
@@ -568,8 +568,8 @@ export const HI_INFO_TIPS: Record<string, string> = {
|
||||
'उसी साइट पर <a href> लक्ष्य। क्रॉल बंद रन को निश्चित पेज सेट के ऑडिट में बदल देता है — साइटमैप, कैनोनिकल और नीचे के अन्य घोषित विकल्प फिर भी खोज को भरते हैं। संग्रह बंद लिंक ग्राफ़ खाली कर देता है: इनलिंक, आउटलिंक, एंकर-टेक्स्ट रिपोर्ट और लिंक स्कोर सब उसके साथ जाते हैं।',
|
||||
['Leave both on. Crawl off only when a sitemap or URL list already defines the exact set you want.']:
|
||||
'दोनों चालू रखें। क्रॉल केवल तब बंद करें जब कोई साइटमैप या URL सूची पहले से ठीक वही सेट तय करती हो जो आप चाहते हैं।',
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here means fully crawling those pages, following their links onward too. Store keeps outbound links in the link graph.']:
|
||||
"अन्य होस्ट के आउटबाउंड लिंक हमेशा स्टेटस-जाँचे जाते हैं (प्रत्येक एक HEAD) ताकि 'टूटे लिंक' मृत बाहरी पकड़े — वह इस पंक्ति पर निर्भर नहीं। यहाँ क्रॉल का अर्थ है उन पेजों को पूरी तरह क्रॉल करना, उनके लिंक भी आगे फ़ॉलो करना। संग्रह आउटबाउंड लिंक को लिंक ग्राफ़ में रखता है।",
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here also fetches each external page in full (GET) for its status and title; external pages are never crawled through — their links are not followed. Store keeps outbound links in the link graph.']:
|
||||
"अन्य होस्ट के आउटबाउंड लिंक हमेशा स्टेटस-जाँचे जाते हैं (प्रत्येक एक HEAD) ताकि 'टूटे लिंक' मृत बाहरी पकड़े — वह इस पंक्ति पर निर्भर नहीं। यहाँ क्रॉल हर बाहरी पेज को उसके स्टेटस और शीर्षक के लिए पूरा (GET) भी लाता है; बाहरी पेजों से आगे कभी क्रॉल नहीं होता — उनके लिंक फ़ॉलो नहीं किए जाते। संग्रह आउटबाउंड लिंक को लिंक ग्राफ़ में रखता है।",
|
||||
['Crawl off (default) — status-check externals without spidering the whole web.']:
|
||||
'क्रॉल बंद (डिफ़ॉल्ट) — पूरा वेब स्पाइडर किए बिना बाहरी लिंक की स्टेटस-जाँच करें।',
|
||||
['<link rel=canonical> and its HTTP Link: header form. Crawl also enqueues the canonical target, treating it as a navigation hint. Store feeds the Canonicals tab and every canonical issue filter.']:
|
||||
|
||||
@@ -573,8 +573,8 @@ export const IT_INFO_TIPS: Record<string, string> = {
|
||||
"Destinazioni di <a href> sullo stesso sito. Scansiona disattivato trasforma l'esecuzione in un audit di un insieme fisso di pagine — sitemap, canonical e le altre alternative dichiarate sotto alimentano comunque la scoperta. Memorizza disattivato svuota il grafo dei link: link in entrata, in uscita, report dei testi di ancoraggio e punteggio link se ne vanno con esso.",
|
||||
['Leave both on. Crawl off only when a sitemap or URL list already defines the exact set you want.']:
|
||||
"Lascia entrambi attivati. Scansiona disattivato solo quando una sitemap o una lista di URL definisce già l'insieme esatto che vuoi.",
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here means fully crawling those pages, following their links onward too. Store keeps outbound links in the link graph.']:
|
||||
'I link in uscita verso altri host vengono sempre controllati per stato (un HEAD ciascuno) così Link interrotti cattura gli esterni morti — questo non dipende da questa riga. Scansiona qui significa scansionare completamente quelle pagine, seguendo anche i loro link. Memorizza conserva i link in uscita nel grafo dei link.',
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here also fetches each external page in full (GET) for its status and title; external pages are never crawled through — their links are not followed. Store keeps outbound links in the link graph.']:
|
||||
'I link in uscita verso altri host vengono sempre controllati per stato (un HEAD ciascuno) così Link interrotti cattura gli esterni morti — questo non dipende da questa riga. Scansiona qui scarica inoltre per intero (GET) ogni pagina esterna per stato e titolo; le pagine esterne non vengono mai scansionate oltre: i loro link non vengono seguiti. Memorizza conserva i link in uscita nel grafo dei link.',
|
||||
['Crawl off (default) — status-check externals without spidering the whole web.']:
|
||||
"Scansiona disattivato (predefinito) — controlla lo stato degli esterni senza scansionare l'intero web.",
|
||||
['<link rel=canonical> and its HTTP Link: header form. Crawl also enqueues the canonical target, treating it as a navigation hint. Store feeds the Canonicals tab and every canonical issue filter.']:
|
||||
|
||||
@@ -563,8 +563,8 @@ export const KO_INFO_TIPS: Record<string, string> = {
|
||||
'같은 사이트의 <a href> 대상. 크롤링을 끄면 실행이 고정된 페이지 집합의 감사로 바뀝니다 — 사이트맵, canonical, 아래의 다른 선언된 대체 버전은 여전히 발견에 기여합니다. 저장을 끄면 링크 그래프가 비워집니다: 인링크, 아웃링크, 앵커 텍스트 보고서, 링크 점수가 모두 사라집니다.',
|
||||
['Leave both on. Crawl off only when a sitemap or URL list already defines the exact set you want.']:
|
||||
'둘 다 켜 두세요. 사이트맵이나 URL 목록이 원하는 정확한 집합을 이미 정의할 때만 크롤링을 끄세요.',
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here means fully crawling those pages, following their links onward too. Store keeps outbound links in the link graph.']:
|
||||
'다른 호스트로 나가는 링크는 항상 상태 검사(각각 HEAD 한 번)를 받아 깨진 링크가 죽은 외부 링크를 잡습니다 — 이는 이 행에 의존하지 않습니다. 여기서 크롤링은 그 페이지들을 완전히 크롤링하고 그 링크까지 따라간다는 뜻입니다. 저장은 아웃바운드 링크를 링크 그래프에 유지합니다.',
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here also fetches each external page in full (GET) for its status and title; external pages are never crawled through — their links are not followed. Store keeps outbound links in the link graph.']:
|
||||
'다른 호스트로 나가는 링크는 항상 상태 검사(각각 HEAD 한 번)를 받아 깨진 링크가 죽은 외부 링크를 잡습니다 — 이는 이 행에 의존하지 않습니다. 여기서 크롤링은 각 외부 페이지를 상태와 제목을 위해 전체(GET)로 가져옵니다. 외부 페이지를 거쳐 더 크롤링하지는 않으며 그 링크는 따라가지 않습니다. 저장은 아웃바운드 링크를 링크 그래프에 유지합니다.',
|
||||
['Crawl off (default) — status-check externals without spidering the whole web.']:
|
||||
'크롤링 끔(기본값) — 웹 전체를 스파이더링하지 않고 외부 링크 상태만 검사합니다.',
|
||||
['<link rel=canonical> and its HTTP Link: header form. Crawl also enqueues the canonical target, treating it as a navigation hint. Store feeds the Canonicals tab and every canonical issue filter.']:
|
||||
|
||||
@@ -570,8 +570,8 @@ export const NL_INFO_TIPS: Record<string, string> = {
|
||||
"<a href>-doelen op dezelfde site. Met Crawlen uit wordt de run een audit van een vaste set pagina's — sitemaps, canonicals en de andere opgegeven alternatieven hieronder voeden nog steeds de ontdekking. Met Opslaan uit blijft de linkgraaf leeg: inkomende links, uitgaande links, ankertekstrapporten en linkscore verdwijnen allemaal.",
|
||||
['Leave both on. Crawl off only when a sitemap or URL list already defines the exact set you want.']:
|
||||
'Laat beide aan. Zet Crawlen alleen uit als een sitemap of URL-lijst al precies de set bepaalt die je wilt.',
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here means fully crawling those pages, following their links onward too. Store keeps outbound links in the link graph.']:
|
||||
"Van uitgaande links naar andere hosts wordt altijd de status gecontroleerd (één HEAD per link), zodat Kapotte links dode externe links vindt — dat staat los van deze rij. Crawlen betekent hier dat die pagina's volledig worden gecrawld, inclusief het verder volgen van hun links. Opslaan bewaart uitgaande links in de linkgraaf.",
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here also fetches each external page in full (GET) for its status and title; external pages are never crawled through — their links are not followed. Store keeps outbound links in the link graph.']:
|
||||
"Van uitgaande links naar andere hosts wordt altijd de status gecontroleerd (één HEAD per link), zodat Kapotte links dode externe links vindt — dat staat los van deze rij. Crawlen haalt hier daarnaast elke externe pagina volledig op (GET) voor de status en titel; externe pagina's worden nooit verder gecrawld — hun links worden niet gevolgd. Opslaan bewaart uitgaande links in de linkgraaf.",
|
||||
['Crawl off (default) — status-check externals without spidering the whole web.']:
|
||||
'Crawlen uit (standaard) — controleer de status van externe links zonder het hele web af te spideren.',
|
||||
['<link rel=canonical> and its HTTP Link: header form. Crawl also enqueues the canonical target, treating it as a navigation hint. Store feeds the Canonicals tab and every canonical issue filter.']:
|
||||
|
||||
@@ -571,8 +571,8 @@ export const PT_BR_INFO_TIPS: Record<string, string> = {
|
||||
'Destinos de <a href> no mesmo site. Rastrear desligado transforma a execução em uma auditoria de um conjunto fixo de páginas — sitemaps, canonicals e as outras alternativas declaradas abaixo ainda alimentam a descoberta. Armazenar desligado esvazia o grafo de links: links de entrada, de saída, relatórios de texto âncora e pontuação de links vão embora com ele.',
|
||||
['Leave both on. Crawl off only when a sitemap or URL list already defines the exact set you want.']:
|
||||
'Deixe ambos ligados. Rastrear desligado só quando um sitemap ou lista de URLs já define o conjunto exato que você quer.',
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here means fully crawling those pages, following their links onward too. Store keeps outbound links in the link graph.']:
|
||||
'Links de saída para outros hosts sempre têm o status verificado (um HEAD cada) para que Links quebrados capture externos mortos — isso não depende desta linha. Rastrear aqui significa rastrear essas páginas por completo, seguindo também os links delas. Armazenar mantém os links de saída no grafo de links.',
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here also fetches each external page in full (GET) for its status and title; external pages are never crawled through — their links are not followed. Store keeps outbound links in the link graph.']:
|
||||
'Links de saída para outros hosts sempre têm o status verificado (um HEAD cada) para que Links quebrados capture externos mortos — isso não depende desta linha. Rastrear aqui também baixa cada página externa por completo (GET) para obter status e título; páginas externas nunca são rastreadas adiante — os links delas não são seguidos. Armazenar mantém os links de saída no grafo de links.',
|
||||
['Crawl off (default) — status-check externals without spidering the whole web.']:
|
||||
'Rastrear desligado (padrão) — verificar o status dos externos sem rastrear a web inteira.',
|
||||
['<link rel=canonical> and its HTTP Link: header form. Crawl also enqueues the canonical target, treating it as a navigation hint. Store feeds the Canonicals tab and every canonical issue filter.']:
|
||||
|
||||
@@ -572,8 +572,8 @@ export const RU_INFO_TIPS: Record<string, string> = {
|
||||
'Цели <a href> на том же сайте. «Сканировать» выкл. превращает запуск в аудит фиксированного набора страниц — sitemap, canonical и прочие объявленные альтернативы ниже по-прежнему питают обнаружение. «Сохранять» выкл. опустошает граф ссылок: входящие, исходящие, отчёты по анкорам и ссылочный балл уходят вместе с ним.',
|
||||
['Leave both on. Crawl off only when a sitemap or URL list already defines the exact set you want.']:
|
||||
'Оставьте оба вкл. «Сканировать» выкл. — только когда sitemap или список URL уже задаёт точный нужный набор.',
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here means fully crawling those pages, following their links onward too. Store keeps outbound links in the link graph.']:
|
||||
'Исходящие ссылки на другие хосты всегда проверяются на статус (по одному HEAD), чтобы «Битые ссылки» ловили мёртвые внешние — это не зависит от этой строки. «Сканировать» здесь означает полное сканирование тех страниц с переходом и по их ссылкам. «Сохранять» держит исходящие ссылки в графе ссылок.',
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here also fetches each external page in full (GET) for its status and title; external pages are never crawled through — their links are not followed. Store keeps outbound links in the link graph.']:
|
||||
'Исходящие ссылки на другие хосты всегда проверяются на статус (по одному HEAD), чтобы «Битые ссылки» ловили мёртвые внешние — это не зависит от этой строки. «Сканировать» здесь дополнительно загружает каждую внешнюю страницу целиком (GET) ради статуса и заголовка; дальше внешних страниц сканирование не идёт — их ссылки не отслеживаются. «Сохранять» держит исходящие ссылки в графе ссылок.',
|
||||
['Crawl off (default) — status-check externals without spidering the whole web.']:
|
||||
'«Сканировать» выкл. (по умолчанию) — проверять статус внешних, не обходя весь интернет.',
|
||||
['<link rel=canonical> and its HTTP Link: header form. Crawl also enqueues the canonical target, treating it as a navigation hint. Store feeds the Canonicals tab and every canonical issue filter.']:
|
||||
|
||||
@@ -572,8 +572,8 @@ export const TR_INFO_TIPS: Record<string, string> = {
|
||||
"Aynı sitedeki <a href> hedefleri. Tara kapalıyken çalışma, sabit bir sayfa kümesinin denetimine dönüşür — sitemap'ler, canonical'lar ve aşağıdaki diğer bildirilen alternatifler keşfi beslemeye devam eder. Sakla kapalıyken bağlantı grafiği boşalır: inlink'ler, outlink'ler, anchor metni raporları ve link skoru da onunla birlikte gider.",
|
||||
['Leave both on. Crawl off only when a sitemap or URL list already defines the exact set you want.']:
|
||||
"İkisini de açık bırakın. Yalnızca bir sitemap veya URL listesi istediğiniz kümeyi zaten tanımlıyorsa Tara'yı kapatın.",
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here means fully crawling those pages, following their links onward too. Store keeps outbound links in the link graph.']:
|
||||
"Diğer host'lara giden bağlantıların durumu her zaman kontrol edilir (her biri için bir HEAD), böylece Bozuk Bağlantılar ölü dış bağlantıları yakalar — bu, bu satıra bağlı değildir. Buradaki Tara, o sayfaları tümüyle taramak ve onların bağlantılarını da izlemek demektir. Sakla, giden bağlantıları bağlantı grafiğinde tutar.",
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here also fetches each external page in full (GET) for its status and title; external pages are never crawled through — their links are not followed. Store keeps outbound links in the link graph.']:
|
||||
"Diğer host'lara giden bağlantıların durumu her zaman kontrol edilir (her biri için bir HEAD), böylece Bozuk Bağlantılar ölü dış bağlantıları yakalar — bu, bu satıra bağlı değildir. Buradaki Tara, her dış sayfayı durumu ve başlığı için ayrıca tümüyle (GET) indirir; dış sayfaların içinde asla taramaya devam edilmez — bağlantıları izlenmez. Sakla, giden bağlantıları bağlantı grafiğinde tutar.",
|
||||
['Crawl off (default) — status-check externals without spidering the whole web.']:
|
||||
"Tara kapalı (varsayılan) — tüm web'i taramadan dış bağlantıların durumunu kontrol edin.",
|
||||
['<link rel=canonical> and its HTTP Link: header form. Crawl also enqueues the canonical target, treating it as a navigation hint. Store feeds the Canonicals tab and every canonical issue filter.']:
|
||||
|
||||
@@ -559,8 +559,8 @@ export const ZH_CN_INFO_TIPS: Record<string, string> = {
|
||||
'同一站点上的 <a href> 目标。“抓取”关会将运行变成对固定页面集的审计——sitemap、canonical 及下方其他声明的替代版本仍会推动发现。“存储”关会清空链接图:入链、出链、锚文本报告和链接得分随之消失。',
|
||||
['Leave both on. Crawl off only when a sitemap or URL list already defines the exact set you want.']:
|
||||
'两者都保持开启。仅当 sitemap 或 URL 列表已定义你想要的精确集合时关闭“抓取”。',
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here means fully crawling those pages, following their links onward too. Store keeps outbound links in the link graph.']:
|
||||
'指向其他主机的出站链接始终会进行状态检查(每个一次 HEAD),使“断链”能捕获失效外链——这不依赖于此行。此处的“抓取”意味着完整抓取那些页面,并继续跟踪其链接。“存储”将出站链接保留在链接图中。',
|
||||
['Outbound links to other hosts are always status-checked (one HEAD each) so Broken Links catches dead externals — that does not depend on this row. Crawl here also fetches each external page in full (GET) for its status and title; external pages are never crawled through — their links are not followed. Store keeps outbound links in the link graph.']:
|
||||
'指向其他主机的出站链接始终会进行状态检查(每个一次 HEAD),使“断链”能捕获失效外链——这不依赖于此行。此处的“抓取”还会完整获取(GET)每个外部页面以获得其状态和标题;外部页面永远不会被继续抓取——不会跟踪其链接。“存储”将出站链接保留在链接图中。',
|
||||
['Crawl off (default) — status-check externals without spidering the whole web.']:
|
||||
'“抓取”关(默认)——检查外链状态但不去抓取整个互联网。',
|
||||
['<link rel=canonical> and its HTTP Link: header form. Crawl also enqueues the canonical target, treating it as a navigation hint. Store feeds the Canonicals tab and every canonical issue filter.']:
|
||||
|
||||
@@ -25,6 +25,12 @@ function kbToBytes(raw: string): number | undefined {
|
||||
return Number.isFinite(kb) && kb > 0 ? Math.round(kb * 1024) : undefined;
|
||||
}
|
||||
|
||||
/** A row is one image on one page: the same image id repeats across
|
||||
* pages, and one page holds many images, so neither id alone is unique. */
|
||||
function usageKey(row: ImageRow): string {
|
||||
return `${row.id}:${row.fromUrl ?? ''}`;
|
||||
}
|
||||
|
||||
export function ImagesTab() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const lang = i18n.language;
|
||||
@@ -42,6 +48,7 @@ export function ImagesTab() {
|
||||
const [sortDir, setSortDir] = useState<'asc' | 'desc'>('desc');
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [activeUsage, setActiveUsage] = useState<string | null>(null);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const minByteSize = kbToBytes(minKb);
|
||||
|
||||
@@ -112,11 +119,9 @@ export function ImagesTab() {
|
||||
getScrollElement: () => scrollRef.current,
|
||||
estimateSize: () => ROW_HEIGHT,
|
||||
overscan: 30,
|
||||
// Composite key: the tab is per-usage, so the same image id can appear
|
||||
// on several rows (one per page). Keying by id alone would collide.
|
||||
getItemKey: (index) => {
|
||||
const r = rows[index];
|
||||
return r ? `${r.id}:${r.fromUrl ?? ''}` : index;
|
||||
return r ? usageKey(r) : index;
|
||||
},
|
||||
});
|
||||
|
||||
@@ -154,6 +159,7 @@ export function ImagesTab() {
|
||||
// answers "where is this image used, and what else is on that page".
|
||||
const selectPage = (row: ImageRow) => {
|
||||
if (row.fromUrlId === null) return;
|
||||
setActiveUsage(usageKey(row));
|
||||
setSelectedUrlId(row.fromUrlId);
|
||||
setSelectedUrlIds([row.fromUrlId]);
|
||||
};
|
||||
@@ -343,7 +349,15 @@ export function ImagesTab() {
|
||||
{virtualizer.getVirtualItems().map((vi) => {
|
||||
const row = rows[vi.index];
|
||||
if (!row) return null;
|
||||
const isActivePage = row.fromUrlId !== null && row.fromUrlId === selectedUrlId;
|
||||
// Only the clicked usage: highlighting every row whose page is
|
||||
// selected lit up each other image on that page (rows 1 and
|
||||
// 18 — two logos on the home page) as if both were picked.
|
||||
// The page check drops the highlight once another tab
|
||||
// selects a different URL.
|
||||
const isActive =
|
||||
row.fromUrlId !== null &&
|
||||
row.fromUrlId === selectedUrlId &&
|
||||
usageKey(row) === activeUsage;
|
||||
return (
|
||||
<div
|
||||
key={vi.key}
|
||||
@@ -352,7 +366,7 @@ export function ImagesTab() {
|
||||
className={clsx(
|
||||
'absolute left-0 top-0 flex items-center border-b border-surface-900 text-[11px]',
|
||||
row.fromUrlId !== null && 'cursor-pointer',
|
||||
isActivePage ? 'bg-accent-500/20' : 'hover:bg-surface-900/60',
|
||||
isActive ? 'bg-accent-500/20' : 'hover:bg-surface-900/60',
|
||||
)}
|
||||
style={{
|
||||
transform: `translateY(${vi.start}px)`,
|
||||
|
||||
@@ -6,14 +6,14 @@
|
||||
* SQLite WAL mode permits arbitrary concurrent readers.
|
||||
*/
|
||||
|
||||
import type { ProjectDb } from '@freecrawl/db';
|
||||
import { resolveUrlCategory, type ProjectDb } from '@freecrawl/db';
|
||||
import { diagnoseCrawl, htmlToMarkdown } from '@freecrawl/core';
|
||||
import { DEFAULT_CRAWL_CONFIG, rankIssues } from '@freecrawl/shared-types';
|
||||
import type {
|
||||
AiProvider,
|
||||
CrawlConfig,
|
||||
CrawlProgress,
|
||||
SeoProvider,
|
||||
UrlCategory,
|
||||
} from '@freecrawl/shared-types';
|
||||
import { bridgeRequest } from './desktop-bridge.js';
|
||||
|
||||
@@ -37,9 +37,10 @@ export interface Tool {
|
||||
// internal/external content kinds, status:* buckets, security:*,
|
||||
// indexability:*, tab:* groupings, and per-issue drill-downs like
|
||||
// "issues:title-missing" / "issues:severity-critical"). The union is a
|
||||
// type, not a runtime list, so we validate at the DB layer (categoryWhereClause)
|
||||
// and describe rather than `enum`-constrain — an enum of a hand-picked subset
|
||||
// would reject the very `issues:*` drill-downs that `top_issues` returns.
|
||||
// type, not a runtime list, so we validate at the DB layer
|
||||
// (`resolveUrlCategory`) and describe rather than `enum`-constrain — an enum
|
||||
// of a hand-picked subset would reject the very `issues:*` drill-downs that
|
||||
// `top_issues` returns.
|
||||
const URL_CATEGORY_DESC =
|
||||
'UrlCategory filter matching the desktop UI categories. Accepts "all"; ' +
|
||||
'internal:*/external:* content kinds; status:2xx/3xx/4xx/5xx/no-response/blocked-robots; ' +
|
||||
@@ -147,6 +148,18 @@ function clamp(n: unknown, min: number, max: number, fallback: number): number {
|
||||
return Math.max(min, Math.min(max, Math.floor(v)));
|
||||
}
|
||||
|
||||
/**
|
||||
* One typed property per CrawlConfig field, typed like its default. A
|
||||
* client sends real JSON only for declared properties; without these,
|
||||
* `set_crawl_config` received `"false"` / `"[...]"` strings.
|
||||
*/
|
||||
const CRAWL_CONFIG_PROPERTIES: Record<string, { type: string }> = Object.fromEntries(
|
||||
Object.entries(DEFAULT_CRAWL_CONFIG).map(([key, value]) => [
|
||||
key,
|
||||
{ type: Array.isArray(value) ? 'array' : typeof value },
|
||||
]),
|
||||
);
|
||||
|
||||
export function buildTools(): Tool[] {
|
||||
return [
|
||||
{
|
||||
@@ -174,13 +187,13 @@ export function buildTools(): Tool[] {
|
||||
{
|
||||
name: 'query_urls',
|
||||
description:
|
||||
'Paginated query against the URLs table with the same category filter the UI uses. Returns rows + total count. Use `category` to narrow (e.g. "issues:title-missing"), `search` to substring-match URLs/titles, and `limit`/`offset` to page through.',
|
||||
'Paginated query against the URLs table with the same category filter the UI uses. Returns rows + total count. Use `category` to narrow (e.g. "issues:title-missing", exactly as top_issues returns it), `search` to substring-match URLs/titles, and `limit`/`offset` to page through. An unknown category is an error, never a silent "all". Broken-link categories count links, not URLs — list them with query_broken_links.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
category: {
|
||||
type: 'string',
|
||||
description: 'UrlCategory filter (e.g. "all", "internal:html", "issues:title-missing", "status:4xx"). Defaults to "all".',
|
||||
description: `${URL_CATEGORY_DESC} A get_overview_counts counter name ("issues:h1Missing") is accepted as its category.`,
|
||||
},
|
||||
search: {
|
||||
type: 'string',
|
||||
@@ -215,7 +228,7 @@ export function buildTools(): Tool[] {
|
||||
},
|
||||
},
|
||||
handler: (args, db) => {
|
||||
const category = (args.category as UrlCategory | undefined) ?? 'all';
|
||||
const category = resolveUrlCategory(args.category);
|
||||
const search = typeof args.search === 'string' ? args.search : undefined;
|
||||
const limit = Math.min(
|
||||
Math.max(typeof args.limit === 'number' ? args.limit : 50, 1),
|
||||
@@ -246,6 +259,18 @@ export function buildTools(): Tool[] {
|
||||
fieldsArg,
|
||||
),
|
||||
);
|
||||
// The broken-link filters describe link rows, so the URL table
|
||||
// matches none — say where they are instead of an unexplained 0
|
||||
// next to a non-zero top_issues count.
|
||||
if (category.startsWith('issues:broken-links-')) {
|
||||
return {
|
||||
rows: projected,
|
||||
total,
|
||||
limit,
|
||||
offset,
|
||||
note: 'Broken-link categories count links, not URL rows. Use query_broken_links (scope "internal" / "external") to list them.',
|
||||
};
|
||||
}
|
||||
return { rows: projected, total, limit, offset };
|
||||
},
|
||||
},
|
||||
@@ -349,7 +374,11 @@ export function buildTools(): Tool[] {
|
||||
respectRobotsTxt: { type: 'boolean' },
|
||||
respectCrawlDelay: { type: 'boolean' },
|
||||
followRedirects: { type: 'boolean' },
|
||||
crawlExternal: { type: 'boolean' },
|
||||
crawlExternal: {
|
||||
type: 'boolean',
|
||||
description:
|
||||
'Check external links: GET each link target on another host once for its status and title. External pages are never crawled through — their links are not followed.',
|
||||
},
|
||||
userAgent: { type: 'string' },
|
||||
includePatterns: { type: 'array', items: { type: 'string' } },
|
||||
excludePatterns: { type: 'array', items: { type: 'string' } },
|
||||
@@ -510,7 +539,7 @@ export function buildTools(): Tool[] {
|
||||
{
|
||||
name: 'top_issues',
|
||||
description:
|
||||
'Ranked list of non-empty issue categories from get_overview_counts, sorted by count descending. Quick way to ask "what are the biggest problems with this crawl?".',
|
||||
'Ranked list of non-empty issue checks, sorted by count descending. Quick way to ask "what are the biggest problems with this crawl?". Each entry has `category` (pass it to query_urls unchanged), `label`, `count` and `unit`: "urls" = pages, "images" = image usages (query_urls lists the pages carrying them; query_images lists the images), "links" = link rows (use query_broken_links).',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
@@ -527,14 +556,8 @@ export function buildTools(): Tool[] {
|
||||
Math.max(typeof args.limit === 'number' ? args.limit : 20, 1),
|
||||
200,
|
||||
);
|
||||
const counts = db.getOverviewCounts() as unknown as Record<string, unknown>;
|
||||
const issues = (counts.issues as Record<string, number>) ?? {};
|
||||
const ranked = Object.entries(issues)
|
||||
.filter(([, n]) => n > 0)
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.slice(0, limit)
|
||||
.map(([category, count]) => ({ category: `issues:${category}`, count }));
|
||||
return { issues: ranked };
|
||||
const ranked = rankIssues(db.getOverviewCounts().issues, db.getDisabledIssues());
|
||||
return { issues: ranked.slice(0, limit) };
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1002,7 +1025,7 @@ export function buildTools(): Tool[] {
|
||||
{
|
||||
name: 'query_images',
|
||||
description:
|
||||
'Project-wide image catalogue — one row per image USAGE (image × page), with src, alt, declared width/height, occurrences, fromUrl (the page), fromUrlId, and byteSize (from the post-crawl size probe or the crawled image row; null = unknown). Backs the Images tab. For "large images and where they are used", combine `minByteSize` with `sortBy: "byteSize"`.',
|
||||
'Project-wide image catalogue — one row per image USAGE (image × page), with src, alt, declared width/height, occurrences, fromUrl (the page), fromUrlId, byteSize (from the post-crawl size probe or the crawled image row; null = unknown) and isVariant. A variant (srcset / <picture> candidate) is not fetched or size-probed unless Settings › srcset Variants is on, so its byteSize is normally null; `minByteSize: 0` lists only the measured rows. Backs the Images tab. For "large images and where they are used", combine `minByteSize` with `sortBy: "byteSize"`.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
@@ -1755,7 +1778,7 @@ export function buildTools(): Tool[] {
|
||||
{
|
||||
requiresDb: false,
|
||||
name: 'get_crawl_config',
|
||||
description: 'Read the most recently-used CrawlConfig — the same config `start_crawl` falls back to when called without overrides. Reflects whatever the user (or the previous MCP `set_crawl_config` call) configured in Settings. Secrets (HTTP auth password / token, form-login password, proxy URL) are returned blank.',
|
||||
description: 'Read the most recently-used CrawlConfig — the same config `start_crawl` falls back to when called without overrides. Reflects whatever the user (or the previous MCP `set_crawl_config` call) configured in Settings. Secrets (HTTP auth password / token, form-login values, the proxy URL and every proxy profile URL, custom header values, the webhook URL) are returned blank; names stay readable.',
|
||||
inputSchema: { type: 'object', properties: {} },
|
||||
handler: async () =>
|
||||
bridgeRequest<unknown>('POST', '/v1/action/get-crawl-config', {}),
|
||||
@@ -1765,10 +1788,11 @@ export function buildTools(): Tool[] {
|
||||
requiresDb: false,
|
||||
name: 'set_crawl_config',
|
||||
description:
|
||||
'Persist a full CrawlConfig as the saved default — next `start_crawl` without overrides will use these settings. The input is the entire CrawlConfig object (every field the Settings dialog exposes). Pass `get_crawl_config` first to read the current shape, then send the modified copy back; secret fields left blank keep their stored values. Validation happens at crawl launch time — out-of-range values may be silently clamped or fail at start.',
|
||||
'Persist a full CrawlConfig as the saved default — next `start_crawl` without overrides will use these settings. The input is the entire CrawlConfig object (every field the Settings dialog exposes); a field left out resets to its default. Pass `get_crawl_config` first to read the current shape, then send the modified copy back; secret fields left blank keep their stored values. A field of the wrong type rejects the whole call with the field named; out-of-range values are clamped or fail at crawl launch.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
description: 'Full CrawlConfig object. Pass the result of `get_crawl_config` with your modifications layered on.',
|
||||
properties: CRAWL_CONFIG_PROPERTIES,
|
||||
additionalProperties: true,
|
||||
},
|
||||
handler: async (args) =>
|
||||
|
||||
+208
-75
@@ -1478,8 +1478,7 @@ export class Crawler extends EventEmitter {
|
||||
// Drop from `seen` first — these URLs were never actually
|
||||
// crawled, just stubbed; enqueue's seen-check would reject
|
||||
// them otherwise.
|
||||
this.seen.delete(p.url);
|
||||
this.enqueue({ url: p.url, depth: p.depth });
|
||||
this.enqueuePending(p);
|
||||
}
|
||||
await this.drainCrawlQueue();
|
||||
await this.externalQueue.onIdle();
|
||||
@@ -1918,8 +1917,12 @@ export class Crawler extends EventEmitter {
|
||||
// does: CDNs and WAFs answer HEAD with 403 / 405 / 5xx (or drop it)
|
||||
// for an image a GET serves fine, and some servers route GET only.
|
||||
// A redirect loop or a DNS / connect failure won't change on GET.
|
||||
// A 2xx HEAD without Content-Length (chunked — Cloudflare answers
|
||||
// image HEADs this way) says nothing about size; the GET measures
|
||||
// the body instead.
|
||||
const retry = result
|
||||
? result.status >= 400 && result.status !== IMAGE_REDIRECT_LIMIT_STATUS
|
||||
? (result.status >= 400 && result.status !== IMAGE_REDIRECT_LIMIT_STATUS) ||
|
||||
(result.status >= 200 && result.status < 300 && result.length === null)
|
||||
: !isHardTransportError(headErr);
|
||||
if (retry && !this.stopped) {
|
||||
try {
|
||||
@@ -1955,7 +1958,8 @@ export class Crawler extends EventEmitter {
|
||||
* internal address; that hop is not requested and its 3xx is recorded
|
||||
* instead. Each request after the first HEAD (a redirect hop, the GET
|
||||
* retry) waits for its own `maxRps` slot, and each has its own timeout.
|
||||
* The body is never read. Throws on a transport failure.
|
||||
* The body is read only by a GET whose 2xx answer has no Content-Length,
|
||||
* to measure it. Throws on a transport failure.
|
||||
*/
|
||||
private async fetchImageHeaders(src: string, method: 'HEAD' | 'GET'): Promise<ImageProbeResult> {
|
||||
const timeoutMs = Math.max(2_000, this.config.requestTimeoutMs / 2);
|
||||
@@ -1981,14 +1985,25 @@ export class Crawler extends EventEmitter {
|
||||
redirect: 'manual',
|
||||
signal: controller.signal,
|
||||
});
|
||||
} finally {
|
||||
} catch (err) {
|
||||
clearTimeout(timeout);
|
||||
throw err;
|
||||
}
|
||||
const status = res.status;
|
||||
const lenStr = res.headers.get('content-length');
|
||||
const location = status >= 300 && status < 400 ? res.headers.get('location') : null;
|
||||
// HEAD has no body (undici still wants 1xx/204 drained); a GET's is
|
||||
// never needed — the headers carry the size.
|
||||
if (!location && method === 'GET' && lenStr === null && status >= 200 && status < 300) {
|
||||
// Chunked answer: the size is only in the body. Measured under the
|
||||
// same timeout, so a stalled stream ends as "unknown size".
|
||||
try {
|
||||
return { status, length: await countBodyBytes(res, ABSOLUTE_BODY_CAP_BYTES) };
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
clearTimeout(timeout);
|
||||
// HEAD has no body (undici still wants 1xx/204 drained); otherwise
|
||||
// the headers carry the size.
|
||||
try {
|
||||
await res.body?.cancel();
|
||||
} catch {
|
||||
@@ -3088,8 +3103,7 @@ export class Crawler extends EventEmitter {
|
||||
if (pending.url === seededStartUrl) continue;
|
||||
// Drop from `seen` so enqueue accepts it — these URLs are genuinely
|
||||
// unfinished work.
|
||||
this.seen.delete(pending.url);
|
||||
this.enqueue({ url: pending.url, depth: pending.depth });
|
||||
this.enqueuePending(pending);
|
||||
}
|
||||
|
||||
// Re-queue any external URLs that were stubbed but never probed.
|
||||
@@ -3098,6 +3112,19 @@ export class Crawler extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-queue a URL the project lists as unfinished internal work. A crawl
|
||||
* from before external pages stopped recording their links left rows
|
||||
* that point at the external site's own pages as "internal"; those are
|
||||
* checked once when external links are checked, and skipped otherwise.
|
||||
*/
|
||||
private enqueuePending(p: { url: string; depth: number }): void {
|
||||
const foreign = this.isForeignHost(p.url);
|
||||
if (foreign && !this.config.crawlExternal) return;
|
||||
this.seen.delete(p.url);
|
||||
this.enqueue({ url: p.url, depth: p.depth, checkOnly: foreign });
|
||||
}
|
||||
|
||||
private enqueueExternal(url: string): void {
|
||||
if (this.stopped) return;
|
||||
if (this.externalSeen.has(url)) return;
|
||||
@@ -3881,6 +3908,7 @@ export class Crawler extends EventEmitter {
|
||||
url: item.url,
|
||||
urlMalformed: isUrlMalformed(item.url) ? 1 : 0,
|
||||
urlTrap: this.trapKind(item.url),
|
||||
isExternal: this.isForeignHost(item.url),
|
||||
// Never fetched, so the extension is all there is to go on. A
|
||||
// flat 'html' put blocked scripts, styles and images in the HTML
|
||||
// / Non-Indexable counts (40 of 58 robots-blocked URLs on one
|
||||
@@ -4341,6 +4369,17 @@ export class Crawler extends EventEmitter {
|
||||
// are bounded by ~concurrency / maxRps, so Stop stays responsive.
|
||||
await this.acquireRateSlot();
|
||||
if (this.stopped) return;
|
||||
// Pause arrived while this task waited for its rate slot. Slots are
|
||||
// spaced 1 / maxRps apart, so at 2 rps and concurrency 20 twenty tasks
|
||||
// sit here, none in flight: pause()'s abort cannot reach them and they
|
||||
// kept fetching for ~10 s after Pause. Park the URL in the paused
|
||||
// queue, as an aborted in-flight fetch is.
|
||||
if (this.paused) {
|
||||
this.queue
|
||||
.add(() => this.fetchAndProcess(item), { priority: Crawler.priorityFor(item) })
|
||||
.catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
// A retry of a URL that failed earlier (blocked, or no response): it is
|
||||
// failed again only if it fails again.
|
||||
if (this.pendingFailedUrls.delete(item.url)) this.failed--;
|
||||
@@ -4413,6 +4452,7 @@ export class Crawler extends EventEmitter {
|
||||
url: item.url,
|
||||
urlMalformed: isUrlMalformed(item.url) ? 1 : 0,
|
||||
urlTrap: this.trapKind(item.url),
|
||||
isExternal: this.isForeignHost(item.url),
|
||||
contentKind: 'other',
|
||||
statusCode: res.status,
|
||||
statusText: 'size-cap-exceeded',
|
||||
@@ -4505,6 +4545,7 @@ export class Crawler extends EventEmitter {
|
||||
url: item.url,
|
||||
urlMalformed: isUrlMalformed(item.url) ? 1 : 0,
|
||||
urlTrap: this.trapKind(item.url),
|
||||
isExternal: this.isForeignHost(item.url),
|
||||
// The challenge page is HTML whatever the URL was; classify by
|
||||
// the URL, as the robots-blocked path does.
|
||||
contentKind: detectContentKind(item.url, null),
|
||||
@@ -4664,6 +4705,7 @@ export class Crawler extends EventEmitter {
|
||||
url: item.url,
|
||||
urlMalformed: isUrlMalformed(item.url) ? 1 : 0,
|
||||
urlTrap: this.trapKind(item.url),
|
||||
isExternal: this.isForeignHost(item.url),
|
||||
contentKind: kind,
|
||||
statusCode,
|
||||
statusText: null,
|
||||
@@ -4713,12 +4755,19 @@ export class Crawler extends EventEmitter {
|
||||
);
|
||||
return;
|
||||
}
|
||||
const inScope = isInScope(this.config.startUrl, target, this.config.scope);
|
||||
if (inScope || this.config.crawlExternal) {
|
||||
this.enqueue({ url: target, depth: item.depth, redirectHopCount: hopCount });
|
||||
} else if (!inScope) {
|
||||
// Record the target as an external stub so the hop chain is
|
||||
// visible in Outlinks even when we won't follow it.
|
||||
// An off-site hop is checked, not crawled through, whichever
|
||||
// route reached it — wa.me → api.whatsapp.com included.
|
||||
const admit = this.admitTarget(target);
|
||||
if (admit) {
|
||||
this.enqueue({
|
||||
url: target,
|
||||
depth: item.depth,
|
||||
redirectHopCount: hopCount,
|
||||
checkOnly: admit === 'check',
|
||||
});
|
||||
} else {
|
||||
// Out of scope and not checked: record the target as an
|
||||
// external stub so the hop chain is visible in Outlinks.
|
||||
this.enqueueExternal(target);
|
||||
}
|
||||
}
|
||||
@@ -4749,12 +4798,27 @@ export class Crawler extends EventEmitter {
|
||||
// discard the stream without buffering megabytes into memory — this is
|
||||
// what makes "Check Images / CSS / JS" resource crawling lightweight.
|
||||
let nonHtmlBody = '';
|
||||
let contentLength = parseIntSafe(contentLengthHeader);
|
||||
if (needsJsonExtraction || needsCssParse) {
|
||||
try {
|
||||
nonHtmlBody = await res.text();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
if (contentLength === null && nonHtmlBody) contentLength = Buffer.byteLength(nonHtmlBody);
|
||||
} else if (
|
||||
contentLength === null &&
|
||||
statusCode >= 200 &&
|
||||
statusCode < 300 &&
|
||||
SIZED_RESOURCE_KINDS.has(kind) &&
|
||||
// Not for a resource whose row isn't stored (below): nothing
|
||||
// would record the number.
|
||||
!(item.resourceRow && !this.storesResourceRow(item.resourceRow))
|
||||
) {
|
||||
// No Content-Length (chunked): an image row with an empty size
|
||||
// leaves every image-weight check blind, so count the bytes as
|
||||
// they stream past instead of dropping them unmeasured.
|
||||
contentLength = await countBodyBytes(res, effectiveBodyCap(this.config.maxFileSizeBytes));
|
||||
} else {
|
||||
try {
|
||||
await res.body?.cancel();
|
||||
@@ -4798,6 +4862,7 @@ export class Crawler extends EventEmitter {
|
||||
url: item.url,
|
||||
urlMalformed: isUrlMalformed(item.url) ? 1 : 0,
|
||||
urlTrap: this.trapKind(item.url),
|
||||
isExternal: this.isForeignHost(item.url),
|
||||
contentKind: kind,
|
||||
statusCode,
|
||||
statusText: null,
|
||||
@@ -4805,7 +4870,7 @@ export class Crawler extends EventEmitter {
|
||||
indexabilityReason: indexability === 'indexable' ? null : `HTTP ${statusCode}`,
|
||||
contentType,
|
||||
extractionResults: jsonExtraction ? JSON.stringify(jsonExtraction) : null,
|
||||
contentLength: parseIntSafe(contentLengthHeader),
|
||||
contentLength,
|
||||
xRobotsTag,
|
||||
responseTimeMs,
|
||||
ttfbMs,
|
||||
@@ -4857,6 +4922,7 @@ export class Crawler extends EventEmitter {
|
||||
url: item.url,
|
||||
urlMalformed: isUrlMalformed(item.url) ? 1 : 0,
|
||||
urlTrap: this.trapKind(item.url),
|
||||
isExternal: this.isForeignHost(item.url),
|
||||
contentKind: 'other',
|
||||
statusCode,
|
||||
statusText: 'size-cap-exceeded',
|
||||
@@ -4996,6 +5062,7 @@ export class Crawler extends EventEmitter {
|
||||
url: item.url,
|
||||
urlMalformed: isUrlMalformed(item.url) ? 1 : 0,
|
||||
urlTrap: this.trapKind(item.url),
|
||||
isExternal: this.isForeignHost(item.url),
|
||||
contentKind: detectContentKind(item.url, null),
|
||||
statusCode: null,
|
||||
statusText: challenge,
|
||||
@@ -5151,12 +5218,21 @@ export class Crawler extends EventEmitter {
|
||||
// Before the write, so a page that completes a calendar trap is
|
||||
// itself stored with the trap flag.
|
||||
if (statusCode >= 200 && statusCode < 300) this.observeCalendarPage(item.url, parsed.simhash);
|
||||
// An external page fetched by "Check External Links" keeps its own
|
||||
// row (status, title, response time) but records nothing it points
|
||||
// at. Its links were classified against ITS host, so stored they'd
|
||||
// turn Instagram's pages into "internal" link targets (which the
|
||||
// end-of-crawl drain then crawls), its images into site images, its
|
||||
// og:image into a probe. The empty lists are written as "has none",
|
||||
// which also clears what an earlier crawl stored for it.
|
||||
const foreignPage = this.isForeignHost(item.url);
|
||||
this.setOp(`crawl:write:${item.url}`);
|
||||
const { urlId } = await this.writeFetchedUrl({
|
||||
upsert: {
|
||||
url: item.url,
|
||||
urlMalformed: isUrlMalformed(item.url) ? 1 : 0,
|
||||
urlTrap: this.trapKind(item.url),
|
||||
isExternal: this.isForeignHost(item.url),
|
||||
contentKind: 'html',
|
||||
statusCode,
|
||||
statusText: null,
|
||||
@@ -5344,24 +5420,26 @@ export class Crawler extends EventEmitter {
|
||||
: 1_048_576,
|
||||
}
|
||||
: null,
|
||||
links: persistedLinks,
|
||||
images: this.config.storeImages ? parsed.images : [],
|
||||
socialImages: parsed.socialImages,
|
||||
links: foreignPage ? [] : persistedLinks,
|
||||
images: !foreignPage && this.config.storeImages ? parsed.images : [],
|
||||
socialImages: foreignPage ? [] : parsed.socialImages,
|
||||
// Whether the empty lists above mean "this page has none"
|
||||
// (storage on → the writer replaces the page's rows) or "not
|
||||
// recording" (storage off → it keeps what an earlier crawl stored).
|
||||
storeLinks:
|
||||
foreignPage ||
|
||||
storeInternalLinks ||
|
||||
storeExternalLinks ||
|
||||
this.config.storeIframes ||
|
||||
this.config.crawlInvalidLinks,
|
||||
storeImages: this.config.storeImages,
|
||||
storeImages: foreignPage || this.config.storeImages,
|
||||
// Lets a script / stylesheet / font row list the pages that embed
|
||||
// it under Inlinks.
|
||||
resources: parsed.resources,
|
||||
resources: foreignPage ? [] : parsed.resources,
|
||||
// Recorded for Outlinks / the bulk export only — never queued.
|
||||
uncrawlableLinks: this.config.storeUncrawlableLinks ? parsed.uncrawlableLinks : [],
|
||||
storeUncrawlableLinks: this.config.storeUncrawlableLinks ?? true,
|
||||
uncrawlableLinks:
|
||||
!foreignPage && this.config.storeUncrawlableLinks ? parsed.uncrawlableLinks : [],
|
||||
storeUncrawlableLinks: foreignPage || (this.config.storeUncrawlableLinks ?? true),
|
||||
fromDepth: item.depth,
|
||||
});
|
||||
// V2 Faz 1 — Persist render artefacts inline so they finish before
|
||||
@@ -5421,13 +5499,19 @@ export class Crawler extends EventEmitter {
|
||||
// Outlinks tab; they're just not fetched as their own URL rows here.
|
||||
const fixedUrlMode =
|
||||
this.config.mode === 'list' || this.config.mode === 'sitemap';
|
||||
if (!fixedUrlMode) {
|
||||
if (!fixedUrlMode && !foreignPage) {
|
||||
for (const link of storableLinks) {
|
||||
if (!link.isInternal && !link.followExcluded) this.enqueueExternal(link.toUrl);
|
||||
}
|
||||
}
|
||||
this.crawled++;
|
||||
|
||||
// A page on another host was fetched to check the link that pointed
|
||||
// at it. Its links, assets and alternates belong to that other site:
|
||||
// queueing them is how one Instagram link became thousands of
|
||||
// Instagram pages, listed as internal.
|
||||
if (foreignPage) return;
|
||||
|
||||
// Subresource crawling — fetch internal images / CSS / JS referenced by
|
||||
// this page so they appear in the Internal tab with their own status
|
||||
// code, content type, and size (Screaming Frog "Check Images/CSS/JS").
|
||||
@@ -5455,22 +5539,21 @@ export class Crawler extends EventEmitter {
|
||||
// a URL pulled in only to check its status (see `checkOnly`).
|
||||
} else {
|
||||
const nextDepth = item.depth + 1;
|
||||
// Every discovery route below admits its targets the same way:
|
||||
// in scope → crawled, out of scope → at most checked once (see
|
||||
// `admitTarget`).
|
||||
const enqueueTarget = (target: string | null): void => {
|
||||
if (!target || target === item.url) return;
|
||||
const admit = this.admitTarget(target);
|
||||
if (admit) this.enqueue({ url: target, depth: nextDepth, checkOnly: admit === 'check' });
|
||||
};
|
||||
// Spider → Crawl "Internal Hyperlinks / Crawl". Off leaves every
|
||||
// other discovery route (sitemaps, canonicals, pagination) intact,
|
||||
// so it audits a fixed set of pages without spidering outward.
|
||||
if (this.config.crawlInternalLinks) {
|
||||
for (const link of storableLinks) {
|
||||
const inScope = isInScope(this.config.startUrl, link.toUrl, this.config.scope);
|
||||
// With `scope: 'subfolder'`, "Check Links Outside of Start
|
||||
// Folder" fetches out-of-folder targets once so their status
|
||||
// is known, then stops — Screaming Frog draws the same line
|
||||
// between checking a link and crawling through it.
|
||||
const checkOnly =
|
||||
!inScope &&
|
||||
this.config.scope === 'subfolder' &&
|
||||
this.config.checkLinksOutsideStartFolder &&
|
||||
isInScope(this.config.startUrl, link.toUrl, 'subdomain');
|
||||
if (!inScope && !checkOnly && !this.config.crawlExternal) continue;
|
||||
const admit = this.admitTarget(link.toUrl);
|
||||
if (!admit) continue;
|
||||
// Settings → Filters "Don't follow links in": the link is kept in
|
||||
// the graph, it just doesn't lead the crawl anywhere.
|
||||
if (link.followExcluded) continue;
|
||||
@@ -5488,19 +5571,15 @@ export class Crawler extends EventEmitter {
|
||||
: this.config.followExternalNofollow;
|
||||
if (!followThis) continue;
|
||||
}
|
||||
this.enqueue({ url: link.toUrl, depth: nextDepth, checkOnly });
|
||||
this.enqueue({ url: link.toUrl, depth: nextDepth, checkOnly: admit === 'check' });
|
||||
}
|
||||
}
|
||||
// Wave 3 — Pagination follow toggle. rel=next/prev are part of
|
||||
// the standard discovery graph; the toggle exists to debug
|
||||
// pagination-only loops without disabling all link follow.
|
||||
if (this.config.followPaginationLinks) {
|
||||
for (const target of [parsed.paginationNext, parsed.paginationPrev]) {
|
||||
if (!target) continue;
|
||||
const inScope = isInScope(this.config.startUrl, target, this.config.scope);
|
||||
if (!inScope && !this.config.crawlExternal) continue;
|
||||
this.enqueue({ url: target, depth: nextDepth });
|
||||
}
|
||||
enqueueTarget(parsed.paginationNext);
|
||||
enqueueTarget(parsed.paginationPrev);
|
||||
}
|
||||
// Bölüm 29 — SPA routes discovered during JS render. The app
|
||||
// reached these itself (pushState / hash change) or links to
|
||||
@@ -5509,15 +5588,7 @@ export class Crawler extends EventEmitter {
|
||||
// request the crawler could see.
|
||||
if (renderSpaRoutes.length > 0) {
|
||||
for (const route of renderSpaRoutes) {
|
||||
const normalized = normalizeUrl(route, item.url, this.urlRewrites);
|
||||
if (!normalized || normalized === item.url) continue;
|
||||
const inScope = isInScope(
|
||||
this.config.startUrl,
|
||||
normalized,
|
||||
this.config.scope,
|
||||
);
|
||||
if (!inScope && !this.config.crawlExternal) continue;
|
||||
this.enqueue({ url: normalized, depth: nextDepth });
|
||||
enqueueTarget(normalizeUrl(route, item.url, this.urlRewrites));
|
||||
}
|
||||
}
|
||||
// Wave 3 — Canonical follow toggle. When on, a 200 page that
|
||||
@@ -5532,42 +5603,24 @@ export class Crawler extends EventEmitter {
|
||||
// Resolved, not raw: a relative canonical passed verbatim to
|
||||
// isInScope/enqueue is not a URL and would either be dropped or
|
||||
// fetched against the wrong base.
|
||||
const inScope = isInScope(
|
||||
this.config.startUrl,
|
||||
parsed.canonicalResolved,
|
||||
this.config.scope,
|
||||
);
|
||||
if (inScope || this.config.crawlExternal) {
|
||||
this.enqueue({ url: parsed.canonicalResolved, depth: nextDepth });
|
||||
}
|
||||
enqueueTarget(parsed.canonicalResolved);
|
||||
}
|
||||
// Wave 3 — JS-style redirect follow: `<meta http-equiv="refresh">`
|
||||
// content URLs and `window.location = "…"`-style statements the
|
||||
// parser could resolve statically (literal targets only).
|
||||
if (this.config.followJsRedirects) {
|
||||
for (const target of [parsed.metaRefreshUrl, parsed.jsRedirectUrl]) {
|
||||
if (!target || target === item.url) continue;
|
||||
const inScope = isInScope(this.config.startUrl, target, this.config.scope);
|
||||
if (inScope || this.config.crawlExternal) {
|
||||
this.enqueue({ url: target, depth: nextDepth });
|
||||
}
|
||||
}
|
||||
enqueueTarget(parsed.metaRefreshUrl);
|
||||
enqueueTarget(parsed.jsRedirectUrl);
|
||||
}
|
||||
// Spider → Crawl rows that only add discovery. Each one enqueues a
|
||||
// declared alternate — a translated page, an AMP variant, an m-dot
|
||||
// URL — that an ordinary hyperlink often never points at, which is
|
||||
// exactly why they go uncrawled without an explicit opt-in.
|
||||
const followDeclared = (target: string | null): void => {
|
||||
if (!target || target === item.url) return;
|
||||
const inScope = isInScope(this.config.startUrl, target, this.config.scope);
|
||||
if (!inScope && !this.config.crawlExternal) return;
|
||||
this.enqueue({ url: target, depth: nextDepth });
|
||||
};
|
||||
if (this.config.crawlHreflang) {
|
||||
for (const h of parsed.hreflangs) followDeclared(h.href);
|
||||
for (const h of parsed.hreflangs) enqueueTarget(h.href);
|
||||
}
|
||||
if (this.config.crawlAmp) followDeclared(parsed.amphtml);
|
||||
if (this.config.crawlMobileAlternate) followDeclared(parsed.mobileAlternate);
|
||||
if (this.config.crawlAmp) enqueueTarget(parsed.amphtml);
|
||||
if (this.config.crawlMobileAlternate) enqueueTarget(parsed.mobileAlternate);
|
||||
}
|
||||
} catch (err) {
|
||||
// Stop / Clear: abandon silently. No row is written, no failure
|
||||
@@ -5611,6 +5664,7 @@ export class Crawler extends EventEmitter {
|
||||
url: item.url,
|
||||
urlMalformed: isUrlMalformed(item.url) ? 1 : 0,
|
||||
urlTrap: this.trapKind(item.url),
|
||||
isExternal: this.isForeignHost(item.url),
|
||||
// Nothing came back, so the kind comes from the URL: a failed
|
||||
// `.webp` stays an image instead of appearing among HTML pages.
|
||||
contentKind: detectContentKind(item.url, null),
|
||||
@@ -5690,6 +5744,44 @@ export class Crawler extends EventEmitter {
|
||||
{ challenge: DigestChallenge; nc: number }
|
||||
>();
|
||||
|
||||
/**
|
||||
* True when `url` is on a host this crawl doesn't own — the same line the
|
||||
* parser draws for a link found on one of the site's own pages (the start
|
||||
* host, its registrable domain under `all-subdomains`, configured CDN
|
||||
* hosts). Such a page is a link target being checked, not part of the
|
||||
* site: its row is external and nothing it links to is discovered.
|
||||
*
|
||||
* Spider mode only. List and sitemap rows have no single start host to
|
||||
* measure against and keep their default classification.
|
||||
*/
|
||||
private isForeignHost(url: string): boolean {
|
||||
if (this.config.mode === 'list' || this.config.mode === 'sitemap') return false;
|
||||
return !isSameHost(this.config.startUrl, url, {
|
||||
includeSubdomains: this.config.scope === 'all-subdomains',
|
||||
cdnHosts: this.config.cdnHosts,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* How a URL found on a crawled page joins the crawl:
|
||||
* - `'follow'`: in scope; fetch it and follow its links.
|
||||
* - `'check'`: out of scope, but the matching option wants its status
|
||||
* ("Check Links Outside of Start Folder" for the start host's other
|
||||
* folders, "Check External Links" for everything else). Fetched once;
|
||||
* nothing it links to is followed. Screaming Frog draws the same line,
|
||||
* so a link to Instagram is checked, not spidered.
|
||||
* - `null`: leave it alone.
|
||||
*/
|
||||
private admitTarget(url: string): 'follow' | 'check' | null {
|
||||
const { startUrl, scope } = this.config;
|
||||
if (isInScope(startUrl, url, scope)) return 'follow';
|
||||
const otherFolder = scope === 'subfolder' && isInScope(startUrl, url, 'subdomain');
|
||||
const check = otherFolder
|
||||
? this.config.checkLinksOutsideStartFolder
|
||||
: this.config.crawlExternal;
|
||||
return check ? 'check' : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The URLs this crawl's HTTP auth + custom headers belong to: what the
|
||||
* user typed (start URL, or every listed URL in List mode), captured in
|
||||
@@ -6508,6 +6600,47 @@ function effectiveBodyCap(configured: number): number {
|
||||
return configured > 0 ? configured : ABSOLUTE_BODY_CAP_BYTES;
|
||||
}
|
||||
|
||||
/**
|
||||
* Size of a response body that came without a Content-Length (chunked
|
||||
* transfer; Cloudflare serves images this way, on HEAD too), measured by
|
||||
* streaming it through and keeping none of it. Null when the stream fails
|
||||
* or runs past `capBytes`: an unknown size, never a guessed one.
|
||||
*/
|
||||
async function countBodyBytes(res: { body: unknown }, capBytes: number): Promise<number | null> {
|
||||
const body = res.body as ReadableStream<Uint8Array> | null;
|
||||
if (!body) return null;
|
||||
const reader = body.getReader();
|
||||
let total = 0;
|
||||
try {
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) return total;
|
||||
if (!value) continue;
|
||||
total += value.byteLength;
|
||||
if (total > capBytes) {
|
||||
await reader.cancel().catch(() => undefined);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
try {
|
||||
reader.releaseLock();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Resource kinds whose byte size feeds a check (image weight, page weight). */
|
||||
const SIZED_RESOURCE_KINDS: ReadonlySet<ContentKind> = new Set<ContentKind>([
|
||||
'image',
|
||||
'css',
|
||||
'js',
|
||||
'font',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Read a fetch Response body as raw bytes with a hard byte cap. undici streams
|
||||
* the DECODED body (content-encoding already stripped), so this bounds the
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
export { ProjectDb, EXPENSIVE_ISSUE_DEFINITIONS, SOFT404_PROBE_META_KEY } from './project-db.js';
|
||||
export {
|
||||
ProjectDb,
|
||||
EXPENSIVE_ISSUE_DEFINITIONS,
|
||||
SOFT404_PROBE_META_KEY,
|
||||
resolveUrlCategory,
|
||||
} from './project-db.js';
|
||||
export type { UpsertUrlInput, ProbeWrite } from './project-db.js';
|
||||
export { runMigrations, LATEST_SCHEMA_VERSION, type MigrationProgress } from './migrations.js';
|
||||
export {
|
||||
|
||||
@@ -74,6 +74,7 @@ import {
|
||||
ISSUE_COUNT_KEY,
|
||||
ISSUE_GROUPS,
|
||||
issueCount,
|
||||
issueCategoryForCounter,
|
||||
type CompareCategory,
|
||||
type CompareDiffRow,
|
||||
type IssueCountDelta,
|
||||
@@ -463,6 +464,13 @@ export interface QueueCheckpointPatch {
|
||||
|
||||
export interface UpsertUrlInput {
|
||||
url: string;
|
||||
/**
|
||||
* The URL is on a host the crawl doesn't own (an external link fetched
|
||||
* by "Check External Links", or a redirect hop off-site). Only ever
|
||||
* raises the flag: a row already known as external stays external when
|
||||
* a caller leaves this out.
|
||||
*/
|
||||
isExternal?: boolean;
|
||||
contentKind?: ContentKind;
|
||||
statusCode?: number | null;
|
||||
statusText?: string | null;
|
||||
@@ -690,7 +698,7 @@ const CHANGED_FLAG_SQL = `CASE
|
||||
|
||||
const UPSERT_URL_SQL = `
|
||||
INSERT INTO urls (
|
||||
url, content_kind, status_code, status_text, indexability, indexability_reason,
|
||||
url, is_external, content_kind, status_code, status_text, indexability, indexability_reason,
|
||||
title, title_length, meta_description, meta_description_length,
|
||||
h1, h1_length, h1_count, h2_count, h3_count, h4_count, h5_count, h6_count,
|
||||
word_count, canonical, canonical_resolved, canonical_distinct_count,
|
||||
@@ -735,7 +743,7 @@ const UPSERT_URL_SQL = `
|
||||
http_charset, meta_charset, canonical_outside_head, content_lang, lang_mismatch,
|
||||
soft_404, js_noindex, js_title_changed, js_title, minhash, hreflang_outside_head
|
||||
) VALUES (
|
||||
:url, :content_kind, :status_code, :status_text, :indexability, :indexability_reason,
|
||||
:url, :is_external, :content_kind, :status_code, :status_text, :indexability, :indexability_reason,
|
||||
:title, :title_length, :meta_description, :meta_description_length,
|
||||
:h1, :h1_length, :h1_count, :h2_count, :h3_count, :h4_count, :h5_count, :h6_count,
|
||||
:word_count, :canonical, :canonical_resolved, :canonical_distinct_count,
|
||||
@@ -781,6 +789,9 @@ const UPSERT_URL_SQL = `
|
||||
:soft_404, :js_noindex, :js_title_changed, :js_title, :minhash, :hreflang_outside_head
|
||||
)
|
||||
ON CONFLICT(url) DO UPDATE SET
|
||||
-- MAX, not a plain assignment: the external-link stub (inserted with 1)
|
||||
-- is updated by writers that don't say, and must not drop to internal.
|
||||
is_external = MAX(urls.is_external, excluded.is_external),
|
||||
content_kind = excluded.content_kind,
|
||||
status_code = excluded.status_code,
|
||||
status_text = excluded.status_text,
|
||||
@@ -1150,6 +1161,16 @@ const DUPLICATE_ALT_PREDICATE = `is_variant = 0 AND alt IS NOT NULL AND alt != '
|
||||
GROUP BY alt HAVING COUNT(*) > 1
|
||||
)`;
|
||||
|
||||
/**
|
||||
* The Images size filter: any given number (0 included) means "known size
|
||||
* of at least this many bytes", so `0` lists the measured rows only. The
|
||||
* UI sends `undefined` for an empty box. `minByteSize: 0` used to apply no
|
||||
* filter at all and still count the unknown sizes.
|
||||
*/
|
||||
function minByteFilter(raw: number | undefined): number | null {
|
||||
return typeof raw === 'number' && Number.isFinite(raw) ? Math.max(0, Math.floor(raw)) : null;
|
||||
}
|
||||
|
||||
// Per-usage duplicate-alt: a usage whose alt text is also carried by a
|
||||
// DIFFERENT image somewhere on the site. Operates on `image_usages.alt` to
|
||||
// match the per-usage Images view. `COUNT(DISTINCT image_id)`, not
|
||||
@@ -2703,6 +2724,7 @@ export class ProjectDb {
|
||||
upsertUrl(input: UpsertUrlInput): number {
|
||||
const params = {
|
||||
url: input.url,
|
||||
is_external: input.isExternal ? 1 : 0,
|
||||
content_kind: input.contentKind ?? 'html',
|
||||
status_code: input.statusCode ?? null,
|
||||
status_text: input.statusText ?? null,
|
||||
@@ -6736,7 +6758,7 @@ export class ProjectDb {
|
||||
// Sorting is done here, not in the renderer: the tab loads one page of
|
||||
// rows, and ordering that page client-side only ever sorted whichever
|
||||
// 5 000 rows the default order happened to return first.
|
||||
const minBytes = Math.max(0, Math.floor(params.minByteSize ?? 0));
|
||||
const minBytes = minByteFilter(params.minByteSize);
|
||||
if (this.hasImageUsages()) {
|
||||
const where: string[] = [];
|
||||
const args: (string | number)[] = [];
|
||||
@@ -6752,7 +6774,7 @@ export class ProjectDb {
|
||||
}
|
||||
// The size filter has to see the same expression the SELECT exposes,
|
||||
// so both the count and the page agree on which rows qualify.
|
||||
if (minBytes > 0) {
|
||||
if (minBytes !== null) {
|
||||
where.push(`${IMAGE_BYTE_SIZE_SQL} >= ?`);
|
||||
args.push(minBytes);
|
||||
}
|
||||
@@ -6772,7 +6794,7 @@ export class ProjectDb {
|
||||
.prepare(
|
||||
`SELECT i.id, i.src, iu.alt AS alt, i.width, i.height, i.is_internal,
|
||||
i.occurrences, u.url AS from_url, iu.from_url_id AS from_url_id,
|
||||
${IMAGE_BYTE_SIZE_SQL} AS byte_size
|
||||
${IMAGE_BYTE_SIZE_SQL} AS byte_size, iu.is_variant AS is_variant
|
||||
FROM image_usages iu
|
||||
JOIN images i ON iu.image_id = i.id
|
||||
LEFT JOIN urls u ON iu.from_url_id = u.id
|
||||
@@ -6784,6 +6806,7 @@ export class ProjectDb {
|
||||
.all(...args, params.limit, params.offset) as unknown as (ImageRowDb & {
|
||||
from_url: string | null;
|
||||
from_url_id: number | null;
|
||||
is_variant: number | null;
|
||||
})[];
|
||||
return {
|
||||
total,
|
||||
@@ -6798,6 +6821,7 @@ export class ProjectDb {
|
||||
fromUrl: r.from_url ?? null,
|
||||
fromUrlId: r.from_url_id ?? null,
|
||||
byteSize: r.byte_size ?? null,
|
||||
isVariant: r.is_variant === 1,
|
||||
})),
|
||||
};
|
||||
}
|
||||
@@ -6817,7 +6841,7 @@ export class ProjectDb {
|
||||
const like = `%${params.search}%`;
|
||||
args.push(like, like);
|
||||
}
|
||||
if (minBytes > 0) {
|
||||
if (minBytes !== null) {
|
||||
where.push(`${IMAGE_BYTE_SIZE_SQL} >= ?`);
|
||||
args.push(minBytes);
|
||||
}
|
||||
@@ -8691,7 +8715,7 @@ export class ProjectDb {
|
||||
} = {}): IterableIterator<ImageRow> {
|
||||
const where: string[] = [];
|
||||
const args: (string | number)[] = [];
|
||||
const minBytes = Math.max(0, Math.floor(options.minByteSize ?? 0));
|
||||
const minBytes = minByteFilter(options.minByteSize);
|
||||
// Per-usage export to match the per-usage Images tab (one row per page).
|
||||
if (this.hasImageUsages()) {
|
||||
if (options.missingAltOnly) where.push('iu.alt IS NULL AND iu.is_variant = 0');
|
||||
@@ -8703,7 +8727,7 @@ export class ProjectDb {
|
||||
const like = `%${options.search}%`;
|
||||
args.push(like, like);
|
||||
}
|
||||
if (minBytes > 0) {
|
||||
if (minBytes !== null) {
|
||||
where.push(`${IMAGE_BYTE_SIZE_SQL} >= ?`);
|
||||
args.push(minBytes);
|
||||
}
|
||||
@@ -8753,7 +8777,7 @@ export class ProjectDb {
|
||||
const like = `%${options.search}%`;
|
||||
args.push(like, like);
|
||||
}
|
||||
if (minBytes > 0) {
|
||||
if (minBytes !== null) {
|
||||
where.push(`${IMAGE_BYTE_SIZE_SQL} >= ?`);
|
||||
args.push(minBytes);
|
||||
}
|
||||
@@ -11749,6 +11773,29 @@ function buildClauseSql(c: FilterClause, args: (string | number)[]): string | nu
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A `category` argument from outside the app (MCP server, assistant tools)
|
||||
* as a filter `queryUrls` understands. An unknown string would fall through
|
||||
* `categoryWhereClause` to "no clause" and return the whole crawl under the
|
||||
* label asked for, so it is refused instead. A sidebar counter name
|
||||
* (`issues:h1Missing` or `h1Missing`, as `getOverviewCounts` names them) is
|
||||
* accepted as its category.
|
||||
*/
|
||||
export function resolveUrlCategory(raw: unknown): UrlCategory {
|
||||
if (raw === undefined || raw === null || raw === '') return 'all';
|
||||
if (typeof raw !== 'string') throw new Error('`category` must be a string.');
|
||||
const name = raw.trim();
|
||||
if (name === 'all' || categoryWhereClause(name as UrlCategory) !== null) {
|
||||
return name as UrlCategory;
|
||||
}
|
||||
const viaCounter = issueCategoryForCounter(name);
|
||||
if (viaCounter) return viaCounter;
|
||||
throw new Error(
|
||||
`Unknown category "${raw}". Pass a category from top_issues (e.g. "issues:h1-missing"), ` +
|
||||
'or one of "all", "internal:html", "external:all", "status:4xx", "indexability:non-indexable".',
|
||||
);
|
||||
}
|
||||
|
||||
export function categoryWhereClause(
|
||||
cat: UrlCategory,
|
||||
/** Silenced issue checks (Settings → Issues): their filter matches nothing. */
|
||||
@@ -12410,6 +12457,14 @@ export function categoryWhereClause(
|
||||
return `is_external = 0 AND content_kind = 'html'
|
||||
AND id IN (SELECT from_url_id FROM image_usages
|
||||
WHERE has_title = 0 AND is_variant = 0)`;
|
||||
case 'issues:image-duplicate-alt':
|
||||
// Pages using at least one image whose alt text a different image
|
||||
// also carries (the Images tab lists the individual uses). Without
|
||||
// a clause the bulk export wrote every URL into
|
||||
// image-duplicate-alt.csv and query_urls could not filter by it.
|
||||
return `is_external = 0 AND content_kind = 'html'
|
||||
AND id IN (SELECT iu.from_url_id FROM image_usages iu
|
||||
WHERE ${USAGE_DUPLICATE_ALT_PREDICATE})`;
|
||||
case 'issues:hreflang-self-only':
|
||||
// Every hreflang annotation on the page is the page itself.
|
||||
return "is_external = 0 AND content_kind = 'html' AND hreflang_self_only = 1";
|
||||
|
||||
@@ -2512,6 +2512,10 @@ export interface ImageRow {
|
||||
* `content_length` when the image was fetched as its own URL. Null when
|
||||
* neither ran — "unknown", never "zero". */
|
||||
byteSize: number | null;
|
||||
/** A srcset / `<picture>` candidate rather than the `<img src>` itself.
|
||||
* Variants are neither fetched nor size-probed unless Settings › srcset
|
||||
* Variants is on, so their `byteSize` is normally null. */
|
||||
isVariant?: boolean;
|
||||
}
|
||||
|
||||
/** Columns the Images tab can order by. Sorting happens in SQL so the
|
||||
|
||||
@@ -410,6 +410,70 @@ export function issueCount(issues: OverviewCounts['issues'], def: IssueCheckDef)
|
||||
: def.count.reduce((acc, k) => acc + (issues[k] ?? 0), 0);
|
||||
}
|
||||
|
||||
/** Counter name (`h1Missing`) → the `issues:*` category it counts. */
|
||||
const CATEGORY_BY_COUNTER: ReadonlyMap<string, UrlCategory> = new Map(
|
||||
[...ISSUE_COUNT_KEY].map(([category, key]) => [key, category] as const),
|
||||
);
|
||||
|
||||
/**
|
||||
* The category behind a sidebar counter name — `h1Missing`, or the
|
||||
* `issues:h1Missing` form agents build from `OverviewCounts.issues` — or
|
||||
* null when the name is no counter.
|
||||
*/
|
||||
export function issueCategoryForCounter(name: string): UrlCategory | null {
|
||||
const key = name.startsWith('issues:') ? name.slice('issues:'.length) : name;
|
||||
return CATEGORY_BY_COUNTER.get(key) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What an issue counter counts, which decides where its rows are listed:
|
||||
* `urls` → the URL query for its category; `images` → image usages (the
|
||||
* category lists the pages carrying them); `links` → link rows, served by
|
||||
* the broken-links listing rather than the URL table.
|
||||
*/
|
||||
export type IssueCountUnit = 'urls' | 'images' | 'links';
|
||||
|
||||
/** One non-empty issue check, as the agent-facing `top_issues` lists it. */
|
||||
export interface RankedIssue {
|
||||
/** Filter category for the URL query — never a counter name. */
|
||||
category: UrlCategory;
|
||||
/** English sidebar path, e.g. "H1 › Missing". */
|
||||
label: string;
|
||||
count: number;
|
||||
unit: IssueCountUnit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Non-empty, enabled issue checks, biggest first. Built from the catalog
|
||||
* so each entry carries its filter category: ranking the raw
|
||||
* `OverviewCounts.issues` fields handed out counter names
|
||||
* (`issues:h1Missing`) that no filter knows.
|
||||
*/
|
||||
export function rankIssues(
|
||||
issues: OverviewCounts['issues'],
|
||||
disabled: ReadonlySet<string> = new Set(),
|
||||
): RankedIssue[] {
|
||||
const ranked: RankedIssue[] = [];
|
||||
for (const group of ISSUE_GROUPS) {
|
||||
for (const def of group.items) {
|
||||
if (disabled.has(def.category)) continue;
|
||||
const count = issueCount(issues, def);
|
||||
if (count === null || !(count > 0)) continue;
|
||||
ranked.push({
|
||||
category: def.category,
|
||||
label: `${group.label} › ${def.label}`,
|
||||
count,
|
||||
unit: def.category.startsWith('issues:broken-links-')
|
||||
? 'links'
|
||||
: def.percentBase === 'images'
|
||||
? 'images'
|
||||
: 'urls',
|
||||
});
|
||||
}
|
||||
}
|
||||
return ranked.sort((a, b) => b.count - a.count);
|
||||
}
|
||||
|
||||
/** Every toggleable issue category, in sidebar order. */
|
||||
export const ISSUE_CATEGORIES: readonly UrlCategory[] = ISSUE_GROUPS.flatMap((g) =>
|
||||
g.items.map((i) => i.category),
|
||||
|
||||
Reference in new issue
Block a user