nfunc-mcp 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +84 -376
  2. package/dist/index.js +4 -0
  3. package/dist/index.js.map +1 -1
  4. package/dist/mappers/labFieldComparator.d.ts +62 -0
  5. package/dist/mappers/labFieldComparator.js +134 -0
  6. package/dist/mappers/labFieldComparator.js.map +1 -0
  7. package/dist/mappers/psiAggregator.d.ts +130 -0
  8. package/dist/mappers/psiAggregator.js +293 -0
  9. package/dist/mappers/psiAggregator.js.map +1 -0
  10. package/dist/mappers/webVitalsMapper.d.ts +52 -0
  11. package/dist/mappers/webVitalsMapper.js +131 -0
  12. package/dist/mappers/webVitalsMapper.js.map +1 -0
  13. package/dist/tools/performanceAudit.d.ts +2 -0
  14. package/dist/tools/performanceAudit.js +446 -0
  15. package/dist/tools/performanceAudit.js.map +1 -0
  16. package/dist/tools/performanceAuditPlan.d.ts +2 -0
  17. package/dist/tools/performanceAuditPlan.js +438 -0
  18. package/dist/tools/performanceAuditPlan.js.map +1 -0
  19. package/dist/utils/csvReader.d.ts +20 -0
  20. package/dist/utils/csvReader.js +172 -0
  21. package/dist/utils/csvReader.js.map +1 -0
  22. package/dist/utils/httpClient.d.ts +84 -0
  23. package/dist/utils/httpClient.js +171 -0
  24. package/dist/utils/httpClient.js.map +1 -0
  25. package/dist/utils/psiAuth.d.ts +26 -0
  26. package/dist/utils/psiAuth.js +36 -0
  27. package/dist/utils/psiAuth.js.map +1 -0
  28. package/dist/utils/psiParser.d.ts +124 -0
  29. package/dist/utils/psiParser.js +200 -0
  30. package/dist/utils/psiParser.js.map +1 -0
  31. package/dist/utils/publicUrl.d.ts +17 -0
  32. package/dist/utils/publicUrl.js +115 -0
  33. package/dist/utils/publicUrl.js.map +1 -0
  34. package/dist/utils/sitemapReader.d.ts +27 -0
  35. package/dist/utils/sitemapReader.js +272 -0
  36. package/dist/utils/sitemapReader.js.map +1 -0
  37. package/dist/utils/urlClassifier.d.ts +45 -0
  38. package/dist/utils/urlClassifier.js +267 -0
  39. package/dist/utils/urlClassifier.js.map +1 -0
  40. package/docs/manual.md +558 -0
  41. package/docs/psi-report-spec.md +174 -0
  42. package/package.json +13 -3
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Whether PSI can reach a URL at all.
3
+ *
4
+ * PSI fetches the target from Google's own infrastructure, so "can I open this
5
+ * in my browser" is not the test — the page has to be reachable from the
6
+ * public internet. Localhost and RFC1918 addresses are not degraded cases that
7
+ * return partial data; they cannot be audited, full stop, and the only useful
8
+ * response is to say so before spending a request finding out.
9
+ */
10
+ export type ReachVerdict = "public" | "loopback" | "private" | "non_http" | "malformed";
11
+ export interface ReachResult {
12
+ verdict: ReachVerdict;
13
+ auditable: boolean;
14
+ reason?: string;
15
+ }
16
+ export declare function checkPublicReachability(rawUrl: string): ReachResult;
17
+ export declare function isSessionGated(rawUrl: string): boolean;
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Whether PSI can reach a URL at all.
3
+ *
4
+ * PSI fetches the target from Google's own infrastructure, so "can I open this
5
+ * in my browser" is not the test — the page has to be reachable from the
6
+ * public internet. Localhost and RFC1918 addresses are not degraded cases that
7
+ * return partial data; they cannot be audited, full stop, and the only useful
8
+ * response is to say so before spending a request finding out.
9
+ */
10
+ /** IPv4 in a private or link-local range, per RFC1918 / RFC3927. */
11
+ function isPrivateIPv4(host) {
12
+ const parts = host.split(".");
13
+ if (parts.length !== 4)
14
+ return false;
15
+ const [a, b] = parts.map(Number);
16
+ if (parts.some((p) => !/^\d+$/.test(p)) || [a, b].some(Number.isNaN))
17
+ return false;
18
+ if (a === 10)
19
+ return true;
20
+ if (a === 172 && b >= 16 && b <= 31)
21
+ return true;
22
+ if (a === 192 && b === 168)
23
+ return true;
24
+ if (a === 169 && b === 254)
25
+ return true; // link-local
26
+ if (a === 100 && b >= 64 && b <= 127)
27
+ return true; // CGNAT
28
+ return false;
29
+ }
30
+ function isLoopback(host) {
31
+ if (host === "localhost" || host.endsWith(".localhost"))
32
+ return true;
33
+ if (host === "::1" || host === "[::1]")
34
+ return true;
35
+ return /^127\./.test(host);
36
+ }
37
+ /**
38
+ * Hostnames that never resolve on the public internet. `.local` is mDNS,
39
+ * `.internal` and `.test`/`.invalid` are reserved, and a bare hostname with no
40
+ * dot is a LAN name.
41
+ */
42
+ function isNonPublicName(host) {
43
+ if (/\.(local|internal|localdomain|test|invalid|example)$/.test(host))
44
+ return true;
45
+ return !host.includes(".") && !/^\d+$/.test(host);
46
+ }
47
+ export function checkPublicReachability(rawUrl) {
48
+ let url;
49
+ try {
50
+ url = new URL(rawUrl);
51
+ }
52
+ catch {
53
+ return { verdict: "malformed", auditable: false, reason: `"${rawUrl}" is not a valid URL.` };
54
+ }
55
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
56
+ return {
57
+ verdict: "non_http",
58
+ auditable: false,
59
+ reason: `PSI only audits http(s) URLs; got "${url.protocol}".`,
60
+ };
61
+ }
62
+ const host = url.hostname.toLowerCase();
63
+ if (isLoopback(host)) {
64
+ return {
65
+ verdict: "loopback",
66
+ auditable: false,
67
+ reason: "PSI fetches pages from Google's infrastructure, so it cannot reach " +
68
+ "localhost. Use run_lighthouse, which runs Chrome on this machine.",
69
+ };
70
+ }
71
+ if (isPrivateIPv4(host)) {
72
+ return {
73
+ verdict: "private",
74
+ auditable: false,
75
+ reason: `${host} is a private-network address and is not reachable from ` +
76
+ "Google's infrastructure. Use run_lighthouse for internal hosts.",
77
+ };
78
+ }
79
+ if (isNonPublicName(host)) {
80
+ return {
81
+ verdict: "private",
82
+ auditable: false,
83
+ reason: `"${host}" is not a publicly resolvable hostname. Use run_lighthouse ` +
84
+ "for hosts that only resolve on your network.",
85
+ };
86
+ }
87
+ return { verdict: "public", auditable: true };
88
+ }
89
+ /**
90
+ * Paths that PSI can fetch but cannot meaningfully audit, because an anonymous
91
+ * request does not see the real page.
92
+ *
93
+ * PSI has no session: it audits an empty cart, a redirect to a login form, or
94
+ * a search page with no query, and reports the result as if it were the page
95
+ * someone asked about. A confidently wrong number is worse than a gap, so
96
+ * these are flagged rather than run. `run_lighthouse` can carry cookies and is
97
+ * the right tool for them.
98
+ */
99
+ const SESSION_GATED = [
100
+ /(^|\/)(cart|basket|bag)(\/|$)/,
101
+ /(^|\/)(checkout|payment|order-confirmation)(\/|$)/,
102
+ /(^|\/)(account|my-account|profile|dashboard|orders)(\/|$)/,
103
+ /(^|\/)(login|signin|sign-in|register|signup|sign-up|logout)(\/|$)/,
104
+ /(^|\/)(wishlist|favorites|favourites|saved)(\/|$)/,
105
+ ];
106
+ export function isSessionGated(rawUrl) {
107
+ try {
108
+ const path = new URL(rawUrl).pathname.toLowerCase();
109
+ return SESSION_GATED.some((re) => re.test(path));
110
+ }
111
+ catch {
112
+ return false;
113
+ }
114
+ }
115
+ //# sourceMappingURL=publicUrl.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"publicUrl.js","sourceRoot":"","sources":["../../src/utils/publicUrl.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAUH,oEAAoE;AACpE,SAAS,aAAa,CAAC,IAAY;IACjC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC9B,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACrC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACjC,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACnF,IAAI,CAAC,KAAK,EAAE;QAAE,OAAO,IAAI,CAAC;IAC1B,IAAI,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E,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IACnD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Sitemap discovery.
3
+ *
4
+ * The cheapest honest way to learn which pages a site has. A sitemap is
5
+ * authoritative (the site published it), instant (one or two requests), and
6
+ * needs no crawling, no robots.txt politeness budget and no HTML parsing. A
7
+ * crawler is the fallback for sites without one, and is deliberately not built
8
+ * yet — everything downstream works without it.
9
+ *
10
+ * Sitemaps are parsed with regular expressions rather than an XML library.
11
+ * That is normally a mistake, but a sitemap is a machine-generated document
12
+ * with a fixed two-element vocabulary, and the alternative is a dependency
13
+ * carried by every install of this server for one code path. The parser reads
14
+ * <loc> only and ignores everything else, so malformed markup degrades to
15
+ * fewer URLs rather than to wrong ones.
16
+ */
17
+ export interface SitemapResult {
18
+ urls: string[];
19
+ /** Every sitemap document actually fetched, in order. */
20
+ sitemapsRead: string[];
21
+ /** True when a cap stopped the walk early — the URL list is a subset. */
22
+ truncated: boolean;
23
+ /** Every location tried, so a failure can say what was ruled out. */
24
+ attempted: string[];
25
+ warnings: string[];
26
+ }
27
+ export declare function readSitemap(origin: string): Promise<SitemapResult>;
@@ -0,0 +1,272 @@
1
+ /**
2
+ * Sitemap discovery.
3
+ *
4
+ * The cheapest honest way to learn which pages a site has. A sitemap is
5
+ * authoritative (the site published it), instant (one or two requests), and
6
+ * needs no crawling, no robots.txt politeness budget and no HTML parsing. A
7
+ * crawler is the fallback for sites without one, and is deliberately not built
8
+ * yet — everything downstream works without it.
9
+ *
10
+ * Sitemaps are parsed with regular expressions rather than an XML library.
11
+ * That is normally a mistake, but a sitemap is a machine-generated document
12
+ * with a fixed two-element vocabulary, and the alternative is a dependency
13
+ * carried by every install of this server for one code path. The parser reads
14
+ * <loc> only and ignores everything else, so malformed markup degrades to
15
+ * fewer URLs rather than to wrong ones.
16
+ */
17
+ import { gunzipSync } from "node:zlib";
18
+ import { httpGet } from "./httpClient.js";
19
+ /** A sitemap index can point at hundreds of children; walking all of them is rarely worth it. */
20
+ const MAX_SITEMAPS = 25;
21
+ const MAX_URLS = 50_000;
22
+ const FETCH_TIMEOUT_MS = 20_000;
23
+ const LOC_RE = /<loc>\s*([^<\s][^<]*?)\s*<\/loc>/gi;
24
+ function decodeXmlEntities(value) {
25
+ return value
26
+ .replace(/&lt;/g, "<")
27
+ .replace(/&gt;/g, ">")
28
+ .replace(/&quot;/g, '"')
29
+ .replace(/&apos;/g, "'")
30
+ .replace(/&#(\d+);/g, (_, d) => String.fromCharCode(Number(d)))
31
+ // Ampersand last, so "&amp;lt;" does not become "<".
32
+ .replace(/&amp;/g, "&");
33
+ }
34
+ function extractLocs(xml) {
35
+ const out = [];
36
+ for (const match of xml.matchAll(LOC_RE)) {
37
+ const loc = decodeXmlEntities(match[1].trim());
38
+ if (loc)
39
+ out.push(loc);
40
+ }
41
+ return out;
42
+ }
43
+ /** A <sitemapindex> points at more sitemaps; a <urlset> holds pages. */
44
+ function isSitemapIndex(xml) {
45
+ return /<sitemapindex[\s>]/i.test(xml);
46
+ }
47
+ /**
48
+ * Sitemap locations declared in robots.txt.
49
+ *
50
+ * Large sites frequently do not serve /sitemap.xml and only announce the real
51
+ * location here, so checking robots first turns a "no sitemap found" dead end
52
+ * into a hit. It is also the polite thing to read before touching a site.
53
+ */
54
+ async function sitemapsFromRobots(origin) {
55
+ const robotsUrl = new URL("/robots.txt", origin).toString();
56
+ const result = await httpGet(robotsUrl, { timeoutMs: 10_000, retries: 1 });
57
+ if (!result.ok)
58
+ return [];
59
+ const found = [];
60
+ for (const line of result.body.split(/\r?\n/)) {
61
+ const match = /^\s*sitemap:\s*(\S+)/i.exec(line);
62
+ if (match)
63
+ found.push(match[1]);
64
+ }
65
+ return found;
66
+ }
67
+ /**
68
+ * Non-HTML entries a performance audit should never spend a PSI call on.
69
+ * Image and video sitemaps are common and would otherwise fill the sample.
70
+ */
71
+ function looksAuditable(url) {
72
+ return !/\.(jpe?g|png|gif|webp|avif|svg|ico|pdf|zip|gz|mp4|webm|mp3|xml|json|txt|css|js)(\?|$)/i.test(url);
73
+ }
74
+ /**
75
+ * Sitemap locations worth guessing, beyond the two standard ones.
76
+ *
77
+ * Ordered by how often they pay off. These only run when the standard
78
+ * locations and robots.txt have produced nothing, so the common case still
79
+ * costs one or two requests — a 404 from Google's edge is cheap, but seven of
80
+ * them on every audit would not be.
81
+ */
82
+ const CANDIDATE_PATHS = [
83
+ "/sitemap-index.xml",
84
+ "/sitemap/sitemap.xml",
85
+ "/sitemap/index.xml",
86
+ "/wp-sitemap.xml", // WordPress 5.5+
87
+ "/sitemap_index.xml.gz",
88
+ "/sitemap1.xml",
89
+ "/sitemap.txt", // plain text, one URL per line
90
+ ];
91
+ /**
92
+ * `<link rel="sitemap">` in the homepage head.
93
+ *
94
+ * Rare but authoritative when present, and it costs one request we can often
95
+ * justify anyway. Only consulted after the cheaper guesses fail.
96
+ */
97
+ async function sitemapFromHomepageLink(origin) {
98
+ const result = await httpGet(origin, { timeoutMs: 15_000, retries: 0 });
99
+ if (!result.ok)
100
+ return [];
101
+ const found = [];
102
+ for (const match of result.body.matchAll(/<link\b[^>]*>/gi)) {
103
+ const tag = match[0];
104
+ if (!/rel=["']?sitemap["']?/i.test(tag))
105
+ continue;
106
+ const href = /href=["']([^"']+)["']/i.exec(tag)?.[1];
107
+ if (href) {
108
+ try {
109
+ found.push(new URL(href, origin).toString());
110
+ }
111
+ catch {
112
+ // Unparseable href — ignore rather than fail discovery over it.
113
+ }
114
+ }
115
+ }
116
+ return found;
117
+ }
118
+ /**
119
+ * A sitemap.txt is a bare newline-delimited URL list, not XML. Detected by
120
+ * content rather than extension, because servers are inconsistent about both.
121
+ */
122
+ function isPlainTextSitemap(body) {
123
+ const head = body.trimStart().slice(0, 200);
124
+ return !head.startsWith("<") && /^https?:\/\//im.test(head);
125
+ }
126
+ function extractPlainTextUrls(body) {
127
+ return body
128
+ .split(/\r?\n/)
129
+ .map((line) => line.trim())
130
+ .filter((line) => /^https?:\/\//i.test(line));
131
+ }
132
+ export async function readSitemap(origin) {
133
+ const warnings = [];
134
+ const sitemapsRead = [];
135
+ const attempted = [];
136
+ const urls = new Set();
137
+ const seen = new Set();
138
+ let truncated = false;
139
+ /**
140
+ * Tiers, cheapest and most authoritative first. Each is tried only if every
141
+ * earlier one came up empty, so a site that declares its sitemap properly
142
+ * still costs two requests while a site that hides it gets a real search.
143
+ */
144
+ const declared = await sitemapsFromRobots(origin);
145
+ const tiers = [
146
+ { name: "robots.txt", locations: async () => declared },
147
+ {
148
+ name: "standard locations",
149
+ locations: async () => [
150
+ new URL("/sitemap.xml", origin).toString(),
151
+ new URL("/sitemap_index.xml", origin).toString(),
152
+ ],
153
+ },
154
+ { name: "homepage <link rel=sitemap>", locations: () => sitemapFromHomepageLink(origin) },
155
+ {
156
+ name: "common CMS locations",
157
+ locations: async () => CANDIDATE_PATHS.map((path) => new URL(path, origin).toString()),
158
+ },
159
+ ];
160
+ for (const tier of tiers) {
161
+ // Stop on the first tier that finds a sitemap *document*, not the first
162
+ // that yields URLs. web.dev serves a valid index whose children time out;
163
+ // falling through on an empty result sent discovery guessing at nine more
164
+ // locations for 43s when the sitemap had already been located.
165
+ if (sitemapsRead.length > 0)
166
+ break;
167
+ const queue = await tier.locations();
168
+ let consecutiveFailures = 0;
169
+ while (queue.length > 0) {
170
+ if (sitemapsRead.length >= MAX_SITEMAPS || urls.size >= MAX_URLS) {
171
+ truncated = true;
172
+ break;
173
+ }
174
+ const next = queue.shift();
175
+ if (seen.has(next))
176
+ continue;
177
+ seen.add(next);
178
+ attempted.push(next);
179
+ // Large sites commonly serve .xml.gz. It arrives as an opaque gzip payload
180
+ // rather than with Content-Encoding, so fetch does not inflate it and a
181
+ // text read produces binary noise — hence the explicit binary path.
182
+ const gzipped = /\.gz(\?|$)/i.test(next);
183
+ // No retry: discovery must stay fast, and a sitemap that times out once
184
+ // usually times out again. Retrying doubled the cost of the slow case
185
+ // for no observed benefit.
186
+ const result = await httpGet(next, {
187
+ timeoutMs: FETCH_TIMEOUT_MS,
188
+ retries: 0,
189
+ raw: gzipped,
190
+ });
191
+ if (!result.ok) {
192
+ // A 404 or 403 on a guessed location is the expected answer to "is it
193
+ // here?" — cheap, informative, and no reason to stop guessing. Only
194
+ // expensive failures (timeouts, 5xx) count toward giving up.
195
+ if (result.status === 404 || result.status === 403)
196
+ continue;
197
+ consecutiveFailures++;
198
+ // A sitemap index can list hundreds of children. If the first few all
199
+ // time out, the rest almost certainly will too, at a full timeout each.
200
+ if (consecutiveFailures >= 3) {
201
+ warnings.push(`Gave up on ${tier.name} after ${consecutiveFailures} consecutive failures ` +
202
+ `(last: ${result.error ?? `HTTP ${result.status}`}).`);
203
+ break;
204
+ }
205
+ warnings.push(`Could not read ${next}: ${result.error ?? `HTTP ${result.status}`}`);
206
+ continue;
207
+ }
208
+ consecutiveFailures = 0;
209
+ let body = result.body;
210
+ if (gzipped) {
211
+ try {
212
+ body = gunzipSync(Buffer.from(result.bytes ?? new Uint8Array())).toString("utf8");
213
+ }
214
+ catch (err) {
215
+ warnings.push(`Could not decompress ${next}: ${err.message}`);
216
+ continue;
217
+ }
218
+ }
219
+ if (isPlainTextSitemap(body)) {
220
+ const plain = extractPlainTextUrls(body).filter(looksAuditable);
221
+ if (plain.length === 0)
222
+ continue;
223
+ sitemapsRead.push(next);
224
+ for (const loc of plain) {
225
+ if (urls.size >= MAX_URLS) {
226
+ truncated = true;
227
+ break;
228
+ }
229
+ urls.add(loc);
230
+ }
231
+ continue;
232
+ }
233
+ const locs = extractLocs(body);
234
+ if (locs.length === 0)
235
+ continue;
236
+ sitemapsRead.push(next);
237
+ if (isSitemapIndex(body)) {
238
+ for (const child of locs)
239
+ if (!seen.has(child))
240
+ queue.push(child);
241
+ continue;
242
+ }
243
+ for (const loc of locs) {
244
+ if (urls.size >= MAX_URLS) {
245
+ truncated = true;
246
+ break;
247
+ }
248
+ if (looksAuditable(loc))
249
+ urls.add(loc);
250
+ }
251
+ }
252
+ }
253
+ if (sitemapsRead.length > 0 && urls.size === 0) {
254
+ warnings.push(`Found a sitemap at ${sitemapsRead[0]} but could not extract any URLs from it — ` +
255
+ `its child documents failed to load or contained no page entries. Supply URLs ` +
256
+ `with discovery:"list" or discovery:"csv".`);
257
+ }
258
+ if (sitemapsRead.length === 0) {
259
+ warnings.push(`No sitemap found for ${origin}. Tried ${attempted.length} location(s): ` +
260
+ `robots.txt, the standard paths, the homepage <link rel="sitemap">, and ` +
261
+ `common CMS locations. ` +
262
+ `Supply URLs directly with discovery:"list", or point at a CSV export with ` +
263
+ `discovery:"csv" — an analytics top-pages export is the better input for a ` +
264
+ `performance audit anyway, since it is weighted by real traffic.`);
265
+ }
266
+ if (truncated) {
267
+ warnings.push(`Stopped after ${sitemapsRead.length} sitemap documents and ${urls.size} URLs. ` +
268
+ `The template breakdown below is based on that subset.`);
269
+ }
270
+ return { urls: [...urls], sitemapsRead, truncated, attempted, warnings };
271
+ }
272
+ //# sourceMappingURL=sitemapReader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sitemapReader.js","sourceRoot":"","sources":["../../src/utils/sitemapReader.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAEvC,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAa1C,iGAAiG;AACjG,MAAM,YAAY,GAAG,EAAE,CAAC;AACxB,MAAM,QAAQ,GAAG,MAAM,CAAC;AACxB,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAEhC,MAAM,MAAM,GAAG,oCAAoC,CAAC;AAEpD,SAAS,iBAAiB,CAAC,KAAa;IACtC,OAAO,KAAK;SACT,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;SACrB,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;SACrB,OAAO,CAAC,SAAS,EA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AI,CACX,sBAAsB,YAAY,CAAC,CAAC,CAAC,4CAA4C;YAC/E,+EAA+E;YAC/E,2CAA2C,CAC9C,CAAC;IACJ,CAAC;IAED,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC9B,QAAQ,CAAC,IAAI,CACX,wBAAwB,MAAM,WAAW,SAAS,CAAC,MAAM,gBAAgB;YACvE,yEAAyE;YACzE,wBAAwB;YACxB,4EAA4E;YAC5E,4EAA4E;YAC5E,iEAAiE,CACpE,CAAC;IACJ,CAAC;IACD,IAAI,SAAS,EAAE,CAAC;QACd,QAAQ,CAAC,IAAI,CACX,iBAAiB,YAAY,CAAC,MAAM,0BAA0B,IAAI,CAAC,IAAI,SAAS;YAC9E,uDAAuD,CAC1D,CAAC;IACJ,CAAC;IAED,OAAO,EAAE,IAAI,EAAE,CAAC,GAAG,IAAI,CAAC,EAAE,YAAY,EAAE,SAAS,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC;AAC3E,CAAC"}
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Cluster a URL list into page templates.
3
+ *
4
+ * A performance audit's unit of analysis is the template, not the URL. Nobody
5
+ * needs 3,904 product pages measured; they need to know what a product page
6
+ * costs. The manual Five Below audit was organised exactly this way — Homepage,
7
+ * PLP (category), PLP (subcategory), PLP (paginated), PDP, Cart, Search,
8
+ * Info — with representative URLs sampled per template, and this reproduces
9
+ * that structure automatically instead of asking someone to hand-write the
10
+ * list.
11
+ *
12
+ * The clustering is a heuristic and will occasionally be wrong. That is
13
+ * acceptable because the plan tool shows its work and the user approves the
14
+ * sample before any PSI call is spent: a misclassification costs a
15
+ * conversation turn, not quota.
16
+ */
17
+ export interface UrlTemplate {
18
+ id: string;
19
+ label: string;
20
+ /** Path shape with high-cardinality segments collapsed, e.g. "/categories/*". */
21
+ pattern: string;
22
+ urlCount: number;
23
+ /** How many URLs to audit, given the population size. */
24
+ suggestedSample: number;
25
+ /** Representative URLs, most-canonical first. */
26
+ candidates: string[];
27
+ auditable: boolean;
28
+ reason?: string;
29
+ recommendation?: string;
30
+ /**
31
+ * True when *any* URL in the template is session-gated — computed over the
32
+ * whole group, not the sampled candidates. Deciding this from candidates made
33
+ * the verdict depend on which URLs the sampler happened to pick, so a
34
+ * template containing /cart could pass as auditable purely by luck.
35
+ */
36
+ anySessionGated: boolean;
37
+ }
38
+ export interface ClassifyOptions {
39
+ /** Patterns matching fewer URLs than this are folded into "Other". */
40
+ minTemplateSize?: number;
41
+ }
42
+ export declare function classifyUrls(rawUrls: string[], options?: ClassifyOptions): {
43
+ templates: UrlTemplate[];
44
+ skipped: number;
45
+ };