@a2f0/agent-tool 0.1.70 → 0.1.72
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/package.json +1 -1
- package/skills/seo-optimization/SKILL.md +6 -3
- package/src/cli.ts +1 -21
- package/src/config.ts +1 -8
- package/src/permissions/catalog.ts +3 -5
- package/src/seo/address.ts +117 -0
- package/src/seo/html.ts +217 -33
- package/src/seo/http.ts +20 -9
- package/src/seo/probe.ts +36 -29
- package/src/skills/bundled.ts +1 -1
- package/src/skills/link.ts +0 -320
package/README.md
CHANGED
|
@@ -83,8 +83,8 @@ validation suite, and release procedures.
|
|
|
83
83
|
aggregate gates, release verification, durable validation receipts, and
|
|
84
84
|
toolchain/protection diagnostics.
|
|
85
85
|
- [CLI reference](docs/reference.md): existing review, version, skill installation,
|
|
86
|
-
|
|
87
|
-
|
|
86
|
+
command capture, the SEO probe, import-graph checks, configuration, and
|
|
87
|
+
distribution contracts.
|
|
88
88
|
- [Development](docs/development.md): setup, source layout, validation, and release
|
|
89
89
|
procedures for this package.
|
|
90
90
|
- [Images](docs/images.md): declarative brand sources and generated outputs.
|
package/package.json
CHANGED
|
@@ -66,9 +66,12 @@ lists the page's internal links that do not answer 200 directly; and
|
|
|
66
66
|
`--sitemap` checks every sitemap URL's status, canonical, and robots, and
|
|
67
67
|
reports duplicate titles and descriptions. The mode flag comes first, the
|
|
68
68
|
host is a hostname with an optional port, and each path starts with `/`. The
|
|
69
|
-
probe matches
|
|
70
|
-
raw response before acting on it.
|
|
71
|
-
|
|
69
|
+
probe matches text patterns rather than parsing HTML, so confirm anything
|
|
70
|
+
surprising in the raw response before acting on it. A `000` status means no
|
|
71
|
+
response, including a URL it refused to request: one that is not HTTP or
|
|
72
|
+
HTTPS, or one on a private or local address that a page or redirect, not the
|
|
73
|
+
command line, named. Set `SEO_PROBE_USER_AGENT` to a browser user agent to see
|
|
74
|
+
what a zone injects only for browsers.
|
|
72
75
|
|
|
73
76
|
Check whether the default branch already has merged work that has not been
|
|
74
77
|
deployed, because a deploy ships it too. Deployment listings often do not
|
package/src/cli.ts
CHANGED
|
@@ -13,7 +13,6 @@ import { carryReviewCommand } from "./review/carry";
|
|
|
13
13
|
import { runAgentToolAction } from "./runAgentToolAction";
|
|
14
14
|
import { BUNDLED_SKILLS } from "./skills/bundled";
|
|
15
15
|
import { checkSkills, installSkills } from "./skills/install";
|
|
16
|
-
import { checkSkillLinks, linkSkills } from "./skills/link";
|
|
17
16
|
import { bunCommand } from "./bun/dependencies";
|
|
18
17
|
import { checkPermissions, installPermissions, showPermissions } from "./permissions/install";
|
|
19
18
|
import { bumpVersions, checkVersions, planVersions } from "./version/bumpVersions";
|
|
@@ -76,8 +75,6 @@ Usage: agent-tool [--repo <directory>] [--config <file>] <command>
|
|
|
76
75
|
skills list
|
|
77
76
|
skills install [--harness <all|claude|codex|opencode|hermes>] [--apply]
|
|
78
77
|
skills check [--harness <all|claude|codex|opencode|hermes>]
|
|
79
|
-
skills link [--apply] Link agent-tool.json skills.user into each user skill directory
|
|
80
|
-
skills check-links Read-only: exit 1 while a declared user skill link is missing, broken, or conflicts
|
|
81
78
|
bun install [--cwd <dir>] Frozen-lockfile install with the pinned Bun
|
|
82
79
|
bun add <name@version>... [--dev|--optional|--peer] [--exact] [--cwd <dir>]
|
|
83
80
|
bun update <name[@version]>... [--cwd <dir>] Change versions of declared dependencies only
|
|
@@ -197,24 +194,7 @@ export function main(argv = process.argv.slice(2)): number | Promise<number> {
|
|
|
197
194
|
if (command === "skills") {
|
|
198
195
|
const action = args.shift();
|
|
199
196
|
if (action === "list") { usage(args.length === 0, "Usage: agent-tool skills list"); output(Object.keys(BUNDLED_SKILLS)); return 0; }
|
|
200
|
-
|
|
201
|
-
let apply = false;
|
|
202
|
-
while (args.length) {
|
|
203
|
-
const flag = args.shift();
|
|
204
|
-
if (flag === "--apply") { usage(action === "link", "skills check-links is read-only; --apply is not allowed."); usage(!apply, "Duplicate --apply."); apply = true; }
|
|
205
|
-
else throw new Error(`Unknown skills ${action} argument '${flag}'.`);
|
|
206
|
-
}
|
|
207
|
-
// The checkout's top level, so a subdirectory cannot read as a repository that declares nothing.
|
|
208
|
-
const root = gitRoot();
|
|
209
|
-
const names = loadConfig(root).skills.user;
|
|
210
|
-
if (action === "check-links") {
|
|
211
|
-
const result = checkSkillLinks(root, names);
|
|
212
|
-
output(result); return result.ok ? 0 : 1;
|
|
213
|
-
}
|
|
214
|
-
const result = linkSkills(root, names, apply);
|
|
215
|
-
output(result); return result.changes.some(change => change.status === "conflict" || change.result === "failed") ? 1 : 0;
|
|
216
|
-
}
|
|
217
|
-
usage(action === "install" || action === "check", "Usage: agent-tool skills <list|install|check|link|check-links>");
|
|
197
|
+
usage(action === "install" || action === "check", "Usage: agent-tool skills <list|install|check>");
|
|
218
198
|
let target = "all", apply = false;
|
|
219
199
|
while (args.length) {
|
|
220
200
|
const flag = args.shift();
|
package/src/config.ts
CHANGED
|
@@ -26,8 +26,6 @@ export interface AgentToolConfig extends WorkflowConfig {
|
|
|
26
26
|
screenshots: ScreenshotsConfig;
|
|
27
27
|
graph: GraphConfig;
|
|
28
28
|
permissions: { executables: Record<string, PermissionClass> };
|
|
29
|
-
/** `user`: skills `skills link` links into each user skill directory, by skill directory name. */
|
|
30
|
-
skills: { user: string[] };
|
|
31
29
|
/** Null when the repository declares no push gate. */
|
|
32
30
|
pushGate: PushGateConfig | null;
|
|
33
31
|
}
|
|
@@ -51,7 +49,6 @@ export const DEFAULT_CONFIG: AgentToolConfig = {
|
|
|
51
49
|
screenshots: structuredClone(SCREENSHOTS_DEFAULTS),
|
|
52
50
|
graph: structuredClone(GRAPH_DEFAULTS),
|
|
53
51
|
permissions: { executables: {} },
|
|
54
|
-
skills: { user: [] },
|
|
55
52
|
pushGate: null,
|
|
56
53
|
};
|
|
57
54
|
|
|
@@ -104,7 +101,7 @@ export function parseConfig(source: string): AgentToolConfig {
|
|
|
104
101
|
keys(input, Object.keys(DEFAULT_CONFIG), "config");
|
|
105
102
|
if (input.schemaVersion !== 1) throw new Error("Unsupported config schemaVersion; expected 1.");
|
|
106
103
|
const result = structuredClone(DEFAULT_CONFIG);
|
|
107
|
-
for (const section of ["subject", "merge", "review", "versions", "pr", "branch", "commits", "hooks", "binaries", "permissions"
|
|
104
|
+
for (const section of ["subject", "merge", "review", "versions", "pr", "branch", "commits", "hooks", "binaries", "permissions"] as const) {
|
|
108
105
|
if (input[section] === undefined) continue;
|
|
109
106
|
const settings = object(input[section], section);
|
|
110
107
|
keys(settings, Object.keys(result[section]), section);
|
|
@@ -150,10 +147,6 @@ export function parseConfig(source: string): AgentToolConfig {
|
|
|
150
147
|
// Names become literal tokens in harness rules, so keep them free of rule syntax.
|
|
151
148
|
const executables = object(result.permissions.executables, "permissions.executables");
|
|
152
149
|
for (const [name, value] of Object.entries(executables)) if (!/^[\w.+-]+$/.test(name) || !(typeof value === "string" && Object.hasOwn(CLASSES, value))) invalid(`permissions.executables.${name}`);
|
|
153
|
-
// Names become entries in user skill directories, so each is a plain skill directory name, once.
|
|
154
|
-
// `synced` is Claude Code's own account-synced skill store.
|
|
155
|
-
const user = result.skills.user;
|
|
156
|
-
if (!Array.isArray(user) || user.some(name => typeof name !== "string" || name.length > 64 || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name) || name === "synced") || new Set(user).size !== user.length) invalid("skills.user");
|
|
157
150
|
validateWorkflowConfig(result);
|
|
158
151
|
return result;
|
|
159
152
|
}
|
|
@@ -9,7 +9,7 @@ export const CLASSES = {
|
|
|
9
9
|
share: { decision: "allow", description: "Publishes work for review without changing a shared branch: pushes a feature branch, opens a PR, answers review threads, or prunes a merged PR's feature branch." },
|
|
10
10
|
release: { decision: "ask", description: "Merges into a shared branch, publishes a package, or deletes remote state." },
|
|
11
11
|
intake: { decision: "ask", description: "Brings new third-party code into the repository." },
|
|
12
|
-
policy: { decision: "ask", description: "Changes the permissions agents run with
|
|
12
|
+
policy: { decision: "ask", description: "Changes the permissions agents run with." },
|
|
13
13
|
exec: { decision: "ask", description: "Runs whatever command or file its arguments name." },
|
|
14
14
|
} as const;
|
|
15
15
|
export type PermissionClass = keyof typeof CLASSES;
|
|
@@ -19,7 +19,7 @@ export type Decision = "allow" | "ask";
|
|
|
19
19
|
export interface CatalogEntry { command: string; class: PermissionClass; applyClass?: PermissionClass }
|
|
20
20
|
|
|
21
21
|
export const CATALOG: CatalogEntry[] = [
|
|
22
|
-
...["--help", "--version", "logs", "runs list", "doctor", "config show", "branch check", "branch status", "commits check", "checks binaries", "repo context", "policy check", "toolchain check", "ci gate", "release plan", "release verify", "pr context", "pr checks", "pr logs", "pr preflight", "pr threads list", "versions plan", "versions check", "dependencies check-terraform-plan", "dependencies diff", "skills list", "skills check", "
|
|
22
|
+
...["--help", "--version", "logs", "runs list", "doctor", "config show", "branch check", "branch status", "commits check", "checks binaries", "repo context", "policy check", "toolchain check", "ci gate", "release plan", "release verify", "pr context", "pr checks", "pr logs", "pr preflight", "pr threads list", "versions plan", "versions check", "dependencies check-terraform-plan", "dependencies diff", "skills list", "skills check", "hooks check", "push-gate hook", "push-gate check", "repo base-health", "review carry", "images list", "graph check", "state-machines", "permissions show", "permissions check", "proc list"]
|
|
23
23
|
.map(command => ({ command, class: "read" as const })),
|
|
24
24
|
...["bun install", "bun update", "bun remove", "bun test", "branch create", "versions bump", "versions prepare", "versions resolve-conflicts", "images build", "screenshots build", "review", "init", "proc stop"]
|
|
25
25
|
.map(command => ({ command, class: "local" as const })),
|
|
@@ -27,8 +27,6 @@ export const CATALOG: CatalogEntry[] = [
|
|
|
27
27
|
{ command: "hooks install", class: "read", applyClass: "local" },
|
|
28
28
|
{ command: "teardown", class: "read", applyClass: "local" },
|
|
29
29
|
{ command: "permissions install", class: "read", applyClass: "policy" },
|
|
30
|
-
// Linking writes outside the checkout, into the user skill directories every session loads.
|
|
31
|
-
{ command: "skills link", class: "read", applyClass: "policy" },
|
|
32
30
|
...["branch push", "pr open", "pr cancel-runs", "pr threads reply", "pr threads resolve"].map(command => ({ command, class: "share" as const })),
|
|
33
31
|
{ command: "pr merge", class: "release" },
|
|
34
32
|
// Cleanup acts only after GitHub confirms the PR MERGED and the local and remote
|
|
@@ -41,7 +39,7 @@ export const CATALOG: CatalogEntry[] = [
|
|
|
41
39
|
{ command: "openPr", class: "share" },
|
|
42
40
|
];
|
|
43
41
|
// `run`, `run-group`, `push-gate run` and `proc start` execute arbitrary commands, so they stay unclassified and keep the harness default.
|
|
44
|
-
// `seo probe` requests whatever
|
|
42
|
+
// `seo probe` requests whatever host its arguments name, and public hosts its fetched pages name, like curl, so it keeps the harness default too.
|
|
45
43
|
// `bun x` runs only executables that `permissions.executables` classifies; project.ts adds those.
|
|
46
44
|
// Package scripts are not classified, so `bun run` keeps the harness default.
|
|
47
45
|
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which hosts `seo probe` may request when a URL comes from fetched markup or a
|
|
3
|
+
* redirect rather than the command line: a hostile page could otherwise point
|
|
4
|
+
* the probe at this machine or its network (`og:image` on `169.254.169.254`, a
|
|
5
|
+
* sitemap entry on `localhost`) and print what answers.
|
|
6
|
+
*/
|
|
7
|
+
import { lookup as dnsLookup } from "node:dns/promises";
|
|
8
|
+
import { isIP } from "node:net";
|
|
9
|
+
|
|
10
|
+
/** Every address a hostname resolves to; an unresolvable name has none. */
|
|
11
|
+
export type Lookup = (hostname: string) => Promise<string[]>;
|
|
12
|
+
/** Why a URL must not be requested, or undefined when it may be, deciding within `milliseconds`. */
|
|
13
|
+
export type Guard = (url: URL, milliseconds: number) => Promise<string | undefined>;
|
|
14
|
+
|
|
15
|
+
const systemLookup: Lookup = async hostname => (await dnsLookup(hostname, { all: true, verbatim: true })).map(entry => entry.address);
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* IPv4 ranges outside the public internet: this network, private, shared
|
|
19
|
+
* (CGNAT), loopback, link-local, IETF protocol assignments, documentation,
|
|
20
|
+
* benchmarking, and multicast or reserved.
|
|
21
|
+
*/
|
|
22
|
+
const V4_RANGES: [string, number][] = [
|
|
23
|
+
["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8], ["169.254.0.0", 16], ["172.16.0.0", 12], ["192.0.0.0", 24],
|
|
24
|
+
["192.0.2.0", 24], ["192.168.0.0", 16], ["198.18.0.0", 15], ["198.51.100.0", 24], ["203.0.113.0", 24], ["224.0.0.0", 3],
|
|
25
|
+
];
|
|
26
|
+
|
|
27
|
+
function ipv4(address: string): number {
|
|
28
|
+
return address.split(".").reduce((value, part) => value * 256 + Number(part), 0);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const inRange = (value: number, [base, bits]: [string, number]) => Math.floor(value / 2 ** (32 - bits)) === Math.floor(ipv4(base) / 2 ** (32 - bits));
|
|
32
|
+
const nonPublicV4 = (address: string) => V4_RANGES.some(range => inRange(ipv4(address), range));
|
|
33
|
+
|
|
34
|
+
/** The eight 16-bit groups of an IPv6 address, with a trailing dotted IPv4 part expanded. */
|
|
35
|
+
function ipv6Groups(address: string): number[] {
|
|
36
|
+
let text = address.replace(/%.*$/, "");
|
|
37
|
+
const dotted = /(\d+\.\d+\.\d+\.\d+)$/.exec(text);
|
|
38
|
+
if (dotted) {
|
|
39
|
+
const value = ipv4(dotted[1]!);
|
|
40
|
+
text = `${text.slice(0, dotted.index)}${Math.floor(value / 65536).toString(16)}:${(value % 65536).toString(16)}`;
|
|
41
|
+
}
|
|
42
|
+
const [head = "", tail] = text.split("::");
|
|
43
|
+
const parse = (part: string) => part ? part.split(":").map(group => parseInt(group, 16)) : [];
|
|
44
|
+
const left = parse(head), right = tail === undefined ? [] : parse(tail);
|
|
45
|
+
return [...left, ...Array<number>(8 - left.length - right.length).fill(0), ...right];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const embeddedV4 = (high: number, low: number) => `${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`;
|
|
49
|
+
|
|
50
|
+
/** Loopback, link-local, private, unspecified, multicast, or reserved: anything that is not a public unicast address. */
|
|
51
|
+
export function isNonPublicAddress(address: string): boolean {
|
|
52
|
+
const family = isIP(address.replace(/%.*$/, ""));
|
|
53
|
+
if (family === 4) return nonPublicV4(address);
|
|
54
|
+
if (family !== 6) return true;
|
|
55
|
+
const groups = ipv6Groups(address);
|
|
56
|
+
const [a = 0, b = 0, , , , f = 0, g = 0, h = 0] = groups;
|
|
57
|
+
const zeros = (count: number) => groups.slice(0, count).every(group => group === 0);
|
|
58
|
+
// IPv4-mapped ::ffff:a.b.c.d and IPv4-translated ::ffff:0:a.b.c.d are that IPv4 address; the rest of ::/96 is unspecified, loopback, or deprecated.
|
|
59
|
+
if ((zeros(5) && f === 0xffff) || (zeros(4) && groups[4] === 0xffff && f === 0)) return nonPublicV4(embeddedV4(g, h));
|
|
60
|
+
if (zeros(6)) return true;
|
|
61
|
+
// NAT64 well-known prefix 64:ff9b::/96, and 6to4 2002::/16, which carry an IPv4 address.
|
|
62
|
+
if (a === 0x64 && b === 0xff9b && groups.slice(2, 6).every(group => group === 0)) return nonPublicV4(embeddedV4(g, h));
|
|
63
|
+
if (a === 0x2002) return nonPublicV4(embeddedV4(b, groups[2] ?? 0));
|
|
64
|
+
// Unique local fc00::/7, link-local fe80::/10, site-local fec0::/10, multicast ff00::/8, local-use NAT64 64:ff9b:1::/48,
|
|
65
|
+
// discard 100::/64, Teredo 2001::/32, and documentation 2001:db8::/32.
|
|
66
|
+
return (a & 0xfe00) === 0xfc00 || (a & 0xffc0) === 0xfe80 || (a & 0xffc0) === 0xfec0 || (a & 0xff00) === 0xff00 || (a === 0x64 && b === 0xff9b && groups[2] === 1)
|
|
67
|
+
|| (a === 0x100 && groups.slice(1, 4).every(group => group === 0)) || (a === 0x2001 && (b === 0 || b === 0xdb8));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The promise's value, or undefined when it takes longer than `milliseconds`. */
|
|
71
|
+
async function within<T>(promise: Promise<T>, milliseconds: number): Promise<T | undefined> {
|
|
72
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
73
|
+
try {
|
|
74
|
+
return await Promise.race([promise, new Promise<undefined>(resolve => { timer = setTimeout(resolve, Math.max(0, milliseconds), undefined); })]);
|
|
75
|
+
} finally { clearTimeout(timer); }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** How long the named host's own lookup may take before the guard assumes it is public. */
|
|
79
|
+
const NAMED_LOOKUP_MILLISECONDS = 15_000;
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The guard for URLs that markup or redirects supply, or undefined when every
|
|
83
|
+
* address of the named host is non-public (probing a local server), since then
|
|
84
|
+
* every target is the user's own network. Otherwise a host that is, or resolves
|
|
85
|
+
* to, any non-public address is refused, except the named host itself, which
|
|
86
|
+
* the user chose: a page cannot switch the guard off, or reach this network
|
|
87
|
+
* through another name, by publishing a private record beside a public one.
|
|
88
|
+
* Names resolve once per run through the system resolver, as `fetch` resolves
|
|
89
|
+
* them. A name that does not resolve is left to the request, which fails or
|
|
90
|
+
* goes through a proxy; one that does not resolve within the request's time
|
|
91
|
+
* limit is refused. The check runs just before each request, so a name that
|
|
92
|
+
* resolves differently by the time `fetch` connects (DNS rebinding) is not
|
|
93
|
+
* caught.
|
|
94
|
+
*/
|
|
95
|
+
export async function addressGuard(namedHost: string, lookup: Lookup = systemLookup, namedMilliseconds = NAMED_LOOKUP_MILLISECONDS): Promise<Guard | undefined> {
|
|
96
|
+
const cache = new Map<string, Promise<string[]>>();
|
|
97
|
+
const bare = (hostname: string) => hostname.replace(/^\[|\]$/g, "");
|
|
98
|
+
const addresses = (hostname: string) => {
|
|
99
|
+
let found = cache.get(hostname);
|
|
100
|
+
if (!found) {
|
|
101
|
+
found = isIP(hostname) ? Promise.resolve([hostname]) : lookup(hostname).catch(() => []);
|
|
102
|
+
cache.set(hostname, found);
|
|
103
|
+
}
|
|
104
|
+
return found;
|
|
105
|
+
};
|
|
106
|
+
const named = bare(new URL(`http://${namedHost}/`).hostname);
|
|
107
|
+
const own = await within(addresses(named), namedMilliseconds);
|
|
108
|
+
if (own?.length && own.every(isNonPublicAddress)) return undefined;
|
|
109
|
+
return async (url, milliseconds) => {
|
|
110
|
+
const hostname = bare(url.hostname);
|
|
111
|
+
if (hostname === named) return undefined;
|
|
112
|
+
const found = await within(addresses(hostname), milliseconds);
|
|
113
|
+
if (found === undefined) return `refused ${hostname}: it did not resolve within the request's time limit`;
|
|
114
|
+
const address = found.find(isNonPublicAddress);
|
|
115
|
+
return address === undefined ? undefined : `refused ${hostname} (${address}): a non-public address that the command line did not name`;
|
|
116
|
+
};
|
|
117
|
+
}
|
package/src/seo/html.ts
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
2
|
+
* Markup readers for `seo probe`, over HTML with its newlines, carriage
|
|
3
|
+
* returns, and tabs collapsed to spaces. They match what the original shell
|
|
4
|
+
* probe's `grep -oiE` patterns matched (`<meta[^>]+name="description"[^>]*>`
|
|
5
|
+
* and the like): double-quoted attributes only, ASCII case-insensitive, first
|
|
6
|
+
* match or every match in document order, and no HTML parser, so a surprising
|
|
7
|
+
* result needs a look at the raw response. They scan with `indexOf` instead of
|
|
8
|
+
* regular expressions, reading each character a bounded number of times, since
|
|
9
|
+
* a backtracking pattern takes quadratic time on a hostile page with many
|
|
10
|
+
* unterminated tags.
|
|
7
11
|
*/
|
|
8
12
|
|
|
9
13
|
/** The body as one line: `\n`, `\r`, and `\t` become spaces. */
|
|
@@ -11,57 +15,206 @@ export function collapse(body: string): string {
|
|
|
11
15
|
return body.replace(/[\n\r\t]/g, " ");
|
|
12
16
|
}
|
|
13
17
|
|
|
14
|
-
|
|
18
|
+
/** ASCII-only lowercase, so every index still points at the same character of the original. */
|
|
19
|
+
const lower = (text: string) => text.replace(/[A-Z]+/g, run => run.toLowerCase());
|
|
15
20
|
|
|
16
|
-
/**
|
|
17
|
-
|
|
18
|
-
return [...text.matchAll(new RegExp(pattern, "gi"))].map(match => match[0]);
|
|
19
|
-
}
|
|
21
|
+
/** Distinct values in code-unit order, each followed by one space. */
|
|
22
|
+
const spaced = (values: string[]) => [...new Set(values)].sort().map(value => `${value} `).join("");
|
|
20
23
|
|
|
21
|
-
|
|
22
|
-
export function first(text: string, pattern: string): string {
|
|
23
|
-
return new RegExp(pattern, "i").exec(text)?.[0] ?? "";
|
|
24
|
-
}
|
|
24
|
+
interface Span { start: number; end: number }
|
|
25
25
|
|
|
26
|
-
/**
|
|
27
|
-
|
|
28
|
-
|
|
26
|
+
/**
|
|
27
|
+
* The tags the pattern `<name[^>]+needle[^>]*>` matches, as spans from `<name`
|
|
28
|
+
* through its first `>`: one of `needles` must start at least one character
|
|
29
|
+
* after the name. Of several `<name` before the same `>`, only the first can
|
|
30
|
+
* match (a later one's text is a suffix of it), so the scan resumes after that
|
|
31
|
+
* `>` whether or not the tag matched.
|
|
32
|
+
*/
|
|
33
|
+
function tags(text: string, name: string, needles: string[], limit = Infinity): Span[] {
|
|
34
|
+
const open = `<${name}`, found: Span[] = [];
|
|
35
|
+
for (let from = 0; found.length < limit;) {
|
|
36
|
+
const start = text.indexOf(open, from);
|
|
37
|
+
if (start < 0) break;
|
|
38
|
+
const end = text.indexOf(">", start + open.length);
|
|
39
|
+
if (end < 0) break;
|
|
40
|
+
const inside = text.slice(start + open.length + 1, end);
|
|
41
|
+
if (needles.some(needle => inside.includes(needle))) found.push({ start, end: end + 1 });
|
|
42
|
+
from = end + 1;
|
|
43
|
+
}
|
|
44
|
+
return found;
|
|
29
45
|
}
|
|
30
46
|
|
|
31
|
-
/** Every `name="value"` value in `text`, in order. */
|
|
47
|
+
/** Every `name="value"` value in `text`, in order, as the pattern `name="[^"]*"` finds them. */
|
|
32
48
|
export function attrValues(text: string, name: string): string[] {
|
|
33
|
-
|
|
49
|
+
const lowered = lower(text), opening = `${name}="`, values: string[] = [];
|
|
50
|
+
for (let at = lowered.indexOf(opening); at >= 0; at = lowered.indexOf(opening, at)) {
|
|
51
|
+
const close = lowered.indexOf('"', at + opening.length);
|
|
52
|
+
if (close < 0) break;
|
|
53
|
+
values.push(text.slice(at + opening.length, close));
|
|
54
|
+
at = close + 1;
|
|
55
|
+
}
|
|
56
|
+
return values;
|
|
34
57
|
}
|
|
35
58
|
|
|
36
59
|
/** The same values, one per line. */
|
|
37
60
|
export const attr = (text: string, name: string) => attrValues(text, name).join("\n");
|
|
38
61
|
|
|
62
|
+
/**
|
|
63
|
+
* The `attribute` values in each tag that the pattern
|
|
64
|
+
* `<name[^>]+attribute="[^"]*"` (`[^>]*` when `gap` is 0) matches, as
|
|
65
|
+
* `attrValues` reads them from the match. The pattern needs no closing `>`, so
|
|
66
|
+
* a tag that never closes runs to the end of the text. Its greedy middle ends
|
|
67
|
+
* at the last value that starts before the tag's first `>` and has a closing
|
|
68
|
+
* quote, which may lie past that `>`; the tag matches when that value starts
|
|
69
|
+
* at least `gap` characters after the name. Of several `<name` before the
|
|
70
|
+
* same `>`, only the first can match.
|
|
71
|
+
*/
|
|
72
|
+
function tagValues(text: string, name: string, attribute: string, gap: 0 | 1, limit = Infinity): string[][] {
|
|
73
|
+
const lowered = lower(text), open = `<${name}`, opening = `${attribute}="`, found: string[][] = [];
|
|
74
|
+
for (let from = 0; found.length < limit;) {
|
|
75
|
+
const start = lowered.indexOf(open, from);
|
|
76
|
+
if (start < 0) break;
|
|
77
|
+
const inside = start + open.length, close = lowered.indexOf(">", inside), end = close < 0 ? text.length : close;
|
|
78
|
+
const segment = lowered.slice(inside, end);
|
|
79
|
+
let last = segment.lastIndexOf(opening);
|
|
80
|
+
// Only the final value can lack a closing quote, and then the one before it has one.
|
|
81
|
+
if (last >= 0 && lowered.indexOf('"', inside + last + opening.length) < 0) last = last > 0 ? segment.lastIndexOf(opening, last - 1) : -1;
|
|
82
|
+
from = end + 1;
|
|
83
|
+
if (last >= gap) {
|
|
84
|
+
const values: string[] = [];
|
|
85
|
+
for (let at = segment.indexOf(opening); at >= 0 && at <= last; at = segment.indexOf(opening, at)) {
|
|
86
|
+
const quote = lowered.indexOf('"', inside + at + opening.length);
|
|
87
|
+
values.push(text.slice(inside + at + opening.length, quote));
|
|
88
|
+
at = quote + 1 - inside;
|
|
89
|
+
}
|
|
90
|
+
found.push(values);
|
|
91
|
+
// The match ends at that last value's closing quote, which can lie past the `>`.
|
|
92
|
+
from = Math.max(from, lowered.indexOf('"', inside + last + opening.length) + 1);
|
|
93
|
+
}
|
|
94
|
+
if (close < 0) break;
|
|
95
|
+
}
|
|
96
|
+
return found;
|
|
97
|
+
}
|
|
98
|
+
|
|
39
99
|
/** Decode the predefined XML entities; `&` goes last so `&lt;` stays `<`. */
|
|
40
100
|
export function unescape(value: string): string {
|
|
41
101
|
return value.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/'/g, "'").replace(/&/g, "&");
|
|
42
102
|
}
|
|
43
103
|
|
|
44
|
-
/** The content of
|
|
45
|
-
|
|
46
|
-
|
|
104
|
+
/** The `content` values of every `<meta>` whose `name` (or `property`) is one of `keys`. */
|
|
105
|
+
function metaContents(body: string, keys: string[], properties: boolean, limit = Infinity): string[] {
|
|
106
|
+
const needles = keys.flatMap(key => [`name="${key}"`, ...(properties ? [`property="${key}"`] : [])]);
|
|
107
|
+
return tags(lower(body), "meta", needles, limit).flatMap(({ start, end }) => attrValues(body.slice(start, end), "content"));
|
|
47
108
|
}
|
|
48
109
|
|
|
110
|
+
/** The content of the first `<meta>` whose property or name is `key`. */
|
|
111
|
+
export const contentOf = (body: string, key: string) => metaContents(body, [key], true, 1).join("\n");
|
|
112
|
+
|
|
113
|
+
/** The content of each robots and googlebot meta tag, in order. */
|
|
114
|
+
export const robotsMetaContents = (body: string) => metaContents(body, ["robots", "googlebot"], false);
|
|
115
|
+
|
|
49
116
|
/** Every robots and googlebot meta directive, lowercase, joined with spaces. */
|
|
50
|
-
export
|
|
51
|
-
|
|
52
|
-
|
|
117
|
+
export const robotsMeta = (body: string) => robotsMetaContents(body).join(" ").toLowerCase();
|
|
118
|
+
|
|
119
|
+
/** Each `theme-color` meta tag's content, each followed by one space. */
|
|
120
|
+
export const themeColors = (body: string) => metaContents(body, ["theme-color"], false).map(value => `${value} `).join("");
|
|
53
121
|
|
|
54
122
|
export function titleOf(body: string): string {
|
|
55
|
-
|
|
123
|
+
const lowered = lower(body);
|
|
124
|
+
for (let from = 0; ;) {
|
|
125
|
+
const start = lowered.indexOf("<title", from);
|
|
126
|
+
if (start < 0) return "";
|
|
127
|
+
const close = lowered.indexOf(">", start + 6);
|
|
128
|
+
if (close < 0) return "";
|
|
129
|
+
const next = lowered.indexOf("<", close + 1);
|
|
130
|
+
if (next < 0) return "";
|
|
131
|
+
if (lowered.startsWith("</title>", next)) return body.slice(close + 1, next);
|
|
132
|
+
from = close + 1;
|
|
133
|
+
}
|
|
56
134
|
}
|
|
57
135
|
|
|
58
136
|
export function canonicalOf(body: string): string {
|
|
59
|
-
|
|
137
|
+
const [tag] = tags(lower(body), "link", ['rel="canonical"'], 1);
|
|
138
|
+
return tag ? unescape(attr(body.slice(tag.start, tag.end), "href")) : "";
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** The `lang` values of the first `<html>` tag that has one, one per line. */
|
|
142
|
+
export const langOf = (body: string) => (tagValues(body, "html", "lang", 0, 1)[0] ?? []).join("\n");
|
|
143
|
+
|
|
144
|
+
const isLetter = (code: number) => (code >= 97 && code <= 122) || (code >= 65 && code <= 90);
|
|
145
|
+
|
|
146
|
+
/** The distinct `og:` properties present, as `"og:name"`, each followed by one space: the pattern `property="og:[a-z_:]+"`. */
|
|
147
|
+
export function ogProperties(body: string): string {
|
|
148
|
+
const lowered = lower(body), opening = 'property="og:', found: string[] = [];
|
|
149
|
+
for (let from = 0; ;) {
|
|
150
|
+
const start = lowered.indexOf(opening, from);
|
|
151
|
+
if (start < 0) break;
|
|
152
|
+
let end = start + opening.length;
|
|
153
|
+
for (let code = lowered.charCodeAt(end); isLetter(code) || code === 95 || code === 58; code = lowered.charCodeAt(++end));
|
|
154
|
+
if (end > start + opening.length && lowered[end] === '"') { found.push(body.slice(start, end + 1)); from = end + 1; }
|
|
155
|
+
else from = start + 1;
|
|
156
|
+
}
|
|
157
|
+
return spaced(found).replace(/property=/g, "");
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** How many times `needle` occurs, ASCII case-insensitively. */
|
|
161
|
+
function count(body: string, needle: string, after?: (next: string | undefined) => boolean): number {
|
|
162
|
+
const lowered = lower(body);
|
|
163
|
+
let total = 0;
|
|
164
|
+
for (let at = lowered.indexOf(needle); at >= 0; at = lowered.indexOf(needle, at + needle.length)) {
|
|
165
|
+
if (!after || after(lowered[at + needle.length])) total++;
|
|
166
|
+
}
|
|
167
|
+
return total;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export const jsonLdBlocks = (body: string) => count(body, "application/ld+json");
|
|
171
|
+
export const h1Count = (body: string) => count(body, "<h1", next => next === " " || next === ">");
|
|
172
|
+
|
|
173
|
+
/** The distinct JSON-LD `@type` values, as `"Name"` or `["A","B"]`, each followed by one space: the pattern `"@type": *("[A-Za-z]+"|\[[^\]]*\])`. */
|
|
174
|
+
export function jsonLdTypes(body: string): string {
|
|
175
|
+
const lowered = lower(body), opening = '"@type":', found: string[] = [];
|
|
176
|
+
let noBracket = false;
|
|
177
|
+
for (let from = 0; ;) {
|
|
178
|
+
const start = lowered.indexOf(opening, from);
|
|
179
|
+
if (start < 0) break;
|
|
180
|
+
let at = start + opening.length;
|
|
181
|
+
while (body[at] === " ") at++;
|
|
182
|
+
let end = -1;
|
|
183
|
+
if (body[at] === '"') {
|
|
184
|
+
let letters = at + 1;
|
|
185
|
+
while (isLetter(body.charCodeAt(letters))) letters++;
|
|
186
|
+
if (letters > at + 1 && body[letters] === '"') end = letters + 1;
|
|
187
|
+
} else if (body[at] === "[" && !noBracket) {
|
|
188
|
+
const close = body.indexOf("]", at + 1);
|
|
189
|
+
if (close < 0) noBracket = true;
|
|
190
|
+
else end = close + 1;
|
|
191
|
+
}
|
|
192
|
+
if (end > 0) { found.push(body.slice(start, end)); from = end; }
|
|
193
|
+
else from = start + 1;
|
|
194
|
+
}
|
|
195
|
+
return spaced(found).replace(/"@type": */g, "");
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Leading and trailing spaces removed, without a pattern that backtracks over a long run of spaces. */
|
|
199
|
+
function trimSpaces(value: string): string {
|
|
200
|
+
let start = 0, end = value.length;
|
|
201
|
+
while (start < end && value[start] === " ") start++;
|
|
202
|
+
while (end > start && value[end - 1] === " ") end--;
|
|
203
|
+
return value.slice(start, end);
|
|
60
204
|
}
|
|
61
205
|
|
|
62
206
|
/** The `<loc>` values of a sitemap, trimmed and decoded. */
|
|
63
207
|
export function locs(body: string): string[] {
|
|
64
|
-
|
|
208
|
+
const text = collapse(body), found: string[] = [];
|
|
209
|
+
for (let from = 0; ;) {
|
|
210
|
+
const start = text.indexOf("<loc>", from);
|
|
211
|
+
if (start < 0) break;
|
|
212
|
+
const next = text.indexOf("<", start + 5);
|
|
213
|
+
if (next < 0) break;
|
|
214
|
+
if (next > start + 5 && text.startsWith("</loc>", next)) { found.push(unescape(trimSpaces(text.slice(start + 5, next)))); from = next + 6; }
|
|
215
|
+
else from = start + 1;
|
|
216
|
+
}
|
|
217
|
+
return found;
|
|
65
218
|
}
|
|
66
219
|
|
|
67
220
|
/** A sitemap or sitemap index document, by its root element. */
|
|
@@ -89,6 +242,32 @@ export function lines(text: string): string[] {
|
|
|
89
242
|
return all;
|
|
90
243
|
}
|
|
91
244
|
|
|
245
|
+
/** Valued robots directives, whose value can be `none` without blocking indexing. */
|
|
246
|
+
const VALUED_DIRECTIVES = new Set(["max-snippet", "max-image-preview", "max-video-preview", "unavailable_after"]);
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Whether a robots value keeps a page out of search: a whole `noindex` or
|
|
250
|
+
* `none` directive, in a list separated by commas or spaces. A valued
|
|
251
|
+
* directive such as `max-image-preview:none` never counts, nor does its value
|
|
252
|
+
* after a space (`max-image-preview: none`). In an
|
|
253
|
+
* `X-Robots-Tag` header (`agentPrefix`), an element may begin with any other
|
|
254
|
+
* `name:`, which names a crawler, as in `googlebot: none` or
|
|
255
|
+
* `googlebot:noindex`; robots meta tags name the crawler in the tag instead.
|
|
256
|
+
*/
|
|
257
|
+
export function blocksIndexing(value: string, agentPrefix: boolean): boolean {
|
|
258
|
+
return value.toLowerCase().split(",").some(element => {
|
|
259
|
+
const tokens = element.trim().split(/\s+/);
|
|
260
|
+
const colon = tokens[0]!.indexOf(":");
|
|
261
|
+
if (agentPrefix && colon >= 0 && !VALUED_DIRECTIVES.has(tokens[0]!.slice(0, colon))) tokens[0] = tokens[0]!.slice(colon + 1);
|
|
262
|
+
for (let index = 0; index < tokens.length; index++) {
|
|
263
|
+
const token = tokens[index]!;
|
|
264
|
+
if (token.endsWith(":") && VALUED_DIRECTIVES.has(token.slice(0, -1))) index++; // the next token is its value
|
|
265
|
+
else if (token === "noindex" || token === "none") return true;
|
|
266
|
+
}
|
|
267
|
+
return false;
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
|
|
92
271
|
/**
|
|
93
272
|
* Resolve a relative reference (no scheme, not protocol-relative) against the
|
|
94
273
|
* final document path: a query-only reference against the page itself, any
|
|
@@ -115,6 +294,11 @@ export function resolvePath(reference: string, page: string): string {
|
|
|
115
294
|
return resolved + query;
|
|
116
295
|
}
|
|
117
296
|
|
|
297
|
+
/** Every `href` value of an `<a>` tag, in order, as the pattern `<a[^>]+href="[^"]*"` finds them. */
|
|
298
|
+
export const hrefValues = (body: string) => tagValues(body, "a", "href", 1).flat();
|
|
299
|
+
|
|
300
|
+
const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
|
|
301
|
+
|
|
118
302
|
/**
|
|
119
303
|
* The page's links to its own host, as URLs to request: absolute ones exactly
|
|
120
304
|
* as written, protocol-relative ones with the page's scheme, and relative ones
|
|
@@ -124,14 +308,14 @@ export function resolvePath(reference: string, page: string): string {
|
|
|
124
308
|
export function internalLinks(body: string, finalUrl: URL): string[] {
|
|
125
309
|
const origin = `${finalUrl.protocol}//${finalUrl.host}`;
|
|
126
310
|
const host = escapeRegExp(finalUrl.host);
|
|
127
|
-
const
|
|
128
|
-
|
|
129
|
-
.map(href => unescape(href).
|
|
311
|
+
const absolute = new RegExp(`^https?://${host}(?:[/?]|$)`, "i"), relative = new RegExp(`^//${host}(?:[/?]|$)`, "i");
|
|
312
|
+
const hrefs = hrefValues(body)
|
|
313
|
+
.map(href => { const value = unescape(href), hash = value.indexOf("#"); return hash < 0 ? value : value.slice(0, hash); })
|
|
130
314
|
.filter(href => href !== "");
|
|
131
315
|
const links = new Set<string>();
|
|
132
316
|
for (const href of hrefs) {
|
|
133
|
-
if (
|
|
134
|
-
else if (
|
|
317
|
+
if (absolute.test(href)) links.add(href);
|
|
318
|
+
else if (relative.test(href)) links.add(`${finalUrl.protocol}${href}`);
|
|
135
319
|
else if (!/^[a-zA-Z][a-zA-Z0-9+.-]*:|^\/\//.test(href)) links.add(origin + resolvePath(href, finalUrl.pathname));
|
|
136
320
|
}
|
|
137
321
|
return [...links].sort();
|