@neon-pixels/scripts 0.2.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.
@@ -0,0 +1,408 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { parseArgs } from "node:util";
4
+ import { r as prefixedConsole, t as describeError } from "./workflow-command-Bb1eVLow.js";
5
+ import { execFileSync } from "node:child_process";
6
+ // src/lighthouse/report.ts
7
+ const REGRESSION_LABEL = "lighthouse-regression";
8
+ const MAX_TABLE_ROWS = 100;
9
+ const MAX_CELL_LENGTH = 200;
10
+ const LOOPBACK_HOSTNAMES = /* @__PURE__ */ new Set([
11
+ "localhost",
12
+ "127.0.0.1",
13
+ "[::1]"
14
+ ]);
15
+ const ISSUE_TITLE_PREFIX = "Lighthouse regression on ";
16
+ function issueTitleFor(site) {
17
+ return `${ISSUE_TITLE_PREFIX}${site}`;
18
+ }
19
+ /** Lighthouse CI writes plain objects; anything else in the file is ignored. */
20
+ function parseAssertionResults(raw) {
21
+ const parsed = JSON.parse(raw);
22
+ if (!Array.isArray(parsed)) return [];
23
+ return parsed.filter(isPlainObject).map(keepKnownFields);
24
+ }
25
+ function isPlainObject(item) {
26
+ return item !== null && typeof item === "object" && !Array.isArray(item);
27
+ }
28
+ const TEXT_FIELDS = [
29
+ "url",
30
+ "auditId",
31
+ "auditProperty",
32
+ "operator",
33
+ "level"
34
+ ];
35
+ const NUMBER_FIELDS = ["expected", "actual"];
36
+ function keepKnownFields(item) {
37
+ const result = {};
38
+ for (const field of TEXT_FIELDS.filter((name) => typeof item[name] === "string")) result[field] = item[field];
39
+ for (const field of NUMBER_FIELDS.filter((name) => typeof item[name] === "number")) result[field] = item[field];
40
+ if (typeof item["passed"] === "boolean") result["passed"] = item["passed"];
41
+ return result;
42
+ }
43
+ function failingResults(results) {
44
+ return results.filter((result) => result.passed === false && result.level !== "warn");
45
+ }
46
+ /** The host of a page URL, or null when the result has no usable URL. */
47
+ function siteOf(result) {
48
+ try {
49
+ const { hostname } = new URL(result.url ?? "");
50
+ return LOOPBACK_HOSTNAMES.has(hostname) ? null : hostname || null;
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+ /**
56
+ * The sites with a failing assertion. A run that failed before assertions
57
+ * were recorded (a failed build) still needs one issue, filed under the
58
+ * fallback site.
59
+ */
60
+ function failingSites(results, fallbackSite) {
61
+ const sites = /* @__PURE__ */ new Set();
62
+ for (const result of failingResults(results)) sites.add(siteOf(result) ?? fallbackSite);
63
+ return sites.size > 0 ? [...sites] : [fallbackSite];
64
+ }
65
+ function resultsForSite(results, site, fallbackSite) {
66
+ return failingResults(results).filter((result) => (siteOf(result) ?? fallbackSite) === site);
67
+ }
68
+ function failedStepLabel(buildOutcome) {
69
+ if (buildOutcome === "failure") return "Build (the build failed before Lighthouse ran)";
70
+ if (buildOutcome === "cancelled") return "Build (timed out or was cancelled)";
71
+ if (buildOutcome === "skipped") return "Setup or install (checkout, Node setup, or dependency install failed before the build)";
72
+ if (buildOutcome === "success") return "Lighthouse run (collection or assertions)";
73
+ return "Unknown (the build outcome was not reported; see the run log)";
74
+ }
75
+ function auditLabel(result) {
76
+ const parts = [result.auditId, result.auditProperty].filter(Boolean);
77
+ return parts.length > 0 ? parts.join(":") : "n/a";
78
+ }
79
+ function formatScore(value) {
80
+ return typeof value === "number" ? value.toFixed(2) : "n/a";
81
+ }
82
+ function tableCell(text) {
83
+ const flat = text.replace(/[\r\n]+/g, " ");
84
+ return (flat.length > MAX_CELL_LENGTH ? `${flat.slice(0, MAX_CELL_LENGTH)}...` : flat).replace(/\|/g, "\\|");
85
+ }
86
+ function formatAssertionRows(failing) {
87
+ if (failing.length === 0) return "No failing assertions were recorded. The run failed before assertions completed; see the run log.";
88
+ const header = "| Page | Category | Score | Threshold | Level |\n| --- | --- | --- | --- | --- |";
89
+ const rows = failing.slice(0, MAX_TABLE_ROWS).map((result) => [
90
+ tableCell(result.url ?? "n/a"),
91
+ tableCell(auditLabel(result)),
92
+ formatScore(result.actual),
93
+ `${tableCell(result.operator ?? ">=")} ${formatScore(result.expected)}`,
94
+ tableCell(result.level ?? "n/a")
95
+ ].join(" | "));
96
+ const omitted = failing.length - MAX_TABLE_ROWS;
97
+ const note = omitted > 0 ? [`\n...and ${omitted} more failing assertion(s); see the run log.`] : [];
98
+ return [
99
+ header,
100
+ ...rows.map((row) => `| ${row} |`),
101
+ ...note
102
+ ].join("\n");
103
+ }
104
+ function formatCommitRange(context) {
105
+ const { repository, lastPassSha, headSha } = context;
106
+ if (!lastPassSha) return "No earlier successful scheduled run exists, so there is no commit range to compare.";
107
+ if (lastPassSha === headSha) return "No commits since the last successful scheduled run; the failure is likely flaky or caused by something external.";
108
+ return `https://github.com/${repository}/compare/${lastPassSha}...${headSha}`;
109
+ }
110
+ function commitRangeNotes(context) {
111
+ if (!context.lastPassSha || context.lastPassSha === context.headSha) return [];
112
+ return ["- Open the compare link above and look for the commit that touched the failing pages or their assets."];
113
+ }
114
+ function buildReport(context, failing) {
115
+ return [
116
+ `Scheduled Lighthouse run failed: ${context.runUrl}`,
117
+ "",
118
+ `**Failed step:** ${failedStepLabel(context.buildOutcome)}`,
119
+ "",
120
+ "### Failing pages and categories",
121
+ formatAssertionRows(failing),
122
+ "",
123
+ "### Commits since the last successful scheduled run",
124
+ formatCommitRange(context),
125
+ "",
126
+ "### Notes for the fixer",
127
+ ...commitRangeNotes(context),
128
+ "- Reproduce locally by running the same build and Lighthouse commands the workflow runs.",
129
+ `- Confirm the fix with \`gh workflow run ${context.workflowFile} --ref <branch>\`.`,
130
+ "- Do not lower Lighthouse thresholds or assertions to make this pass."
131
+ ].join("\n");
132
+ }
133
+ // src/lighthouse/file-issues.ts
134
+ async function fileSiteIssue(client, open, site, body) {
135
+ const title = issueTitleFor(site);
136
+ const existing = open.find((issue) => issue.title === title);
137
+ if (existing) {
138
+ await client.commentOnIssue(existing.number, body);
139
+ return {
140
+ site,
141
+ action: "commented",
142
+ output: `#${existing.number}`
143
+ };
144
+ }
145
+ return {
146
+ site,
147
+ action: "created",
148
+ output: await client.createRegressionIssue(title, body)
149
+ };
150
+ }
151
+ async function fileSiteIssueSafely(client, open, site, body) {
152
+ try {
153
+ return await fileSiteIssue(client, open, site, body);
154
+ } catch (error) {
155
+ return {
156
+ site,
157
+ action: "failed",
158
+ output: describeError(error)
159
+ };
160
+ }
161
+ }
162
+ /**
163
+ * Opens one issue per failing site, or comments on the site's open one. A
164
+ * site that fails is recorded and the rest still run, so the caller can report
165
+ * every issue that was filed.
166
+ */
167
+ async function fileFailureIssues(client, context, results, fallbackSite) {
168
+ const open = await client.listOpenRegressionIssues();
169
+ const filings = [];
170
+ for (const site of failingSites(results, fallbackSite)) {
171
+ const body = buildReport(context, resultsForSite(results, site, fallbackSite));
172
+ filings.push(await fileSiteIssueSafely(client, open, site, body));
173
+ }
174
+ return filings;
175
+ }
176
+ async function closeIssueSafely(client, number, comment) {
177
+ try {
178
+ await client.closeIssue(number, comment);
179
+ return {
180
+ number,
181
+ closed: true,
182
+ error: null
183
+ };
184
+ } catch (error) {
185
+ return {
186
+ number,
187
+ closed: false,
188
+ error: describeError(error)
189
+ };
190
+ }
191
+ }
192
+ /** Closes every open regression issue after a passing run; one failure does not stop the rest. */
193
+ async function closePassedIssues(client, runUrl) {
194
+ const open = await client.listOpenRegressionIssues();
195
+ const comment = runUrl ? `The scheduled Lighthouse run passed, closing: ${runUrl}` : "The scheduled Lighthouse run passed, closing.";
196
+ const results = [];
197
+ for (const issue of open) results.push(await closeIssueSafely(client, issue.number, comment));
198
+ return results;
199
+ }
200
+ // src/lighthouse/github.ts
201
+ const ISSUE_LIST_LIMIT = 100;
202
+ const LABEL_LIST_LIMIT = 1e3;
203
+ const LABELS = [{
204
+ name: REGRESSION_LABEL,
205
+ color: "B60205",
206
+ description: "Scheduled Lighthouse run failed"
207
+ }, {
208
+ name: "p1",
209
+ color: "D93F0B",
210
+ description: "Priority 1"
211
+ }];
212
+ const runGh = (args) => {
213
+ try {
214
+ return execFileSync("gh", args, {
215
+ encoding: "utf8",
216
+ stdio: "pipe"
217
+ });
218
+ } catch (error) {
219
+ const stderr = String(error.stderr ?? "").trim();
220
+ throw new Error(`gh ${args.slice(0, 2).join(" ")} failed: ${stderr}`, { cause: error });
221
+ }
222
+ };
223
+ function ghJson(gh, args) {
224
+ return JSON.parse(gh(args));
225
+ }
226
+ function missingLabels(gh, repository) {
227
+ const existing = ghJson(gh, [
228
+ "label",
229
+ "list",
230
+ "--repo",
231
+ repository,
232
+ "--limit",
233
+ String(LABEL_LIST_LIMIT),
234
+ "--json",
235
+ "name"
236
+ ]).map((label) => label.name.toLowerCase());
237
+ return LABELS.filter((label) => !existing.includes(label.name.toLowerCase()));
238
+ }
239
+ function ensureLabels(gh, repository) {
240
+ for (const label of missingLabels(gh, repository)) gh([
241
+ "label",
242
+ "create",
243
+ label.name,
244
+ "--repo",
245
+ repository,
246
+ "--color",
247
+ label.color,
248
+ "--description",
249
+ label.description
250
+ ]);
251
+ }
252
+ /** An IssueClient backed by the `gh` CLI, which reads its token from GH_TOKEN. */
253
+ function createGhIssueClient(repository, gh = runGh) {
254
+ return {
255
+ async listOpenRegressionIssues() {
256
+ return ghJson(gh, [
257
+ "issue",
258
+ "list",
259
+ "--repo",
260
+ repository,
261
+ "--label",
262
+ REGRESSION_LABEL,
263
+ "--state",
264
+ "open",
265
+ "--limit",
266
+ String(ISSUE_LIST_LIMIT),
267
+ "--json",
268
+ "number,title"
269
+ ]).filter((issue) => issue.title.startsWith(ISSUE_TITLE_PREFIX));
270
+ },
271
+ async createRegressionIssue(title, body) {
272
+ ensureLabels(gh, repository);
273
+ return gh([
274
+ "issue",
275
+ "create",
276
+ "--repo",
277
+ repository,
278
+ "--title",
279
+ title,
280
+ "--label",
281
+ `p1,${REGRESSION_LABEL}`,
282
+ "--body",
283
+ body
284
+ ]).trim();
285
+ },
286
+ async commentOnIssue(number, body) {
287
+ gh([
288
+ "issue",
289
+ "comment",
290
+ String(number),
291
+ "--repo",
292
+ repository,
293
+ "--body",
294
+ body
295
+ ]);
296
+ },
297
+ async closeIssue(number, comment) {
298
+ gh([
299
+ "issue",
300
+ "close",
301
+ String(number),
302
+ "--repo",
303
+ repository,
304
+ "--comment",
305
+ comment
306
+ ]);
307
+ },
308
+ async findLastPassSha(workflowFile) {
309
+ return ghJson(gh, [
310
+ "run",
311
+ "list",
312
+ "--repo",
313
+ repository,
314
+ "--workflow",
315
+ workflowFile,
316
+ "--event",
317
+ "schedule",
318
+ "--status",
319
+ "success",
320
+ "--limit",
321
+ "1",
322
+ "--json",
323
+ "headSha"
324
+ ])[0]?.headSha ?? null;
325
+ }
326
+ };
327
+ }
328
+ // src/lighthouse/run.ts
329
+ const systemEnvironment = {
330
+ variables: process.env,
331
+ createClient: (repository) => createGhIssueClient(repository),
332
+ readResults: (path) => existsSync(path) ? readFileSync(path, "utf8") : null,
333
+ ...prefixedConsole("np-report-lighthouse-failure")
334
+ };
335
+ function requireVariable(variables, name) {
336
+ const value = variables[name];
337
+ if (!value) throw new Error(`Missing required environment variable ${name}`);
338
+ return value;
339
+ }
340
+ function readAssertionResults(environment, path) {
341
+ try {
342
+ const raw = environment.readResults(path);
343
+ return raw === null ? [] : parseAssertionResults(raw);
344
+ } catch {
345
+ environment.warn(`Could not read or parse ${path}; reporting without assertion rows`);
346
+ return [];
347
+ }
348
+ }
349
+ async function findLastPassShaOrNull(client, workflowFile, environment) {
350
+ try {
351
+ return await client.findLastPassSha(workflowFile);
352
+ } catch (error) {
353
+ environment.warn(`Could not find the last passing run of ${workflowFile} (${describeError(error)}); reporting without a commit range`);
354
+ return null;
355
+ }
356
+ }
357
+ async function reportPassed(client, environment) {
358
+ const results = await closePassedIssues(client, environment.variables["RUN_URL"] || null);
359
+ for (const result of results.filter((item) => !item.closed)) environment.error(`Could not close #${result.number}: ${result.error}`);
360
+ const closed = results.filter((result) => result.closed).length;
361
+ environment.log(`Closed ${closed} Lighthouse regression issue(s).`);
362
+ if (closed < results.length) throw new Error("Could not close every Lighthouse regression issue");
363
+ }
364
+ async function reportFailure(client, repository, flags, environment) {
365
+ const { variables } = environment;
366
+ const workflowFile = flags.workflow || "lighthouse.yml";
367
+ const filings = await fileFailureIssues(client, {
368
+ repository,
369
+ workflowFile,
370
+ runUrl: requireVariable(variables, "RUN_URL"),
371
+ headSha: requireVariable(variables, "HEAD_SHA"),
372
+ buildOutcome: variables["BUILD_OUTCOME"] ?? "",
373
+ lastPassSha: await findLastPassShaOrNull(client, workflowFile, environment)
374
+ }, readAssertionResults(environment, flags.results || ".lighthouseci/assertion-results.json"), flags.site || repository.split("/").pop() || repository);
375
+ for (const filing of filings) environment.log(`Issue ${filing.action} for ${filing.site}: ${filing.output}`);
376
+ if (filings.some((filing) => filing.action === "failed")) throw new Error("Could not file every Lighthouse regression issue");
377
+ }
378
+ /**
379
+ * Files or updates one issue per failing site, or with `--passed` closes the
380
+ * open ones; returns the exit code.
381
+ */
382
+ async function runReportLighthouseFailure(argv, environment = systemEnvironment) {
383
+ try {
384
+ const { values } = parseArgs({
385
+ args: argv,
386
+ options: {
387
+ passed: { type: "boolean" },
388
+ results: { type: "string" },
389
+ workflow: { type: "string" },
390
+ site: { type: "string" }
391
+ }
392
+ });
393
+ const repository = requireVariable(environment.variables, "GITHUB_REPOSITORY");
394
+ const client = environment.createClient(repository);
395
+ if (values.passed) {
396
+ await reportPassed(client, environment);
397
+ return 0;
398
+ }
399
+ await reportFailure(client, repository, values, environment);
400
+ return 0;
401
+ } catch (error) {
402
+ environment.error(describeError(error));
403
+ return 1;
404
+ }
405
+ }
406
+ // src/report-lighthouse-failure.ts
407
+ process.exitCode = await runReportLighthouseFailure(process.argv.slice(2));
408
+ export {};
@@ -1,13 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import { appendFileSync } from "node:fs";
3
3
  import { parseArgs } from "node:util";
4
- import { i as createNetlifyClient, n as escapeWorkflowCommand, t as describeError } from "./workflow-command-BkYMh3G8.js";
4
+ import { n as createNetlifyClient } from "./client-fLNszLcv.js";
5
+ import { n as escapeWorkflowCommand, t as describeError } from "./workflow-command-Bb1eVLow.js";
5
6
  // src/should-deploy/decide.ts
6
- const READY_STATE = "ready";
7
- const PRODUCTION_CONTEXT = "production";
8
- function findLastDeployedSha(deploys) {
9
- return deploys.find((deploy) => deploy.state === READY_STATE && deploy.context === PRODUCTION_CONTEXT && deploy.commitRef !== null)?.commitRef ?? null;
10
- }
11
7
  function decideDeploy(currentSha, lastDeployedSha) {
12
8
  if (currentSha === null) return {
13
9
  deploy: true,
@@ -35,10 +31,12 @@ const systemEnvironment = {
35
31
  }),
36
32
  appendOutput: (path, text) => appendFileSync(path, text)
37
33
  };
34
+ const MANUAL_RUN_EVENT = "workflow_dispatch";
35
+ const MANUAL_RUN_REASON = "A manual run always deploys.";
38
36
  function log(message) {
39
37
  console.log(`np-should-deploy: ${escapeWorkflowCommand(message)}`);
40
38
  }
41
- async function lookUpLastDeployedSha(environment) {
39
+ async function lookUpPublishedSha(environment) {
42
40
  const siteId = environment.variables["NETLIFY_SITE_ID"];
43
41
  const token = environment.variables["NETLIFY_AUTH_TOKEN"];
44
42
  if (!siteId || !token) {
@@ -46,12 +44,15 @@ async function lookUpLastDeployedSha(environment) {
46
44
  return null;
47
45
  }
48
46
  try {
49
- return findLastDeployedSha(await environment.createClient(siteId, token).listProductionDeploys());
47
+ return await environment.createClient(siteId, token).getPublishedCommitRef();
50
48
  } catch (error) {
51
- log(`could not read the last deploy (${describeError(error)}).`);
49
+ log(`could not read the published deploy (${describeError(error)}).`);
52
50
  return null;
53
51
  }
54
52
  }
53
+ function isManualRun(environment) {
54
+ return environment.variables["GITHUB_EVENT_NAME"] === MANUAL_RUN_EVENT;
55
+ }
55
56
  function writeDecision(environment, deploy) {
56
57
  const outputPath = environment.variables["GITHUB_OUTPUT"];
57
58
  if (!outputPath) {
@@ -67,8 +68,13 @@ async function runShouldDeploy(argv, environment = systemEnvironment) {
67
68
  args: argv,
68
69
  options: {}
69
70
  });
71
+ if (isManualRun(environment)) {
72
+ log(MANUAL_RUN_REASON);
73
+ writeDecision(environment, true);
74
+ return 0;
75
+ }
70
76
  const currentSha = environment.variables["CURRENT_SHA"] || null;
71
- const { deploy, reason } = decideDeploy(currentSha, currentSha === null ? null : await lookUpLastDeployedSha(environment));
77
+ const { deploy, reason } = decideDeploy(currentSha, currentSha === null ? null : await lookUpPublishedSha(environment));
72
78
  log(reason);
73
79
  writeDecision(environment, deploy);
74
80
  return 0;