@se-studio/site-check 2.20.0 → 2.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +60 -0
- package/README.md +4 -0
- package/develop-published-gate.mjs +869 -0
- package/dist/check-pages-exist.d.ts.map +1 -1
- package/dist/check-pages-exist.js +2 -1
- package/dist/check-pages-exist.js.map +1 -1
- package/dist/check-rewrites.d.ts.map +1 -1
- package/dist/check-rewrites.js +2 -1
- package/dist/check-rewrites.js.map +1 -1
- package/dist/cli.js +8 -1
- package/dist/cli.js.map +1 -1
- package/dist/collect-markdown-urls.d.ts.map +1 -1
- package/dist/collect-markdown-urls.js +2 -1
- package/dist/collect-markdown-urls.js.map +1 -1
- package/dist/download.d.ts.map +1 -1
- package/dist/download.js +2 -1
- package/dist/download.js.map +1 -1
- package/dist/fetch-timeout.d.ts +9 -0
- package/dist/fetch-timeout.d.ts.map +1 -0
- package/dist/fetch-timeout.js +17 -0
- package/dist/fetch-timeout.js.map +1 -0
- package/dist/validate.d.ts.map +1 -1
- package/dist/validate.js +5 -3
- package/dist/validate.js.map +1 -1
- package/dist/xml-entities.d.ts +3 -0
- package/dist/xml-entities.d.ts.map +1 -0
- package/dist/xml-entities.js +10 -0
- package/dist/xml-entities.js.map +1 -0
- package/docs/develop-published.md +44 -0
- package/package.json +6 -3
- package/templates/develop-published/develop-published-gate.yml +148 -0
- package/templates/develop-published/update-develop-published.yml +58 -0
|
@@ -0,0 +1,869 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* develop-published promote gate.
|
|
5
|
+
*
|
|
6
|
+
* Runs the full smoke, the content smoke (cases with `contentAssert` only), the sitemap slug-guard parity
|
|
7
|
+
* and the draft canary against the `develop-published` deployment of the exact commit being promoted.
|
|
8
|
+
* The develop-vs-production compare (sitemap pages exist, page text) is ON DEMAND ONLY: it runs just when
|
|
9
|
+
* `--compare` (alias `--prod-compare`) is given. Without it that stage reports `compare: not run (on-demand)`
|
|
10
|
+
* and counts as neither a pass nor a fail.
|
|
11
|
+
* Run it from the app root (where smoke.cases.json and vercel.json live).
|
|
12
|
+
*
|
|
13
|
+
* Usage:
|
|
14
|
+
* develop-published-gate --url <deploymentUrl> --prod-url <productionUrl> [options]
|
|
15
|
+
*
|
|
16
|
+
* Options:
|
|
17
|
+
* --url <url> develop-published deployment URL (or DEPLOYMENT_URL)
|
|
18
|
+
* --compare, --prod-compare run the develop-vs-production compare (off by default, on demand only)
|
|
19
|
+
* --prod-url <url> production site for the compare (or PRODUCTION_SITE_URL). Required with
|
|
20
|
+
* --compare (or --sitemap-roots); not needed otherwise
|
|
21
|
+
* --expect-sha <sha> commit being promoted (default: git HEAD)
|
|
22
|
+
* --deployment-sha <sha> commit the deployment was built from (the Vercel dispatch payload sha)
|
|
23
|
+
* --draft-canary <path> path that exists only as a draft; must 404 on the deployment (repeatable)
|
|
24
|
+
* --no-draft-canary skip the canary stage (site has no draft-only page). Without it, giving no
|
|
25
|
+
* --draft-canary fails the gate. Ignored when a --draft-canary is also given
|
|
26
|
+
* --compare-timeout-minutes <n> kill the spawned prod compare after n minutes (default 25, or the
|
|
27
|
+
* GATE_COMPARE_TIMEOUT_MINUTES env when it is a positive number; the flag wins).
|
|
28
|
+
* Only used when --compare is given
|
|
29
|
+
* --sitemap-roots <list> sitemap roots this app owns, comma-separated paths or absolute URLs on the production
|
|
30
|
+
* site (e.g. /marketing/sitemap.xml); repeatable. The prod compare walks only these
|
|
31
|
+
* roots (an index is followed one level). Default: the full production sitemap
|
|
32
|
+
* index (/sitemap.xml and /sitemap-unindexed.xml), i.e. unchanged behaviour
|
|
33
|
+
* --host-prefix <prefix> required. The deployment host must start with this (e.g. "my-site-"); the
|
|
34
|
+
* bypass token is only ever sent to a matching *.vercel.app host. The gate's own
|
|
35
|
+
* requests follow redirects by hand; the spawned site-check compare does not (a
|
|
36
|
+
* redirect from the deployment to another host would carry the header)
|
|
37
|
+
* --pages <n> pages in the text compare (default 5)
|
|
38
|
+
* --min-similarity <0..1> text compare threshold per page (default 0.9)
|
|
39
|
+
* --cases <file> smoke cases (default smoke.cases.json)
|
|
40
|
+
* --json <file> write the result summary as JSON
|
|
41
|
+
*
|
|
42
|
+
* Env: VERCEL_PROTECTION_BYPASS_TOKEN (deployment protection bypass; never printed).
|
|
43
|
+
* GATE_COMPARE_TIMEOUT_MINUTES (compare kill limit in minutes, default 25; ignored unless > 0).
|
|
44
|
+
* Exit 0 only when every stage passes, 1 when a stage fails, 2 on a usage or runtime error.
|
|
45
|
+
* See docs/develop-published.md.
|
|
46
|
+
*/
|
|
47
|
+
import { spawnSync } from 'node:child_process';
|
|
48
|
+
import fs from 'node:fs';
|
|
49
|
+
import os from 'node:os';
|
|
50
|
+
import path from 'node:path';
|
|
51
|
+
import { fileURLToPath } from 'node:url';
|
|
52
|
+
import { pathnameHasImpossibleCmsSlug } from '@se-studio/core-ui/impossible-cms-slug';
|
|
53
|
+
|
|
54
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
55
|
+
const SMOKE_LIVE = path.join(here, 'smoke-test-live.mjs');
|
|
56
|
+
const SITE_CHECK = path.join(here, 'dist/cli.js');
|
|
57
|
+
|
|
58
|
+
export function parseArgs(argv) {
|
|
59
|
+
const o = {
|
|
60
|
+
canaries: [],
|
|
61
|
+
pages: 5,
|
|
62
|
+
minSimilarity: 0.9,
|
|
63
|
+
cases: 'smoke.cases.json',
|
|
64
|
+
hostPrefix: '',
|
|
65
|
+
sitemapRoots: [],
|
|
66
|
+
};
|
|
67
|
+
for (let i = 0; i < argv.length; i++) {
|
|
68
|
+
const a = argv[i];
|
|
69
|
+
const next = () => argv[++i];
|
|
70
|
+
if (a === '--url') o.url = next();
|
|
71
|
+
else if (a === '--prod-url') o.prodUrl = next();
|
|
72
|
+
else if (a === '--host-prefix') o.hostPrefix = next();
|
|
73
|
+
else if (a === '--expect-sha') o.expectSha = next();
|
|
74
|
+
else if (a === '--deployment-sha') o.deploymentSha = next();
|
|
75
|
+
else if (a === '--draft-canary') o.canaries.push(next());
|
|
76
|
+
else if (a === '--no-draft-canary') o.noCanary = true;
|
|
77
|
+
else if (a === '--compare' || a === '--prod-compare') o.compare = true;
|
|
78
|
+
else if (a === '--compare-timeout-minutes') {
|
|
79
|
+
const minutes = Number(next());
|
|
80
|
+
if (!Number.isFinite(minutes) || minutes <= 0)
|
|
81
|
+
throw new Error('--compare-timeout-minutes needs a positive number of minutes');
|
|
82
|
+
o.compareTimeoutMinutes = minutes;
|
|
83
|
+
} else if (a === '--sitemap-roots') {
|
|
84
|
+
const roots = splitRoots(next());
|
|
85
|
+
if (roots.length === 0) throw new Error('--sitemap-roots needs at least one root');
|
|
86
|
+
o.sitemapRoots.push(...roots);
|
|
87
|
+
} else if (a === '--pages') o.pages = Number(next());
|
|
88
|
+
else if (a === '--min-similarity') o.minSimilarity = Number(next());
|
|
89
|
+
else if (a === '--cases') o.cases = next();
|
|
90
|
+
else if (a === '--json') o.json = next();
|
|
91
|
+
else throw new Error(`Unknown argument: ${a}`);
|
|
92
|
+
}
|
|
93
|
+
o.url = (o.url ?? process.env.DEPLOYMENT_URL ?? '').replace(/\/+$/, '');
|
|
94
|
+
if (o.url && !/^https?:\/\//.test(o.url)) o.url = `https://${o.url}`;
|
|
95
|
+
o.prodUrl = (o.prodUrl ?? process.env.PRODUCTION_SITE_URL ?? '').replace(/\/+$/, '');
|
|
96
|
+
return o;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Visible text lines of an HTML document (scripts, styles, tags and whitespace removed). */
|
|
100
|
+
export function visibleLines(html) {
|
|
101
|
+
const body = html
|
|
102
|
+
.replace(/<(script|style|noscript|svg)\b[\s\S]*?<\/\1>/gi, ' ')
|
|
103
|
+
.replace(/<!--[\s\S]*?-->/g, ' ')
|
|
104
|
+
.replace(/<\/(p|div|li|h[1-6]|section|article|header|footer|nav|tr|br)\s*>/gi, '\n')
|
|
105
|
+
.replace(/<[^>]+>/g, ' ')
|
|
106
|
+
.replace(/ /g, ' ')
|
|
107
|
+
.replace(/&/g, '&')
|
|
108
|
+
.replace(/'|'/g, "'")
|
|
109
|
+
.replace(/"/g, '"');
|
|
110
|
+
return body
|
|
111
|
+
.split('\n')
|
|
112
|
+
.map((l) => l.replace(/\s+/g, ' ').trim())
|
|
113
|
+
.filter((l) => l.length > 2);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Dice similarity of two line sets, 1 = identical. */
|
|
117
|
+
export function similarity(a, b) {
|
|
118
|
+
const A = new Set(a);
|
|
119
|
+
const B = new Set(b);
|
|
120
|
+
if (A.size === 0 && B.size === 0) return 1;
|
|
121
|
+
let shared = 0;
|
|
122
|
+
for (const l of A) if (B.has(l)) shared++;
|
|
123
|
+
return (2 * shared) / (A.size + B.size);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Paths vercel.json's ignoreCommand treats as "no rebuild needed" (the `:!path` pathspecs). */
|
|
127
|
+
export function ignoredPaths(file = 'vercel.json') {
|
|
128
|
+
try {
|
|
129
|
+
const cmd = JSON.parse(fs.readFileSync(file, 'utf8')).ignoreCommand ?? '';
|
|
130
|
+
return [...cmd.matchAll(/":!([^"\\]+)"/g)].map((m) => m[1]);
|
|
131
|
+
} catch {
|
|
132
|
+
return [];
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* The build must be of the promoted commit: the same SHA, or an ancestor when every file changed
|
|
138
|
+
* since is in vercel.json's ignoreCommand pathspec (Vercel skipped that build on purpose).
|
|
139
|
+
* Runs git in the current directory.
|
|
140
|
+
*/
|
|
141
|
+
export function checkExactCommit(deploymentSha, expectSha, vercelJson = 'vercel.json') {
|
|
142
|
+
if (!deploymentSha)
|
|
143
|
+
return {
|
|
144
|
+
ok: false,
|
|
145
|
+
detail: 'no --deployment-sha given, cannot prove the build is the promoted commit',
|
|
146
|
+
};
|
|
147
|
+
const d = deploymentSha.slice(0, 9);
|
|
148
|
+
const e = expectSha.slice(0, 9);
|
|
149
|
+
if (deploymentSha === expectSha)
|
|
150
|
+
return { ok: true, detail: `deployment and promoted commit are both ${e}` };
|
|
151
|
+
const ignored = ignoredPaths(vercelJson);
|
|
152
|
+
const ancestor =
|
|
153
|
+
spawnSync('git', ['merge-base', '--is-ancestor', deploymentSha, expectSha]).status === 0;
|
|
154
|
+
const changed = spawnSync('git', [
|
|
155
|
+
'diff',
|
|
156
|
+
'--quiet',
|
|
157
|
+
deploymentSha,
|
|
158
|
+
expectSha,
|
|
159
|
+
'--',
|
|
160
|
+
'.',
|
|
161
|
+
...ignored.map((p) => `:!${p}`),
|
|
162
|
+
]).status;
|
|
163
|
+
if (ancestor && ignored.length > 0 && changed === 0)
|
|
164
|
+
return {
|
|
165
|
+
ok: true,
|
|
166
|
+
detail: `deployment ${d} is an ancestor of promoted ${e}; only ignoreCommand paths changed (build skipped by Vercel)`,
|
|
167
|
+
};
|
|
168
|
+
return {
|
|
169
|
+
ok: false,
|
|
170
|
+
detail: `deployment ${d} vs promoted ${e}: ${ancestor ? 'app files changed since the build' : 'not an ancestor'}`,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
let deploymentHost = '';
|
|
175
|
+
|
|
176
|
+
/** The bypass header goes to the deployment host only, never to production. */
|
|
177
|
+
function bypassHeaders(url) {
|
|
178
|
+
const t = process.env.VERCEL_PROTECTION_BYPASS_TOKEN;
|
|
179
|
+
return t && new URL(url).hostname === deploymentHost ? { 'x-vercel-protection-bypass': t } : {};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Per-request limit for every prod-compare / sitemap fetch (headers and body), so a stall cannot hang the run. */
|
|
183
|
+
export const FETCH_TIMEOUT_MS = 30_000;
|
|
184
|
+
|
|
185
|
+
/** Default whole-process limit for the spawned site-check compare (a healthy HSD compare takes ~20 minutes). */
|
|
186
|
+
export const DEFAULT_COMPARE_TIMEOUT_MINUTES = 25;
|
|
187
|
+
export const COMPARE_TIMEOUT_MS = DEFAULT_COMPARE_TIMEOUT_MINUTES * 60_000;
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Whole-process limit for the spawned site-check compare, so a stall inside it cannot hang the run either.
|
|
191
|
+
* `--compare-timeout-minutes` wins, then a positive GATE_COMPARE_TIMEOUT_MINUTES, else the 25-minute default.
|
|
192
|
+
*/
|
|
193
|
+
export function resolveCompareTimeoutMs(flagMinutes, env = process.env) {
|
|
194
|
+
if (flagMinutes !== undefined) return flagMinutes * 60_000;
|
|
195
|
+
const fromEnv = Number(env.GATE_COMPARE_TIMEOUT_MINUTES);
|
|
196
|
+
return (fromEnv > 0 ? fromEnv : DEFAULT_COMPARE_TIMEOUT_MINUTES) * 60_000;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** fetch() with a hard per-request timeout. The abort surfaces as a TimeoutError, which withRetry treats as transient. */
|
|
200
|
+
export function fetchWithTimeout(url, init = {}, timeoutMs = FETCH_TIMEOUT_MS) {
|
|
201
|
+
return fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export function run(cmd, args, env = {}, timeout) {
|
|
205
|
+
const r = spawnSync(cmd, args, {
|
|
206
|
+
encoding: 'utf8',
|
|
207
|
+
env: { ...process.env, ...env },
|
|
208
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
209
|
+
...(timeout ? { timeout, killSignal: 'SIGKILL' } : {}),
|
|
210
|
+
});
|
|
211
|
+
// `killed` is explicit: the partial output of a stalled run may contain "fetch failed" or similar, so it is never
|
|
212
|
+
// judged by its text. A run that exceeded its whole-process limit fails and is not retried.
|
|
213
|
+
const killed = r.error?.code === 'ETIMEDOUT';
|
|
214
|
+
const note = killed ? `\ncompare killed after exceeding the ${timeout}ms limit\n` : '';
|
|
215
|
+
return { code: r.status ?? 1, out: `${r.stdout ?? ''}${r.stderr ?? ''}${note}`, killed };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function smokeSummary(out) {
|
|
219
|
+
const m = out.match(/Summary: (\d+) cases, (\d+) failed, (\d+) warnings/);
|
|
220
|
+
return m ? { cases: +m[1], failed: +m[2], warnings: +m[3] } : null;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const TRANSIENT_RE =
|
|
224
|
+
/fetch failed|ECONNRESET|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|ECONNREFUSED|EPIPE|socket hang up|UND_ERR_\w+|other side closed|connect timeout|TimeoutError|timed? ?out/i;
|
|
225
|
+
|
|
226
|
+
/** True when an error message or tool output looks like a network blip rather than an answer. */
|
|
227
|
+
export function isTransientFetchError(text) {
|
|
228
|
+
return TRANSIENT_RE.test(String(text ?? ''));
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const sleepMs = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Run `fn`, retrying up to `tries` times in total with exponential backoff (baseMs, 2x) when it
|
|
235
|
+
* throws a transient fetch error. Non-transient errors and the last transient error are rethrown.
|
|
236
|
+
*/
|
|
237
|
+
export async function withRetry(fn, { tries = 3, baseMs = 500, sleep = sleepMs } = {}) {
|
|
238
|
+
for (let attempt = 1; ; attempt++) {
|
|
239
|
+
try {
|
|
240
|
+
return await fn(attempt);
|
|
241
|
+
} catch (err) {
|
|
242
|
+
const message =
|
|
243
|
+
err instanceof Error ? `${err.name} ${err.message} ${err.cause ?? ''}` : String(err);
|
|
244
|
+
if (attempt >= tries || !isTransientFetchError(message)) throw err;
|
|
245
|
+
console.log(
|
|
246
|
+
` transient fetch error (attempt ${attempt}/${tries}), retrying: ${message.trim()}`,
|
|
247
|
+
);
|
|
248
|
+
await sleep(baseMs * 2 ** (attempt - 1));
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Split a `--sitemap-roots` value (comma-separated) into trimmed, non-empty entries. */
|
|
254
|
+
export function splitRoots(value) {
|
|
255
|
+
return String(value ?? '')
|
|
256
|
+
.split(',')
|
|
257
|
+
.map((r) => r.trim())
|
|
258
|
+
.filter(Boolean);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Absolute production URLs for the configured sitemap roots. A root is a path ("/marketing/sitemap.xml")
|
|
263
|
+
* or an absolute URL; an absolute URL must be on the production origin, so a typo can never make the gate
|
|
264
|
+
* fetch some other host.
|
|
265
|
+
*/
|
|
266
|
+
export function resolveSitemapRoots(roots, prodUrl) {
|
|
267
|
+
const origin = new URL(prodUrl).origin;
|
|
268
|
+
return roots.map((r) => {
|
|
269
|
+
const u = /^https?:\/\//i.test(r)
|
|
270
|
+
? new URL(r)
|
|
271
|
+
: new URL(r.startsWith('/') ? r : `/${r}`, origin);
|
|
272
|
+
if (u.origin !== origin)
|
|
273
|
+
throw new Error(`--sitemap-roots entry ${r} is not on the production origin ${origin}`);
|
|
274
|
+
return u.href;
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const decodeXml = (v) =>
|
|
279
|
+
v
|
|
280
|
+
.replace(/</g, '<')
|
|
281
|
+
.replace(/>/g, '>')
|
|
282
|
+
.replace(/"/g, '"')
|
|
283
|
+
.replace(/'/g, "'")
|
|
284
|
+
.replace(/&/g, '&');
|
|
285
|
+
|
|
286
|
+
/** `<loc>` values of a sitemap or sitemap index body, XML entities decoded. */
|
|
287
|
+
export function extractLocs(xml) {
|
|
288
|
+
return [...xml.matchAll(/<loc>([^<]+)<\/loc>/g)]
|
|
289
|
+
.map((m) => decodeXml(m[1].trim()))
|
|
290
|
+
.filter(Boolean);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const STATIC_EXT_RE =
|
|
294
|
+
/\.(?:png|jpe?g|gif|svg|webp|avif|ico|pdf|css|js|map|xml|txt|json|zip|mp4|webm|woff2?|ttf)$/i;
|
|
295
|
+
|
|
296
|
+
/** Sitemap URLs that are files or downloads rather than pages (same idea as site-check's compare). */
|
|
297
|
+
export function isNonPageUrl(url) {
|
|
298
|
+
try {
|
|
299
|
+
const p = new URL(url).pathname.replace(/\/$/, '');
|
|
300
|
+
return p.startsWith('/download/') || STATIC_EXT_RE.test(p);
|
|
301
|
+
} catch {
|
|
302
|
+
return false;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Production page URLs listed under the given sitemap roots only. A root that is a sitemap index is
|
|
308
|
+
* followed one level (its child sitemaps are fetched and must answer 2xx; a nested index is an error);
|
|
309
|
+
* a root that is a urlset contributes its own URLs. A root that does not answer 2xx, or lists nothing,
|
|
310
|
+
* throws: the compare never passes on an empty or unreadable root.
|
|
311
|
+
* `fetchText(url)` resolves {status, text}.
|
|
312
|
+
*/
|
|
313
|
+
export async function collectRootPageUrls(rootUrls, fetchText, { rebaseChildren = false } = {}) {
|
|
314
|
+
const pages = [];
|
|
315
|
+
for (const root of rootUrls) {
|
|
316
|
+
const origin = new URL(root).origin;
|
|
317
|
+
const res = await fetchText(root);
|
|
318
|
+
if (res.status < 200 || res.status >= 300)
|
|
319
|
+
throw new Error(`sitemap root ${root} returned HTTP ${res.status}`);
|
|
320
|
+
const isIndex = /<sitemapindex[\s>]/.test(res.text);
|
|
321
|
+
const locs = extractLocs(res.text);
|
|
322
|
+
const rootPages = [];
|
|
323
|
+
if (!isIndex) {
|
|
324
|
+
rootPages.push(...locs);
|
|
325
|
+
} else {
|
|
326
|
+
for (const loc of locs) {
|
|
327
|
+
const childUrl = new URL(loc);
|
|
328
|
+
if (childUrl.origin !== origin && !rebaseChildren)
|
|
329
|
+
throw new Error(`child sitemap ${loc} of ${root} is not on ${origin}`);
|
|
330
|
+
const child = rebaseChildren ? `${origin}${childUrl.pathname}${childUrl.search}` : loc;
|
|
331
|
+
const c = await fetchText(child);
|
|
332
|
+
if (c.status < 200 || c.status >= 300)
|
|
333
|
+
throw new Error(`child sitemap ${child} of ${root} returned HTTP ${c.status}`);
|
|
334
|
+
if (/<sitemapindex[\s>]/.test(c.text))
|
|
335
|
+
throw new Error(`child sitemap ${child} of ${root} is itself an index`);
|
|
336
|
+
rootPages.push(...extractLocs(c.text));
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
if (rootPages.length === 0) throw new Error(`sitemap root ${root} lists no URLs`);
|
|
340
|
+
pages.push(...rootPages);
|
|
341
|
+
}
|
|
342
|
+
return [...new Set(pages)];
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Prod compare limited to the configured sitemap roots. Returns the same {code, out} shape the spawned
|
|
347
|
+
* site-check compare produces, so judgeSitemapCompare and the retry logic apply unchanged.
|
|
348
|
+
* `fetchText(url)` reads the production sitemaps; `headStatus(url)` is the build's HEAD status for a URL.
|
|
349
|
+
*/
|
|
350
|
+
export async function compareSitemapRoots({
|
|
351
|
+
rootUrls,
|
|
352
|
+
devUrl,
|
|
353
|
+
fetchText,
|
|
354
|
+
headStatus,
|
|
355
|
+
concurrency = 8,
|
|
356
|
+
}) {
|
|
357
|
+
let prodPages;
|
|
358
|
+
try {
|
|
359
|
+
prodPages = await collectRootPageUrls(rootUrls, fetchText);
|
|
360
|
+
} catch (err) {
|
|
361
|
+
return {
|
|
362
|
+
code: 1,
|
|
363
|
+
out: `Sitemap roots failed: ${err instanceof Error ? err.message : String(err)}\n`,
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
const devOrigin = new URL(devUrl).origin;
|
|
367
|
+
const devPages = prodPages
|
|
368
|
+
.filter((u) => !isNonPageUrl(u))
|
|
369
|
+
.map((u) => {
|
|
370
|
+
const x = new URL(u);
|
|
371
|
+
return `${devOrigin}${x.pathname}${x.search}${x.hash}`;
|
|
372
|
+
});
|
|
373
|
+
let out = `Using sitemap roots ${rootUrls.join(', ')}: ${prodPages.length} page(s) → checking ${devPages.length} on development\n`;
|
|
374
|
+
if (devPages.length === 0)
|
|
375
|
+
return {
|
|
376
|
+
code: 1,
|
|
377
|
+
out: `${out}Sitemap roots failed: the roots list ${prodPages.length} URL(s) but none is a checkable page\n`,
|
|
378
|
+
};
|
|
379
|
+
out += `Checking ${devPages.length} page(s) exist on development…\n`;
|
|
380
|
+
const failures = new Array(devPages.length).fill(null);
|
|
381
|
+
let next = 0;
|
|
382
|
+
const worker = async () => {
|
|
383
|
+
for (let i = next++; i < devPages.length; i = next++) {
|
|
384
|
+
let status;
|
|
385
|
+
try {
|
|
386
|
+
status = await headStatus(devPages[i]);
|
|
387
|
+
} catch {
|
|
388
|
+
status = 0;
|
|
389
|
+
}
|
|
390
|
+
if (status < 200 || status >= 300) failures[i] = ` ${devPages[i]} … HTTP ${status}`;
|
|
391
|
+
}
|
|
392
|
+
};
|
|
393
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, devPages.length) }, worker));
|
|
394
|
+
const failed = failures.filter(Boolean);
|
|
395
|
+
if (failed.length > 0) {
|
|
396
|
+
return {
|
|
397
|
+
code: 1,
|
|
398
|
+
out: `${out}\n${failed.length} page(s) did not return 2xx on development:\n${failed.join('\n')}\n`,
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
return {
|
|
402
|
+
code: 0,
|
|
403
|
+
out: `${out}All production sitemap pages in the configured roots exist on development.\n`,
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* Sitemap paths the core guard would 404. The guard is core's `pathnameHasImpossibleCmsSlug` (not a copy), so
|
|
409
|
+
* the sitemap and the routes cannot drift: a URL the sitemap advertises must never be one the app refuses.
|
|
410
|
+
* Returns the offending pathnames (decoded as listed), de-duplicated, in sitemap order.
|
|
411
|
+
*/
|
|
412
|
+
export function findImpossibleSitemapPaths(urls, isImpossible = pathnameHasImpossibleCmsSlug) {
|
|
413
|
+
const bad = [];
|
|
414
|
+
for (const u of urls) {
|
|
415
|
+
let pathname;
|
|
416
|
+
try {
|
|
417
|
+
pathname = new URL(u).pathname;
|
|
418
|
+
} catch {
|
|
419
|
+
bad.push(u);
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
if (isImpossible(pathname)) bad.push(pathname);
|
|
423
|
+
}
|
|
424
|
+
return [...new Set(bad)];
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Sitemap-parity stage: every page the deployment's own sitemap lists must pass the core slug guard. Roots are
|
|
429
|
+
* the build's sitemap roots (default `/sitemap.xml`, plus `/sitemap-unindexed.xml` when the build serves it; a 5xx on it fails). Index children are fetched from the build origin even when the build's sitemap lists them on the production domain.
|
|
430
|
+
* A sitemap that cannot be read FAILS (never a silent pass). `fetchText(url)` resolves {status, text}.
|
|
431
|
+
*/
|
|
432
|
+
export async function checkSitemapSlugParity({
|
|
433
|
+
rootUrls,
|
|
434
|
+
fetchText,
|
|
435
|
+
optionalRootUrls = [],
|
|
436
|
+
isImpossible = pathnameHasImpossibleCmsSlug,
|
|
437
|
+
}) {
|
|
438
|
+
let urls;
|
|
439
|
+
try {
|
|
440
|
+
const rebase = { rebaseChildren: true };
|
|
441
|
+
urls = await collectRootPageUrls(rootUrls, fetchText, rebase);
|
|
442
|
+
for (const root of optionalRootUrls) {
|
|
443
|
+
const probe = await fetchText(root);
|
|
444
|
+
if (probe.status >= 500)
|
|
445
|
+
throw new Error(`optional sitemap ${root} returned HTTP ${probe.status}`);
|
|
446
|
+
if (probe.status >= 200 && probe.status < 300)
|
|
447
|
+
urls = [...new Set([...urls, ...(await collectRootPageUrls([root], fetchText, rebase))])];
|
|
448
|
+
}
|
|
449
|
+
} catch (err) {
|
|
450
|
+
return {
|
|
451
|
+
ok: false,
|
|
452
|
+
offenders: [],
|
|
453
|
+
detail: `could not read the build sitemap: ${err instanceof Error ? err.message : String(err)}`,
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
const offenders = findImpossibleSitemapPaths(urls, isImpossible);
|
|
457
|
+
if (offenders.length > 0) {
|
|
458
|
+
const shown = offenders.slice(0, 10).join(', ');
|
|
459
|
+
return {
|
|
460
|
+
ok: false,
|
|
461
|
+
offenders,
|
|
462
|
+
detail: `${offenders.length} sitemap path(s) fail the core impossible-slug guard and would 404: ${shown}${offenders.length > 10 ? ', …' : ''}`,
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
return {
|
|
466
|
+
ok: true,
|
|
467
|
+
offenders: [],
|
|
468
|
+
detail: `${urls.length} sitemap URL(s) all pass the core slug guard`,
|
|
469
|
+
};
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/** Build sitemap roots: the configured roots rebased onto the deployment origin, else the default index. */
|
|
473
|
+
export function buildSitemapRoots(roots, prodUrl, devUrl) {
|
|
474
|
+
const dev = new URL(devUrl).origin;
|
|
475
|
+
if (roots.length === 0)
|
|
476
|
+
return { rootUrls: [`${dev}/sitemap.xml`], optionalRootUrls: [`${dev}/sitemap-unindexed.xml`] };
|
|
477
|
+
const rebased = resolveSitemapRoots(roots, prodUrl).map((r) => {
|
|
478
|
+
const u = new URL(r);
|
|
479
|
+
return `${dev}${u.pathname}${u.search}`;
|
|
480
|
+
});
|
|
481
|
+
return { rootUrls: rebased, optionalRootUrls: [] };
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** ": <reason>" when the roots compare itself failed (unreadable root), else "". Only the roots path prints this marker. */
|
|
485
|
+
function sitemapRootsError(out) {
|
|
486
|
+
const m = out.match(/^Sitemap roots failed: (.+)$/m);
|
|
487
|
+
return m ? `: ${m[1]}` : '';
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/** Failed page URLs listed by `site-check --check-against` (" <url> … HTTP 404"). */
|
|
491
|
+
export function parseFailedUrls(out) {
|
|
492
|
+
return [...out.matchAll(/^\s+(https?:\/\/\S+) … HTTP \d+/gm)].map((m) => m[1]);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/** Same lines as {url, status}: the build's own answer for each failed page. */
|
|
496
|
+
export function parseFailedPages(out) {
|
|
497
|
+
return [...out.matchAll(/^\s+(https?:\/\/\S+) … HTTP (\d+)/gm)].map((m) => ({
|
|
498
|
+
url: m[1],
|
|
499
|
+
status: Number(m[2]),
|
|
500
|
+
}));
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* Run the spawned compare, retrying (3 tries, backoff) when it died on a transient fetch error
|
|
505
|
+
* (no per-page HTTP failures listed, so it never reached an answer). `runOnce` returns {code, out, killed?};
|
|
506
|
+
* a killed run (whole-process limit exceeded) is returned at once, whatever its partial output says.
|
|
507
|
+
*/
|
|
508
|
+
export async function runCompareWithRetry(
|
|
509
|
+
runOnce,
|
|
510
|
+
{ tries = 3, baseMs = 500, sleep = sleepMs } = {},
|
|
511
|
+
) {
|
|
512
|
+
let result;
|
|
513
|
+
for (let attempt = 1; attempt <= tries; attempt++) {
|
|
514
|
+
result = runOnce();
|
|
515
|
+
if (result.killed) return result;
|
|
516
|
+
const answered =
|
|
517
|
+
parseFailedUrls(result.out).length > 0 || /did not return 2xx/.test(result.out);
|
|
518
|
+
if (result.code === 0 || answered || !isTransientFetchError(result.out)) return result;
|
|
519
|
+
if (attempt < tries) {
|
|
520
|
+
console.log(
|
|
521
|
+
` compare hit a transient fetch error (attempt ${attempt}/${tries}), retrying`,
|
|
522
|
+
);
|
|
523
|
+
await sleep(baseMs * 2 ** (attempt - 1));
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
return result;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/**
|
|
530
|
+
* Judge the "sitemap pages exist" compare. A page missing on the build only fails the gate when
|
|
531
|
+
* production serves it (HTTP 200). A page that is 404/410 on production itself is a dead sitemap
|
|
532
|
+
* entry: reported as a warning, not a failure. Any other production answer (5xx, 401/403/429, error)
|
|
533
|
+
* is indeterminate and still counts as a failure.
|
|
534
|
+
* `probeProd(devUrl)` resolves to the production HTTP status for the same path.
|
|
535
|
+
*/
|
|
536
|
+
export async function judgeSitemapCompare(cmp, probeProd) {
|
|
537
|
+
const checked = Number(cmp.out.match(/Checking (\d+) page\(s\) exist on development/)?.[1] ?? 0);
|
|
538
|
+
const failedUrls = parseFailedUrls(cmp.out);
|
|
539
|
+
const reported = Number(cmp.out.match(/(\d+) page\(s\) did not return 2xx/)?.[1] ?? 0);
|
|
540
|
+
const warnings = [];
|
|
541
|
+
const required = [];
|
|
542
|
+
if (cmp.code !== 0 && failedUrls.length > 0 && failedUrls.length === reported) {
|
|
543
|
+
for (const { url: u, status: buildStatus } of parseFailedPages(cmp.out)) {
|
|
544
|
+
// A build answer other than 404/410 (401/403/5xx) is a build problem, never excused by production.
|
|
545
|
+
if (buildStatus !== 404 && buildStatus !== 410) {
|
|
546
|
+
required.push(u);
|
|
547
|
+
continue;
|
|
548
|
+
}
|
|
549
|
+
let status;
|
|
550
|
+
try {
|
|
551
|
+
status = await probeProd(u);
|
|
552
|
+
} catch {
|
|
553
|
+
status = 0;
|
|
554
|
+
}
|
|
555
|
+
if (status === 404 || status === 410) warnings.push(u);
|
|
556
|
+
else required.push(u);
|
|
557
|
+
}
|
|
558
|
+
} else if (cmp.code !== 0) {
|
|
559
|
+
return {
|
|
560
|
+
ok: false,
|
|
561
|
+
checked,
|
|
562
|
+
warnings,
|
|
563
|
+
detail: `site-check exit ${cmp.code}${reported ? `, ${reported} page(s) did not return 2xx but ${failedUrls.length} were listed` : ''}${sitemapRootsError(cmp.out)}`,
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
const ok = required.length === 0 && checked > 0;
|
|
567
|
+
const deadNote = warnings.length
|
|
568
|
+
? ` (WARN prod sitemap lists dead URL: ${warnings.length} page(s) also 404/410 on production)`
|
|
569
|
+
: '';
|
|
570
|
+
return {
|
|
571
|
+
ok,
|
|
572
|
+
checked,
|
|
573
|
+
warnings,
|
|
574
|
+
detail: ok
|
|
575
|
+
? `${checked - warnings.length} live production sitemap pages return 2xx on the build${deadNote}`
|
|
576
|
+
: checked === 0
|
|
577
|
+
? 'no sitemap pages were checked (empty sitemap?)'
|
|
578
|
+
: `${required.length} production-live page(s) did not return 2xx: ${required.slice(0, 3).join(', ')}`,
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/** GET following up to 5 redirects by hand, so the bypass header is decided per hop and host. Retries transient fetch errors. */
|
|
583
|
+
async function get(url, extra = {}) {
|
|
584
|
+
let current = url;
|
|
585
|
+
for (let hop = 0; hop < 6; hop++) {
|
|
586
|
+
// The body is read inside the retry so a stalled body (covered by the same timeout) is retried too.
|
|
587
|
+
const res = await withRetry(async () => {
|
|
588
|
+
const r = await fetchWithTimeout(current, {
|
|
589
|
+
redirect: 'manual',
|
|
590
|
+
headers: { ...bypassHeaders(current), ...extra },
|
|
591
|
+
});
|
|
592
|
+
const redirect = r.status >= 300 && r.status < 400 && r.headers.get('location');
|
|
593
|
+
return { status: r.status, headers: r.headers, text: redirect ? '' : await r.text() };
|
|
594
|
+
});
|
|
595
|
+
const location = res.headers.get('location');
|
|
596
|
+
if (res.status >= 300 && res.status < 400 && location) {
|
|
597
|
+
current = new URL(location, current).href;
|
|
598
|
+
continue;
|
|
599
|
+
}
|
|
600
|
+
return res;
|
|
601
|
+
}
|
|
602
|
+
throw new Error(`Too many redirects from ${url}`);
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/** HEAD following up to 5 redirects by hand (bypass header only on the deployment host). Retries transient fetch errors. */
|
|
606
|
+
async function headStatus(url) {
|
|
607
|
+
let current = url;
|
|
608
|
+
for (let hop = 0; hop < 6; hop++) {
|
|
609
|
+
const res = await withRetry(() =>
|
|
610
|
+
fetchWithTimeout(current, {
|
|
611
|
+
method: 'HEAD',
|
|
612
|
+
redirect: 'manual',
|
|
613
|
+
headers: bypassHeaders(current),
|
|
614
|
+
}),
|
|
615
|
+
);
|
|
616
|
+
const location = res.headers.get('location');
|
|
617
|
+
if (res.status >= 300 && res.status < 400 && location) {
|
|
618
|
+
current = new URL(location, current).href;
|
|
619
|
+
continue;
|
|
620
|
+
}
|
|
621
|
+
return res.status;
|
|
622
|
+
}
|
|
623
|
+
throw new Error(`Too many redirects from ${url}`);
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/** Detail (and console line) of the prod-compare stage when the compare was not asked for. */
|
|
627
|
+
export const COMPARE_NOT_RUN = 'compare: not run (on-demand)';
|
|
628
|
+
|
|
629
|
+
/** The prod-compare stage when `--compare` was not given: neither a pass nor a fail (`ok: null`, `skipped: true`). */
|
|
630
|
+
export function compareNotRunStage() {
|
|
631
|
+
return { name: 'prod compare', ok: null, skipped: true, detail: COMPARE_NOT_RUN };
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/** The gate passes when every stage that ran passed. A skipped stage counts as neither a pass nor a fail. */
|
|
635
|
+
export function gateOk(stages) {
|
|
636
|
+
return stages.filter((x) => !x.skipped).every((x) => x.ok);
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/** The draft-canary stage when no --draft-canary path was given: a failure, unless --no-draft-canary opts out. */
|
|
640
|
+
export function noCanaryStage(noCanary) {
|
|
641
|
+
return noCanary
|
|
642
|
+
? {
|
|
643
|
+
ok: true,
|
|
644
|
+
detail:
|
|
645
|
+
'SKIPPED (--no-draft-canary): this site has no draft-only page, published-only is not proven by a canary',
|
|
646
|
+
}
|
|
647
|
+
: { ok: false, detail: 'no --draft-canary given, published-only is unproven' };
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
export async function main(argv) {
|
|
651
|
+
const o = parseArgs(argv);
|
|
652
|
+
if (!o.url) throw new Error('--url (or DEPLOYMENT_URL) is required');
|
|
653
|
+
// The production URL is only used by the compare (and to resolve --sitemap-roots paths).
|
|
654
|
+
if (!o.prodUrl && (o.compare || o.sitemapRoots.length > 0))
|
|
655
|
+
throw new Error(
|
|
656
|
+
'--prod-url (or PRODUCTION_SITE_URL) is required with --compare or --sitemap-roots',
|
|
657
|
+
);
|
|
658
|
+
if (!o.hostPrefix)
|
|
659
|
+
throw new Error(
|
|
660
|
+
'--host-prefix is required (the bypass token is only sent to a matching *.vercel.app host)',
|
|
661
|
+
);
|
|
662
|
+
// The bypass token is sent to this host, so only ever one of this project's deployment hosts.
|
|
663
|
+
const host = new URL(o.url).hostname;
|
|
664
|
+
if (!host.startsWith(o.hostPrefix) || !host.endsWith('.vercel.app'))
|
|
665
|
+
throw new Error(`Refusing ${o.url}: not a ${o.hostPrefix}*.vercel.app deployment`);
|
|
666
|
+
deploymentHost = host;
|
|
667
|
+
const head = spawnSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).stdout.trim();
|
|
668
|
+
const expect = (o.expectSha ?? head).trim();
|
|
669
|
+
const stages = [];
|
|
670
|
+
const add = (name, ok, detail) => {
|
|
671
|
+
stages.push({ name, ok, detail });
|
|
672
|
+
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}: ${detail}`);
|
|
673
|
+
};
|
|
674
|
+
let sitemapWarnings = [];
|
|
675
|
+
let pages = [];
|
|
676
|
+
|
|
677
|
+
// 0. exact commit
|
|
678
|
+
const commit = checkExactCommit(o.deploymentSha, expect);
|
|
679
|
+
add('exact commit', commit.ok, commit.detail);
|
|
680
|
+
|
|
681
|
+
// 1. published-only + noindex
|
|
682
|
+
const robots = await get(`${o.url}/robots.txt`);
|
|
683
|
+
const home = await get(`${o.url}/`);
|
|
684
|
+
const disallowAll = /Disallow:\s*\/\s*$/m.test(robots.text);
|
|
685
|
+
const headerNoindex = /noindex/i.test(home.headers.get('x-robots-tag') ?? '');
|
|
686
|
+
const metaNoindex = /<meta[^>]+name=["']robots["'][^>]*noindex/i.test(home.text);
|
|
687
|
+
add(
|
|
688
|
+
'noindex',
|
|
689
|
+
robots.status === 200 && (disallowAll || headerNoindex || metaNoindex),
|
|
690
|
+
`robots.txt ${robots.status} disallow-all ${disallowAll}; home x-robots-tag noindex ${headerNoindex}, meta noindex ${metaNoindex}`,
|
|
691
|
+
);
|
|
692
|
+
for (const p of o.canaries) {
|
|
693
|
+
const r = await get(`${o.url}${p}`);
|
|
694
|
+
add(
|
|
695
|
+
`draft canary ${p}`,
|
|
696
|
+
r.status === 404,
|
|
697
|
+
`HTTP ${r.status} (404 means the draft is not served)`,
|
|
698
|
+
);
|
|
699
|
+
}
|
|
700
|
+
if (o.canaries.length === 0) {
|
|
701
|
+
const stage = noCanaryStage(o.noCanary);
|
|
702
|
+
add('draft canary', stage.ok, stage.detail);
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
// 2. full smoke
|
|
706
|
+
const smoke = run(process.execPath, [SMOKE_LIVE, '--url', o.url, o.cases], {
|
|
707
|
+
SMOKE_TEST_ENVIRONMENT: 'preview',
|
|
708
|
+
});
|
|
709
|
+
const s = smokeSummary(smoke.out);
|
|
710
|
+
add(
|
|
711
|
+
'full smoke',
|
|
712
|
+
smoke.code === 0 && !!s && s.failed === 0,
|
|
713
|
+
s
|
|
714
|
+
? `${s.cases} cases, ${s.failed} failed, ${s.warnings} warnings`
|
|
715
|
+
: `no summary (exit ${smoke.code})`,
|
|
716
|
+
);
|
|
717
|
+
if (smoke.code !== 0)
|
|
718
|
+
console.log(
|
|
719
|
+
smoke.out
|
|
720
|
+
.split('\n')
|
|
721
|
+
.filter((l) => /FAIL|fail|✗|error/i.test(l))
|
|
722
|
+
.slice(0, 30)
|
|
723
|
+
.join('\n'),
|
|
724
|
+
);
|
|
725
|
+
|
|
726
|
+
// 3. content smoke: only the cases that assert page blocks
|
|
727
|
+
const cases = JSON.parse(fs.readFileSync(o.cases, 'utf8'));
|
|
728
|
+
const asserting = (cases.cases ?? []).filter(
|
|
729
|
+
(c) => c.contentAssert && (!Array.isArray(c.contentAssert) || c.contentAssert.length),
|
|
730
|
+
);
|
|
731
|
+
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dpg-'));
|
|
732
|
+
let content;
|
|
733
|
+
try {
|
|
734
|
+
const tmp = path.join(tmpDir, 'content.cases.json');
|
|
735
|
+
fs.writeFileSync(tmp, JSON.stringify({ ...cases, cases: asserting, coverage: undefined }));
|
|
736
|
+
content = run(process.execPath, [SMOKE_LIVE, '--url', o.url, tmp], {
|
|
737
|
+
SMOKE_TEST_ENVIRONMENT: 'preview',
|
|
738
|
+
});
|
|
739
|
+
} finally {
|
|
740
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
741
|
+
}
|
|
742
|
+
const c = smokeSummary(content.out);
|
|
743
|
+
add(
|
|
744
|
+
'content smoke',
|
|
745
|
+
content.code === 0 && !!c && c.failed === 0 && asserting.length > 0,
|
|
746
|
+
c
|
|
747
|
+
? `${asserting.length} asserting cases (${c.cases} checks run incl. discovery), ${c.failed} failed`
|
|
748
|
+
: `no summary (exit ${content.code})`,
|
|
749
|
+
);
|
|
750
|
+
|
|
751
|
+
// 4a. prod compare: every production sitemap page that is live on production exists on the deployment.
|
|
752
|
+
// Pages that 404 on production itself are dead sitemap entries: a warning, not a gate failure.
|
|
753
|
+
// With --sitemap-roots only the roots this app owns are walked; without it the full production index is.
|
|
754
|
+
// Off unless --compare: then the stage is reported as not run, neither a pass nor a fail.
|
|
755
|
+
if (o.compare) {
|
|
756
|
+
const cmp =
|
|
757
|
+
o.sitemapRoots.length > 0
|
|
758
|
+
? await compareSitemapRoots({
|
|
759
|
+
rootUrls: resolveSitemapRoots(o.sitemapRoots, o.prodUrl),
|
|
760
|
+
devUrl: o.url,
|
|
761
|
+
fetchText: async (u) => {
|
|
762
|
+
const r = await get(u);
|
|
763
|
+
return { status: r.status, text: r.text };
|
|
764
|
+
},
|
|
765
|
+
headStatus,
|
|
766
|
+
})
|
|
767
|
+
: await runCompareWithRetry(() =>
|
|
768
|
+
run(
|
|
769
|
+
process.execPath,
|
|
770
|
+
[
|
|
771
|
+
SITE_CHECK,
|
|
772
|
+
o.prodUrl,
|
|
773
|
+
'--check-against',
|
|
774
|
+
o.url,
|
|
775
|
+
...(process.env.VERCEL_PROTECTION_BYPASS_TOKEN ? ['--vercel-bypass'] : []),
|
|
776
|
+
],
|
|
777
|
+
{},
|
|
778
|
+
resolveCompareTimeoutMs(o.compareTimeoutMinutes),
|
|
779
|
+
),
|
|
780
|
+
);
|
|
781
|
+
const sitemap = await judgeSitemapCompare(cmp, async (devUrl) => {
|
|
782
|
+
const u = new URL(devUrl);
|
|
783
|
+
return (await get(`${o.prodUrl}${u.pathname}${u.search}`)).status;
|
|
784
|
+
});
|
|
785
|
+
sitemapWarnings = sitemap.warnings;
|
|
786
|
+
for (const w of sitemap.warnings)
|
|
787
|
+
console.log(`WARN prod sitemap lists dead URL: ${w} (404/410 on production too)`);
|
|
788
|
+
add('prod compare: sitemap pages exist', sitemap.ok, sitemap.detail);
|
|
789
|
+
} else {
|
|
790
|
+
stages.push(compareNotRunStage());
|
|
791
|
+
console.log(COMPARE_NOT_RUN);
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
// 4a'. sitemap parity: no path the build's sitemap lists may fail the core impossible-slug guard. A hard
|
|
795
|
+
// failure (not a warning): such a path would 404 for crawlers and users while the sitemap advertises it.
|
|
796
|
+
const parity = await checkSitemapSlugParity({
|
|
797
|
+
...buildSitemapRoots(o.sitemapRoots, o.prodUrl, o.url),
|
|
798
|
+
fetchText: async (u) => {
|
|
799
|
+
const r = await get(u);
|
|
800
|
+
return { status: r.status, text: r.text };
|
|
801
|
+
},
|
|
802
|
+
});
|
|
803
|
+
add('sitemap slug guard parity', parity.ok, parity.detail);
|
|
804
|
+
|
|
805
|
+
// 4b. prod compare: text of representative pages (release rule 3). Part of the compare: only with --compare.
|
|
806
|
+
if (o.compare) {
|
|
807
|
+
const paths = asserting
|
|
808
|
+
.map((x) => x.path)
|
|
809
|
+
.filter((p, i, a) => a.indexOf(p) === i)
|
|
810
|
+
.slice(0, o.pages);
|
|
811
|
+
pages = [];
|
|
812
|
+
for (const p of paths) {
|
|
813
|
+
const [prod, dev] = await Promise.all([get(`${o.prodUrl}${p}`), get(`${o.url}${p}`)]);
|
|
814
|
+
const sim =
|
|
815
|
+
prod.status === 200 && dev.status === 200
|
|
816
|
+
? similarity(visibleLines(prod.text), visibleLines(dev.text))
|
|
817
|
+
: 0;
|
|
818
|
+
pages.push({
|
|
819
|
+
path: p,
|
|
820
|
+
prod: prod.status,
|
|
821
|
+
dev: dev.status,
|
|
822
|
+
similarity: Number(sim.toFixed(3)),
|
|
823
|
+
});
|
|
824
|
+
}
|
|
825
|
+
const bad = pages.filter((x) => x.similarity < o.minSimilarity);
|
|
826
|
+
add(
|
|
827
|
+
'prod compare: page text',
|
|
828
|
+
pages.length >= 3 && bad.length === 0,
|
|
829
|
+
`${pages.length} pages, min similarity ${Math.min(...pages.map((x) => x.similarity))} (threshold ${o.minSimilarity})`,
|
|
830
|
+
);
|
|
831
|
+
for (const p of pages)
|
|
832
|
+
console.log(` ${p.path} prod ${p.prod} dev ${p.dev} similarity ${p.similarity}`);
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
const ok = gateOk(stages);
|
|
836
|
+
const result = {
|
|
837
|
+
ok,
|
|
838
|
+
url: o.url,
|
|
839
|
+
expectSha: expect,
|
|
840
|
+
deploymentSha: o.deploymentSha ?? null,
|
|
841
|
+
stages,
|
|
842
|
+
compare: !!o.compare,
|
|
843
|
+
warnings: sitemapWarnings.map((u) => `prod sitemap lists dead URL: ${u}`),
|
|
844
|
+
sitemapSlugOffenders: parity.offenders,
|
|
845
|
+
pages,
|
|
846
|
+
smoke: s,
|
|
847
|
+
contentSmoke: c,
|
|
848
|
+
};
|
|
849
|
+
if (o.json) fs.writeFileSync(o.json, `${JSON.stringify(result, null, 2)}\n`);
|
|
850
|
+
console.log(ok ? 'develop-published gate: PASS' : 'develop-published gate: FAIL');
|
|
851
|
+
return ok ? 0 : 1;
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
855
|
+
main(process.argv.slice(2)).then(
|
|
856
|
+
(code) => process.exit(code),
|
|
857
|
+
(err) => {
|
|
858
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
859
|
+
console.error(message);
|
|
860
|
+
const i = process.argv.indexOf('--json');
|
|
861
|
+
if (i > -1 && process.argv[i + 1])
|
|
862
|
+
fs.writeFileSync(
|
|
863
|
+
process.argv[i + 1],
|
|
864
|
+
`${JSON.stringify({ ok: false, error: message, stages: [] }, null, 2)}\n`,
|
|
865
|
+
);
|
|
866
|
+
process.exit(2);
|
|
867
|
+
},
|
|
868
|
+
);
|
|
869
|
+
}
|