@a2f0/agent-tool 0.1.69 → 0.1.70

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.
@@ -0,0 +1,144 @@
1
+ # Framework notes
2
+
3
+ ## Astro
4
+
5
+ - Inject the tier with `vite.define` on an `import.meta.env.PUBLIC_*` value,
6
+ so `astro.config.*` and the pages agree on it. Astro integrations do not
7
+ receive `--mode`; record it from a Vite plugin's `configResolved` hook, and
8
+ throw when it is missing.
9
+ - Write JSON-LD with
10
+ `<script is:inline type="application/ld+json" set:html={json}>` and escape
11
+ `<` as `\u003c` in the serialized JSON.
12
+ - When conditional tags go into a named slot, wrap them as
13
+ `<Fragment slot="head">{condition && …}</Fragment>` rather than putting the
14
+ condition around an element that carries `slot=`. Test that the output
15
+ lands inside `<head>`.
16
+ - In `astro:build:done`, page pathnames look like `""`, `"privacy/"`, and
17
+ `"404/"`. Filter error pages out of the sitemap. `@astrojs/sitemap` works,
18
+ or a small integration can write `sitemap.xml` and `robots.txt` from the
19
+ built pages.
20
+ - Knip treats `astro.config.*` as plugin configuration, so a new integration
21
+ file it imports may need to be listed as a production entry.
22
+
23
+ ## Next.js static export
24
+
25
+ - A page that renders only on the client (`autoExport` with an empty
26
+ `<div id="__next">`) gives crawlers nothing. `next/head` tags in a
27
+ statically exported page do reach the HTML; the main copy needs build-time
28
+ rendering, which is content work.
29
+ - With the pages router, put tier-wide tags such as the staging robots meta
30
+ in `_document.tsx`, so `404.html` gets them too. Inline the tier through
31
+ `next.config` `env` so the browser hydrates with the same tags; otherwise
32
+ `next/head` can add or drop them on the client.
33
+ - Do not import relative TypeScript into `next.config.ts`.
34
+ - Add an explicit `pages/404.tsx` so the error page's head (noindex, no
35
+ canonical, no `og:url`) is under the app's control, and pair it with
36
+ `not_found_handling: "404-page"` when missing paths should get it.
37
+ - When two `next/head` instances emit the same tag, whichever re-rendered
38
+ last wins, even with matching `key`s. Keep one owner for a dynamic tag such
39
+ as `theme-color`. When the theme provider renders on the client below
40
+ `<Head>`, read the attribute it stamps on `<html>` instead.
41
+ - `next build` clears `out/`, so write `robots.txt`, `sitemap.xml`, and
42
+ `_headers` after it. With a single-page fallback on the host, a missing
43
+ file is answered with HTML.
44
+
45
+ ## Monorepo tooling
46
+
47
+ - Turborepo strict environment mode drops undeclared variables, so declare a
48
+ tier variable in `turbo.json` `env`. Declaring it also keeps the two tiers'
49
+ caches apart.
50
+ - In a package script, `VAR=x a && b` sets the variable for `a` only.
51
+ - A broad ignore pattern such as `build/` can also match a new
52
+ `scripts/build/` file, so `git add -A` silently skips it. Run
53
+ `git check-ignore` on new files.
54
+ - A production check of "no noindex anywhere" fails when a site copies
55
+ deliberately noindexed pages from a package. Check the header rules and the
56
+ pages the site owns.
57
+ - When a package's pages are copied into another site, give them absolute
58
+ canonical, `og:url`, and JSON-LD URLs on their own production host, never
59
+ derived from the request host, so the copies point back to the original.
60
+ Keep robots.txt, the sitemap, the preview image, and the 404 page out of
61
+ the package; they belong at the deployment root. Any change to files in
62
+ the published tarball follows the repository's versioning policy, and the
63
+ report names the release a consuming site needs.
64
+ - Tests that fetch every `src` and `href` in a page will fetch an absolute
65
+ canonical from the live network; filter them to relative references.
66
+
67
+ ## Theme-color with a theme switch
68
+
69
+ Keep one owner for the tag. The simplest owner is the script that applies the
70
+ saved theme before first paint: let it write `theme-color` and watch the
71
+ theme attribute it sets (for example `data-theme` on `<html>`), so framework
72
+ components never write the tag.
73
+
74
+ ## Runtime titles
75
+
76
+ Code that sets `document.title` after load, such as the name of an open
77
+ document, replaces the static title that crawlers which run JavaScript index.
78
+ Search for `document.title` before writing a static title. When the product
79
+ behavior must stay, use the form `<document> · <what the page is> · <brand>`;
80
+ the brand alone is not descriptive. Check whether the title callback is part
81
+ of a published API before changing it, and read the rendered title in a
82
+ headless browser after the app mounts, not at the load event.
83
+
84
+ ## Vite single-page apps
85
+
86
+ - Put static tags in `index.html`. For tier-conditional tags, use a plugin
87
+ hook such as `transformIndexHtml`, or `vite-plugin-html`'s `inject.tags`.
88
+ EJS scriptlets in `index.html` can break linters that parse HTML, such as
89
+ Biome.
90
+ - The public directory is copied before `writeBundle`, so a plugin can edit
91
+ the built `_headers` there. Insert into the existing `/*` rule.
92
+ - An extensionless relative import in `vite.config.ts` can trigger Vite's
93
+ native config loader warning; keep small plugins inline or use an explicit
94
+ extension.
95
+ - To give a client-routed site per-route metadata without a framework
96
+ change, list the routes once and write one copy of the app shell per route
97
+ (for example `company.html`) with that route's tags. Then switch the host to
98
+ a 404 page that is the same shell, so client routing still works. Every
99
+ routed path needs its own document, including flag-gated and nested routes,
100
+ or a reload of that path returns 404.
101
+ - Model the head tags once, render them at build time, and reapply them on
102
+ client navigation. Updating only `document.title` leaves a stale canonical,
103
+ description, and robots tag; reviewers rate that as a major finding.
104
+
105
+ ## Bun's HTML bundler
106
+
107
+ It leaves absolute canonical and Open Graph URLs and JSON-LD blocks
108
+ untouched, so static tags in the source HTML survive the build.
109
+
110
+ ## react-native-web
111
+
112
+ - The page is empty until the bundle runs; record that as a recommendation
113
+ when you cannot prerender a static summary.
114
+ - `accessibilityRole="header"` renders an `<h1>` with no visual change and
115
+ marks the heading for native screen readers.
116
+
117
+ ## Service workers
118
+
119
+ Apply tier-specific tags after the build but before the precache manifest
120
+ is generated, so the cached shell matches its tier.
121
+
122
+ ## Preview images with agent-tool
123
+
124
+ Render `og-image.png` with `agent-tool images` from `assets/brand/` sources:
125
+ an output with `"size": [1200, 630]`, a background or fill layer, and the logo
126
+ layer. The renderer loads no fonts, so the image cannot contain text unless
127
+ it is converted to paths. Choosing the target:
128
+
129
+ - Default to a separate target, such as `social`, beside `favicons`, and
130
+ follow `dir` targets when the repository already uses them.
131
+ - Extending an existing target is fine when only one package uses it and no
132
+ test ties it to the linked icons; a target shared by several packages
133
+ through `--out` would put the image in every package's build.
134
+ - Check service worker precache globs: a PNG in a precached `public/` folder
135
+ bloats the offline cache.
136
+ - `build --out <dir>` takes exactly one target and an absolute or
137
+ repository-relative directory. Repositories that ban committed binaries
138
+ render the image during the build, production only if it is tier-specific.
139
+
140
+ Sources must meet agent-tool's rules in its `docs/images.md`: `<title>`,
141
+ `<desc>`, and `<metadata>` are allowed, while `<style>`, `style` attributes,
142
+ text, and elements from editor namespaces are not. The practical test is
143
+ whether `agent-tool images build` succeeds. When the only logo is an editor
144
+ export that fails, record the needed plain SVG instead of rendering from it.
@@ -0,0 +1,219 @@
1
+ # Standard by host class
2
+
3
+ Read "Every host" and the sections for the host classes you found. Sources
4
+ worth opening when a rule matters:
5
+ [Google Search Central](https://developers.google.com/search/docs),
6
+ [robots meta and X-Robots-Tag](https://developers.google.com/search/docs/crawling-indexing/robots-meta-tag),
7
+ [canonical URLs](https://developers.google.com/search/docs/crawling-indexing/consolidate-duplicate-urls),
8
+ [sitemaps](https://www.sitemaps.org/protocol.html),
9
+ [structured data policies](https://developers.google.com/search/docs/appearance/structured-data/sd-policies),
10
+ and [the Open Graph protocol](https://ogp.me/).
11
+
12
+ ## Every host
13
+
14
+ - Every HTML page carries one `theme-color` that matches its top chrome, or
15
+ its background when it has no header, in each theme. When views differ, use
16
+ the first view a visitor sees, such as the sign-in page.
17
+ - When an in-app appearance toggle changes that color, the tag must follow it
18
+ at runtime, not only through `prefers-color-scheme` variants, and exactly
19
+ one piece of code may own it. This is browser chrome, not ranking: when
20
+ following an app's own theme system needs app UI work, record it as a
21
+ recommendation instead.
22
+ - Hosts that this repository's infrastructure binds but another repository
23
+ builds and deploys belong to that repository's pass.
24
+
25
+ ## Non-production tiers
26
+
27
+ A repository with only a production tier skips this section, but still
28
+ checks the platform's duplicate hosts, such as `*.workers.dev`.
29
+
30
+ - Send `X-Robots-Tag: noindex, nofollow` on every response, including assets,
31
+ fallbacks, error pages, redirects, and robots.txt. A non-production API host
32
+ that answers only JSON follows the API rule under
33
+ [Internal hosts](#internal-hosts).
34
+ - Put `<meta name="robots" content="noindex, nofollow">` in every HTML
35
+ document, so a copied or cached page still carries it.
36
+ - Keep robots.txt crawlable. A missing file or a comments-only managed file
37
+ already is; add or change a file only to remove a `Disallow`. A
38
+ `Disallow: /` stops crawlers from fetching pages, so they never see the
39
+ noindex and can still index a linked URL without its content.
40
+ - Emit no `<link rel="canonical">`, `og:url`, sitemap, or Sitemap line; those
41
+ tell crawlers which URL to index. Other preview tags and structured data may
42
+ stay, including `og:image` at the tier's own host or at production, so that
43
+ shared staging links still preview.
44
+ - A zone-level redirect, such as HTTP to HTTPS, is answered before the
45
+ application and cannot carry the header. Record it; the target carries the
46
+ header.
47
+ - Derive the tier from the mechanism the repository already uses, such as a
48
+ wrangler `env`, a build mode, or a release tier variable. Make the
49
+ production build the explicit choice, fail on an unknown tier, and test
50
+ both outcomes. When one artifact is promoted between tiers, apply the tier
51
+ at deploy time, for example by writing `_headers` per environment, rather
52
+ than breaking promotion.
53
+ - Leave an already-compliant tier unchanged after verifying it.
54
+
55
+ ## Content hosts
56
+
57
+ 1. **Static head.** The HTML served before JavaScript runs carries:
58
+ - a unique `<title>` that names what the page is, with the brand (the
59
+ product, or the person or site name on a personal site) last, kept under
60
+ about 60 characters;
61
+ - `<meta name="description">` of up to about 160 characters, written from
62
+ the page's own copy;
63
+ - `<link rel="canonical">` with the absolute production URL in the exact
64
+ form the host serves without redirecting (trailing slash or not);
65
+ - `<html lang>`, the viewport tag, and `theme-color`.
66
+
67
+ The lengths are limits on what search results show, not targets: a short
68
+ title that names a person or a page is fine, and padding with invented
69
+ copy is not. Shortening an over-long description by choosing from its own
70
+ sentences is a metadata edit; when it would need new wording, record it. A
71
+ page that sets its title only from JavaScript needs static or prerendered
72
+ metadata. When the app localizes text in the browser, localize a
73
+ descriptive `document.title` too.
74
+ 2. **Previews.** Add `og:type`, `og:site_name`, `og:title`,
75
+ `og:description`, `og:url` (equal to the canonical), `og:image` (an
76
+ absolute URL to a 1200×630 PNG), `og:image:width`, `og:image:height`,
77
+ `og:image:alt`, and `twitter:card` = `summary_large_image`. Twitter falls
78
+ back to the Open Graph title and description. Without a usable image, omit
79
+ `og:image` and use `twitter:card` = `summary`.
80
+ 3. **Structured data.** Add JSON-LD in `<script type="application/ld+json">`:
81
+ - `WebSite` on every content host's home page, and `Organization` when the
82
+ site names its publisher;
83
+ - `SoftwareApplication` or `WebApplication` for a product, with
84
+ `operatingSystem` listing only platforms a visitor can use today and
85
+ `offers` only for prices the site already states;
86
+ - `Person` for a resume, using only facts on the page.
87
+
88
+ Escape `<` inside the JSON, and parse it in a test. Never add ratings or
89
+ reviews that are not on the page.
90
+ 4. **robots.txt.** Serve a real `text/plain` file with `User-agent: *`,
91
+ `Allow: /`, any deliberate existing rules, and
92
+ `Sitemap: https://<host>/sitemap.xml`. Keep earlier directives that had an
93
+ effect, such as AI-crawler rules or `Content-Signal` lines, unless the user
94
+ decides otherwise.
95
+ 5. **Sitemap.** List the absolute canonical URL of every indexable page and
96
+ nothing else: no error pages, redirects, placeholder pages, or
97
+ non-production hosts. Generating it from the canonical links in the built
98
+ HTML keeps the two from drifting.
99
+ 6. **Status codes.** An unknown path returns 404 with a helpful page when the
100
+ platform allows it; an empty 404 body is a gap. Do not remove a fallback
101
+ that client-side routing or old-link redirects depend on; record the soft
102
+ 404 instead. The site should redirect `http://` to `https://`; when that is
103
+ a CDN or zone setting, record it.
104
+ 7. **Error page.** The same error page is served at any depth, so its links
105
+ and assets need root-relative paths. Hosts often answer its own path (such
106
+ as `/404`) with 200, so give it a robots noindex and no canonical, `og:url`,
107
+ or sitemap entry; it is the one production page that carries noindex.
108
+ Leave analytics off it when it can answer under paths with stricter privacy
109
+ promises (a zone may still inject its own), and make the local development
110
+ server answer missing paths the same way.
111
+ 8. **Internal links.** Every link to the site's own pages uses the canonical
112
+ form, so following it answers 200 without a redirect;
113
+ `agent-tool seo probe --links` finds the others. Add a build test that
114
+ fails on a link that would redirect or miss, generating any gitignored
115
+ build assets it reads first.
116
+ Changing link forms can break code that compares links with the current
117
+ path, such as an active-page marker. Shared link constants in other
118
+ packages count too, and changing them can require those packages' version
119
+ bumps.
120
+ 9. **Hygiene on touched pages.** One `<h1>` that names the page (not one
121
+ shared by a whole gallery), meaningful `alt` text on content images, and
122
+ descriptive link text. On image-heavy pages, keep only the likely Largest
123
+ Contentful Paint image eager, with `fetchpriority="high"`, and lazy-load
124
+ the rest with explicit `width` and `height`.
125
+ 10. **Manifest.** Where a web app manifest exists, make the name, short name,
126
+ description, icons, colors, `start_url`, and `display` accurate. Add
127
+ `related_applications` only after the store listings exist.
128
+ 11. **Copied pages.** When a site serves copies of another project's pages,
129
+ for example from a package's asset folder, the copies should canonicalize
130
+ to the original host. That is the producer's change: absolute canonical
131
+ and `og:url` values in the pages it ships. On the consuming side, upgrade
132
+ to a release whose tarball you have checked for the change, and review
133
+ the API between the old and new versions first. Copies of pages that are
134
+ deliberately kept out of search keep the producer's robots rules, but
135
+ their assets can still be indexed: add a path-scoped `X-Robots-Tag` rule
136
+ for the copied directory in production, where no `/*` rule already sends
137
+ it, and respect any deploy guard the consumer has. Probe asset paths under
138
+ the copy, not only its pages.
139
+
140
+ Paths on a content host that are not meant for search, such as review or
141
+ preview pages, get the internal-host treatment: the header, the robots meta,
142
+ and no sitemap entry. Placeholder pages without real copy do too, through a
143
+ flag on the page, so a page becomes indexable and joins the sitemap as soon
144
+ as it gets content.
145
+
146
+ When several sites belong to one company, give them the same `Organization`
147
+ node, with the same `@id`, name, legal name, URL, and logo, and point
148
+ `publisher` or `provider` at that `@id`.
149
+
150
+ ## App hosts
151
+
152
+ - Replace a generic shell title such as "App" with the product name and what
153
+ it is, for example "Tearleads – Encrypted notes, contacts, and files". Add a
154
+ description and Open Graph tags.
155
+ - Reuse the product's preview image by pointing `og:image` at the content
156
+ host's absolute URL rather than rendering a second copy, and deploy the
157
+ content host first when the image changes. Requesting the image path on the
158
+ app host itself may return the shell; check the URL the page names.
159
+ - Serve a real `text/plain` robots.txt. A single-page fallback otherwise
160
+ answers it with HTML.
161
+ - Add a canonical pointing at the app root only when every route shows the
162
+ same shell. When the app has distinct public, shareable routes, such as user
163
+ pages or published documents, a root canonical marks them as duplicates.
164
+ Omit the canonical and record whether those routes should be indexable. That
165
+ is a product and privacy decision, because sharing by link is not consent to
166
+ search listing.
167
+ - A host that serves a duplicate of another host's app, such as a demo build,
168
+ canonicalizes to the primary app root.
169
+ - Once the product owner decides that public user-content routes stay out
170
+ of search, noindex them with a path rule. If those routes cannot be told
171
+ apart from app routes by URL pattern (for example `/:user` and `/admin`),
172
+ send the header on every path below the root, detach it on built files,
173
+ and keep the root indexable; say so in the report, because it also covers
174
+ app routes. Add the robots meta in the view as well, never twice. Without
175
+ that decision, record the question instead of noindexing anything.
176
+ - Private links that work without an account, such as signing or sharing
177
+ URLs with a token, get `X-Robots-Tag: noindex, nofollow` through a path
178
+ rule, while the rest of the app keeps its canonical. Files those pages link
179
+ to on an API host, such as PDF downloads, should carry the header too.
180
+ - The content-host rule for localized titles applies to app hosts that
181
+ localize in the browser.
182
+
183
+ ## Internal hosts
184
+
185
+ Admin dashboards, galleries, package viewer sites, and other HTML surfaces
186
+ that are not meant for search follow every non-production rule above: the
187
+ header (`noindex, nofollow`) on every response, including server-generated
188
+ redirects and sign-in pages; the robots meta in the HTML; a crawlable
189
+ robots.txt; and no canonical, `og:url`, or sitemap. Empty preview and
190
+ structured-data results are expected on these hosts.
191
+
192
+ - API hosts that answer only JSON need nothing unless adding the header is
193
+ trivial and leaves CORS and other behavior unchanged. On any tier, files
194
+ they serve behind private links do need it.
195
+ - An existing `noindex` robots meta can stay as it is; the header carries
196
+ `nofollow`. Do not change meta tags in pages that a package ships for other
197
+ sites to copy, because the copies take them along. Keep host-only files such
198
+ as `_headers` out of the package.
199
+ - A host with one tier has no tier switch to test. Test that every page has
200
+ the robots meta and no canonical, and that the header is present: the rule
201
+ in the deployed build for static assets, or a unit test of the wrapper when
202
+ a Worker sets it in code. In a repository that also publishes the pages as
203
+ a package, test that the package leaves the host-only header file out.
204
+ - When the repository has a verification script or a documented post-deploy
205
+ check for the site, add the live header check there. Do not add SEO checks
206
+ to gates for other releases, such as a package publishing gate.
207
+
208
+ ## Apps that will ship to stores
209
+
210
+ Until the store listings are live, list only `Web` in `operatingSystem`, and
211
+ do not add smart app banners, `related_applications`, or new links to store
212
+ pages that answer 404. Existing store links may reflect an owner's decision,
213
+ so search the PR history and record a conflict rather than removing them.
214
+
215
+ Record what the launch needs: the App Store ID for `apple-itunes-app`, the
216
+ Play package for `related_applications`, store links in static HTML, offers
217
+ that match the listing, and, only if deep links are wanted,
218
+ `apple-app-site-association` (Team ID and bundle ID) and `assetlinks.json`
219
+ (the Play app signing certificate's SHA-256).
package/src/cli.ts CHANGED
@@ -6,6 +6,7 @@ import { checkTerraformPlan } from "./dependencies/terraformPlan";
6
6
  import { dependencyDiff } from "./dependencies/diff";
7
7
  import { checkGraph } from "./graph/check";
8
8
  import { stateMachinesCommand } from "./stateMachines/command";
9
+ import { seoCommand } from "./seo/probe";
9
10
  import { buildScreenshots, describeScreenshots } from "./screenshots/build";
10
11
  import { review } from "./harnesses";
11
12
  import { carryReviewCommand } from "./review/carry";
@@ -93,6 +94,7 @@ Usage: agent-tool [--repo <directory>] [--config <file>] <command>
93
94
  screenshots build [target...] [--out <dir>] [--json] Stage guarded captures and a gallery manifest
94
95
  graph check Import cycles and layer violations per agent-tool.json
95
96
  state-machines [path...] [--limit N] [--min-score N] [--json] Rank files that look like implicit state machines
97
+ seo probe [--page|--headers|--links|--sitemap] <host> [path...] Live search and preview metadata of a site
96
98
  init Create agent-tool.json without overwriting
97
99
  config show
98
100
  doctor JSON versions and supported review flags
@@ -191,6 +193,7 @@ export function main(argv = process.argv.slice(2)): number | Promise<number> {
191
193
  output(report); return report.ok ? 0 : 1;
192
194
  }
193
195
  if (command === "state-machines") return stateMachinesCommand(args, process.cwd(), undefined, invoked);
196
+ if (command === "seo") return seoCommand(args);
194
197
  if (command === "skills") {
195
198
  const action = args.shift();
196
199
  if (action === "list") { usage(args.length === 0, "Usage: agent-tool skills list"); output(Object.keys(BUNDLED_SKILLS)); return 0; }
@@ -41,6 +41,7 @@ export const CATALOG: CatalogEntry[] = [
41
41
  { command: "openPr", class: "share" },
42
42
  ];
43
43
  // `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 hosts its arguments and fetched pages name, like curl, so it keeps the harness default too.
44
45
  // `bun x` runs only executables that `permissions.executables` classifies; project.ts adds those.
45
46
  // Package scripts are not classified, so `bun run` keeps the harness default.
46
47
 
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Regular-expression readers for `seo probe`, over HTML with its newlines,
3
+ * carriage returns, and tabs collapsed to spaces. They match the way the
4
+ * original shell probe's `grep -oiE` pipelines did: double-quoted attributes
5
+ * only, first match or every match in document order, and no HTML parser, so
6
+ * a surprising result needs a look at the raw response.
7
+ */
8
+
9
+ /** The body as one line: `\n`, `\r`, and `\t` become spaces. */
10
+ export function collapse(body: string): string {
11
+ return body.replace(/[\n\r\t]/g, " ");
12
+ }
13
+
14
+ const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
15
+
16
+ /** Every case-insensitive match of `pattern` in `text`, in order. */
17
+ export function matches(text: string, pattern: string): string[] {
18
+ return [...text.matchAll(new RegExp(pattern, "gi"))].map(match => match[0]);
19
+ }
20
+
21
+ /** The first case-insensitive match, or "". */
22
+ export function first(text: string, pattern: string): string {
23
+ return new RegExp(pattern, "i").exec(text)?.[0] ?? "";
24
+ }
25
+
26
+ /** Distinct matches in code-unit order, each followed by one space. */
27
+ export function names(text: string, pattern: string): string {
28
+ return [...new Set(matches(text, pattern))].sort().map(name => `${name} `).join("");
29
+ }
30
+
31
+ /** Every `name="value"` value in `text`, in order. */
32
+ export function attrValues(text: string, name: string): string[] {
33
+ return matches(text, `${escapeRegExp(name)}="[^"]*"`).map(match => match.slice(match.indexOf('"') + 1, -1));
34
+ }
35
+
36
+ /** The same values, one per line. */
37
+ export const attr = (text: string, name: string) => attrValues(text, name).join("\n");
38
+
39
+ /** Decode the predefined XML entities; `&amp;` goes last so `&amp;lt;` stays `&lt;`. */
40
+ export function unescape(value: string): string {
41
+ return value.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&#39;/g, "'").replace(/&amp;/g, "&");
42
+ }
43
+
44
+ /** The content of the first `<meta>` whose property or name is `key`. */
45
+ export function contentOf(body: string, key: string): string {
46
+ return attr(first(body, `<meta[^>]+(property|name)="${escapeRegExp(key)}"[^>]*>`), "content");
47
+ }
48
+
49
+ /** Every robots and googlebot meta directive, lowercase, joined with spaces. */
50
+ export function robotsMeta(body: string): string {
51
+ return matches(body, '<meta[^>]+name="(robots|googlebot)"[^>]*>').flatMap(tag => attrValues(tag, "content")).join(" ").toLowerCase();
52
+ }
53
+
54
+ export function titleOf(body: string): string {
55
+ return first(body, "<title[^>]*>[^<]*</title>").replace(/<[^>]*>/g, "");
56
+ }
57
+
58
+ export function canonicalOf(body: string): string {
59
+ return unescape(attr(first(body, '<link[^>]+rel="canonical"[^>]*>'), "href"));
60
+ }
61
+
62
+ /** The `<loc>` values of a sitemap, trimmed and decoded. */
63
+ export function locs(body: string): string[] {
64
+ return [...collapse(body).matchAll(/<loc>[^<]+<\/loc>/g)].map(match => unescape(match[0].replace(/<\/?loc>/g, "").replace(/^ +/, "").replace(/ +$/, "")));
65
+ }
66
+
67
+ /** A sitemap or sitemap index document, by its root element. */
68
+ export const isSitemapDocument = (body: string) => /<(?:urlset|sitemapindex)(?:[\s>]|$)/m.test(body);
69
+
70
+ /** A PNG's `WIDTHxHEIGHT` from its IHDR chunk, or "" for anything else. */
71
+ export function pngSize(bytes: Uint8Array): string {
72
+ const signature = [0x50, 0x4e, 0x47]; // "PNG", which follows the first byte of the signature
73
+ const isPng = [0, 1, 2, 3, 4, 5].some(start => signature.every((byte, index) => bytes[start + index] === byte));
74
+ if (!isPng || bytes.length < 24) return "";
75
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
76
+ return `${view.getUint32(16)}x${view.getUint32(20)}`;
77
+ }
78
+
79
+ /** The first 220 characters of each line. */
80
+ export const clip = (value: string) => value.split("\n").map(line => [...line].slice(0, 220).join("")).join("\n");
81
+
82
+ /** Character count, as a UTF-8 shell counts `${#value}`. */
83
+ export const length = (value: string) => [...value].length;
84
+
85
+ /** Lines as `grep` reads them: a trailing newline ends the last line rather than starting another. */
86
+ export function lines(text: string): string[] {
87
+ const all = text.split("\n");
88
+ if (all.at(-1) === "") all.pop();
89
+ return all;
90
+ }
91
+
92
+ /**
93
+ * Resolve a relative reference (no scheme, not protocol-relative) against the
94
+ * final document path: a query-only reference against the page itself, any
95
+ * other against its directory, with `.`, `..`, and empty segments removed. A
96
+ * trailing slash, or a final `.` or `..`, keeps the directory form.
97
+ */
98
+ export function resolvePath(reference: string, page: string): string {
99
+ let target = reference.startsWith("?") ? page + reference
100
+ : reference.startsWith("/") ? reference
101
+ : `${page.slice(0, page.lastIndexOf("/"))}/${reference}`;
102
+ let query = "";
103
+ const mark = target.indexOf("?");
104
+ if (mark >= 0) { query = target.slice(mark); target = target.slice(0, mark); }
105
+ const parts = target.split("/");
106
+ const stack: string[] = [];
107
+ for (const part of parts.slice(1)) {
108
+ if (part === "." || part === "") continue;
109
+ if (part === "..") stack.pop();
110
+ else stack.push(part);
111
+ }
112
+ let resolved = stack.map(part => `/${part}`).join("") || "/";
113
+ const last = parts.at(-1);
114
+ if ((target.endsWith("/") || last === "." || last === "..") && resolved !== "/") resolved += "/";
115
+ return resolved + query;
116
+ }
117
+
118
+ /**
119
+ * The page's links to its own host, as URLs to request: absolute ones exactly
120
+ * as written, protocol-relative ones with the page's scheme, and relative ones
121
+ * resolved against the final document URL rather than a `<base>`. Fragments are
122
+ * dropped; the result is sorted and distinct.
123
+ */
124
+ export function internalLinks(body: string, finalUrl: URL): string[] {
125
+ const origin = `${finalUrl.protocol}//${finalUrl.host}`;
126
+ const host = escapeRegExp(finalUrl.host);
127
+ const hrefs = matches(body, '<a[^>]+href="[^"]*"')
128
+ .flatMap(tag => attrValues(tag, "href"))
129
+ .map(href => unescape(href).replace(/#.*/, ""))
130
+ .filter(href => href !== "");
131
+ const links = new Set<string>();
132
+ for (const href of hrefs) {
133
+ if (new RegExp(`^https?://${host}([/?]|$)`, "i").test(href)) links.add(href);
134
+ else if (new RegExp(`^//${host}([/?]|$)`, "i").test(href)) links.add(`${finalUrl.protocol}${href}`);
135
+ else if (!/^[a-zA-Z][a-zA-Z0-9+.-]*:|^\/\//.test(href)) links.add(origin + resolvePath(href, finalUrl.pathname));
136
+ }
137
+ return [...links].sort();
138
+ }
@@ -0,0 +1,124 @@
1
+ /**
2
+ * The requests `seo probe` makes: one GET at a time with Bun's `fetch`, which
3
+ * honors the proxy variables a sandboxed harness sets. Only `http:` and `https:`
4
+ * URLs are ever requested, including redirect targets, because URLs come from
5
+ * remote markup (`og:image`, sitemap entries, links, `Location`), and `fetch`
6
+ * itself would also read `file:` and `s3:` URLs. Redirects are followed by hand
7
+ * so each hop is checked and the first one can be reported.
8
+ */
9
+
10
+ export interface Reply {
11
+ /** The URL requested. */
12
+ url: string;
13
+ /** The three-digit status, or "000" when no response arrived (curl's `%{http_code}`). */
14
+ code: string;
15
+ /** For a 3xx with a `Location`, the absolute URL it names (curl's `%{redirect_url}`); otherwise "". */
16
+ location: string;
17
+ /** The `Content-Type` header as sent, or "". */
18
+ contentType: string;
19
+ /** Every `X-Robots-Tag` value; HTTP joins repeated header lines with ", ". */
20
+ robotsTag: string;
21
+ body: Uint8Array;
22
+ /** Why no response arrived, for an unreachable host. */
23
+ error?: string;
24
+ }
25
+
26
+ export interface Followed { first: Reply; final: Reply }
27
+
28
+ export interface RequestOptions {
29
+ userAgent: string;
30
+ /** Seconds for the whole request, every redirect included, like curl's `-m`. */
31
+ seconds: number;
32
+ /** Read the body; false cancels it once the headers arrive. */
33
+ body?: boolean;
34
+ }
35
+
36
+ /** curl's default `--max-redirs` with `-L`. */
37
+ const MAX_REDIRECTS = 50;
38
+ /** A body is cut here, so a hostile URL cannot exhaust memory; a sitemap may be 50 MB. */
39
+ const MAX_BODY_BYTES = 64 * 1024 * 1024;
40
+
41
+ const EMPTY: Uint8Array = new Uint8Array();
42
+ const failed = (url: string, error: string): Reply => ({ url, code: "000", location: "", contentType: "", robotsTag: "", body: EMPTY, error });
43
+
44
+ /** The URL when it is HTTP or HTTPS, else null. */
45
+ function webUrl(target: string): URL | null {
46
+ try {
47
+ const url = new URL(target);
48
+ return url.protocol === "http:" || url.protocol === "https:" ? url : null;
49
+ } catch { return null; }
50
+ }
51
+
52
+ async function readBody(response: Response): Promise<Uint8Array> {
53
+ const reader = response.body?.getReader();
54
+ if (!reader) return EMPTY;
55
+ const chunks: Uint8Array[] = [];
56
+ let size = 0;
57
+ try {
58
+ for (;;) {
59
+ const { done, value } = await reader.read();
60
+ if (done) break;
61
+ chunks.push(value);
62
+ size += value.byteLength;
63
+ if (size >= MAX_BODY_BYTES) { await reader.cancel(); break; }
64
+ }
65
+ } catch {
66
+ // A timeout or reset mid-body keeps what arrived, as curl's output file does.
67
+ }
68
+ const body = new Uint8Array(Math.min(size, MAX_BODY_BYTES));
69
+ let offset = 0;
70
+ for (const chunk of chunks) {
71
+ const part = chunk.subarray(0, body.length - offset);
72
+ body.set(part, offset);
73
+ offset += part.length;
74
+ if (offset === body.length) break;
75
+ }
76
+ return body;
77
+ }
78
+
79
+ async function get(target: string, options: RequestOptions, deadline: number): Promise<Reply> {
80
+ const url = webUrl(target);
81
+ if (!url) return failed(target, `refused a URL that is not HTTP or HTTPS: ${target}`);
82
+ const remaining = deadline - performance.now();
83
+ if (remaining <= 0) return failed(target, `timed out after ${options.seconds} seconds`);
84
+ try {
85
+ const response = await fetch(url, {
86
+ redirect: "manual",
87
+ // curl's defaults: no compression, any type.
88
+ headers: { "user-agent": options.userAgent, accept: "*/*", "accept-encoding": "identity" },
89
+ signal: AbortSignal.timeout(remaining),
90
+ });
91
+ const code = String(response.status).padStart(3, "0");
92
+ const raw = response.headers.get("location");
93
+ let location = "";
94
+ if (raw !== null && response.status >= 300 && response.status < 400) {
95
+ try { location = new URL(raw, url).href; } catch { location = raw; }
96
+ }
97
+ let body: Uint8Array = EMPTY;
98
+ if (options.body === false) await response.body?.cancel();
99
+ else body = await readBody(response);
100
+ return { url: target, code, location, contentType: response.headers.get("content-type") ?? "", robotsTag: response.headers.get("x-robots-tag") ?? "", body };
101
+ } catch (error) {
102
+ return failed(target, error instanceof Error ? error.message : String(error));
103
+ }
104
+ }
105
+
106
+ /** One request; redirects are reported, not followed. */
107
+ export function request(target: string, options: RequestOptions): Promise<Reply> {
108
+ return get(target, options, performance.now() + options.seconds * 1000);
109
+ }
110
+
111
+ /**
112
+ * Follow redirects (not 304) up to curl's limit within one deadline. The final
113
+ * reply is the last response received; a redirect to a refused scheme ends the
114
+ * chain at that redirect, and a hop that gets no response ends it with "000".
115
+ */
116
+ export async function follow(target: string, options: RequestOptions): Promise<Followed> {
117
+ const deadline = performance.now() + options.seconds * 1000;
118
+ const first = await get(target, options, deadline);
119
+ let final = first;
120
+ for (let hops = 0; hops < MAX_REDIRECTS && final.location && final.code !== "304" && webUrl(final.location); hops++) {
121
+ final = await get(final.location, options, deadline);
122
+ }
123
+ return { first, final };
124
+ }