@benchcutlogic/reg-notify-plugin 0.0.0-stage → 0.2.1

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/index.js ADDED
@@ -0,0 +1,713 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const { z } = require('zod');
6
+ const {
7
+ designNotificationMarker,
8
+ hasDesignNotificationMarker
9
+ } = require('./design-notification-markers.js');
10
+
11
+ /**
12
+ * @benchcutlogic/reg-notify-plugin
13
+ *
14
+ * Custom reg-suit notifier that posts a rich sticky PR comment (thumbnail diff
15
+ * samples + SHA-bound approval checkbox + machine-readable JSON) and sets the
16
+ * commit status, plus optional best-effort Slack design notifications.
17
+ *
18
+ * @typedef {object} ComparisonResult
19
+ * @property {string[]} failedItems
20
+ * @property {string[]} newItems
21
+ * @property {string[]} deletedItems
22
+ * @property {string[]} passedItems
23
+ *
24
+ * @typedef {object} NotifyParams
25
+ * @property {ComparisonResult} comparisonResult
26
+ * @property {string} [reportUrl]
27
+ *
28
+ * @typedef {object} PluginOptions
29
+ * @property {string} [statusContext]
30
+ * @property {string} [customDomain]
31
+ * @property {string} [pathPrefix]
32
+ * @property {number} [sampleCap]
33
+ * @property {Record<string, string>} [slackUserMap]
34
+ * @property {string} [slackUserMapPath]
35
+ */
36
+
37
+ const DEFAULT_CONTEXT = 'reg-suit';
38
+ const VISUAL_APPROVAL_LABEL = 'visual';
39
+ const PUBLISH_ONLY_EVENTS = new Set(['push', 'workflow_dispatch']);
40
+ const PR_TITLE_EXCERPT_LENGTH = 64;
41
+ const DEFAULT_API_URL = 'https://api.github.com';
42
+ const DEFAULT_SERVER_URL = 'https://github.com';
43
+
44
+ function trimTrailingSlash(url) {
45
+ return url.replace(/\/+$/, '');
46
+ }
47
+
48
+ const githubLoginSchema = z
49
+ .string()
50
+ .min(1)
51
+ .max(100)
52
+ .regex(/^[A-Za-z0-9][A-Za-z0-9-]*(?:\[bot\])?$/)
53
+ .transform((login) => login.toLowerCase());
54
+
55
+ const githubPrTitleSchema = z
56
+ .string()
57
+ .trim()
58
+ .min(1)
59
+ .max(256)
60
+ .transform((title) => title.replace(/\s+/g, ' '));
61
+
62
+ const slackUserMapSchema = z.record(githubLoginSchema, z.string().regex(/^[A-Z][A-Z0-9]{8,}$/));
63
+
64
+ function parseSlackUserMap(raw) {
65
+ if (!raw || typeof raw !== 'object') return {};
66
+ return slackUserMapSchema.parse(raw);
67
+ }
68
+
69
+ function loadSlackUserMap(options, logger) {
70
+ if (options?.slackUserMap) {
71
+ return parseSlackUserMap(options.slackUserMap);
72
+ }
73
+ if (!options?.slackUserMapPath) return {};
74
+ const mapPath = path.resolve(process.cwd(), options.slackUserMapPath);
75
+ // Slack mentions are optional decoration on a best-effort notification, so a
76
+ // missing or malformed map only drops the mention; the visual status is unaffected.
77
+ if (!fs.existsSync(mapPath)) {
78
+ logger.warn(`slackUserMapPath ${mapPath} does not exist; Slack mentions are disabled.`);
79
+ return {};
80
+ }
81
+ try {
82
+ return parseSlackUserMap(JSON.parse(fs.readFileSync(mapPath, 'utf8')));
83
+ } catch (error) {
84
+ logger.warn(
85
+ `Could not read slackUserMapPath ${mapPath}; Slack mentions are disabled: ${error.message}`
86
+ );
87
+ return {};
88
+ }
89
+ }
90
+
91
+ function visualApprovalLabelFor(pathPrefix) {
92
+ return `visual: ${pathPrefix === 'pages' ? 'pages' : 'stories'}`;
93
+ }
94
+
95
+ function markerFor(context) {
96
+ return `<!-- ${context}:do-not-edit -->`;
97
+ }
98
+
99
+ class ForgeNotifier {
100
+ /** @param {{ coreConfig: any; workingDirs: any; logger: any; options: PluginOptions }} config */
101
+ init(config) {
102
+ this._logger = config.logger;
103
+ this._options = config.options || {};
104
+ this._token = process.env.GITHUB_TOKEN;
105
+ this._sha = process.env.GITHUB_HEAD_SHA || process.env.GITHUB_SHA;
106
+ this._eventName = process.env.GITHUB_EVENT_NAME;
107
+ this._slackDesignWebhookUrl = process.env.SLACK_DESIGN_WEBHOOK_URL;
108
+ this._slackUserMap = loadSlackUserMap(this._options, this._logger);
109
+
110
+ const githubPrAuthor = githubLoginSchema.safeParse(process.env.GITHUB_PR_AUTHOR);
111
+ this._githubPrAuthor = githubPrAuthor.success ? githubPrAuthor.data : null;
112
+ if (process.env.GITHUB_PR_AUTHOR && !githubPrAuthor.success) {
113
+ this._logger.warn('Ignoring invalid GITHUB_PR_AUTHOR value.');
114
+ }
115
+ const githubPrTitle = githubPrTitleSchema.safeParse(process.env.GITHUB_PR_TITLE);
116
+ this._githubPrTitle = githubPrTitle.success ? githubPrTitle.data : null;
117
+ if (process.env.GITHUB_PR_TITLE && !githubPrTitle.success) {
118
+ this._logger.warn('Ignoring invalid GITHUB_PR_TITLE value.');
119
+ }
120
+ this._customDomain = this._options.customDomain || process.env.REG_S3_CUSTOM_DOMAIN || '';
121
+ this._apiUrl = trimTrailingSlash(process.env.GITHUB_API_URL || DEFAULT_API_URL);
122
+ this._serverUrl = trimTrailingSlash(process.env.GITHUB_SERVER_URL || DEFAULT_SERVER_URL);
123
+ const [owner, repo] = (process.env.GITHUB_REPOSITORY || '').split('/');
124
+ this._owner = owner;
125
+ this._repo = repo;
126
+ const refMatch = (process.env.GITHUB_REF || '').match(/^refs\/pull\/(\d+)\//);
127
+ this._prFromRef = refMatch ? parseInt(refMatch[1], 10) : null;
128
+ }
129
+
130
+ /** @param {NotifyParams} params */
131
+ async notify(params) {
132
+ if (!this._token || !this._owner || !this._repo || !this._sha) {
133
+ this._logger.warn(
134
+ 'Skipping notify: GITHUB_TOKEN / GITHUB_REPOSITORY / GITHUB_SHA not set (running outside CI?).'
135
+ );
136
+ return;
137
+ }
138
+
139
+ if (PUBLISH_ONLY_EVENTS.has(this._eventName)) {
140
+ this._logger.info(
141
+ `${this._eventName} event — publish-only run; skipping status and comment.`
142
+ );
143
+ return;
144
+ }
145
+
146
+ const counts = {
147
+ changed: params.comparisonResult.failedItems.length,
148
+ new: params.comparisonResult.newItems.length,
149
+ deleted: params.comparisonResult.deletedItems.length,
150
+ passed: params.comparisonResult.passedItems.length
151
+ };
152
+
153
+ const hasRealDiff = counts.changed > 0 || counts.deleted > 0;
154
+ const state = hasRealDiff || this._isEmptyBaseline(counts) ? 'failure' : 'success';
155
+ const context = this._options.statusContext || DEFAULT_CONTEXT;
156
+
157
+ await this._postCommitStatus({
158
+ state,
159
+ context,
160
+ description: this._statusDescription(state, counts),
161
+ targetUrl: params.reportUrl
162
+ });
163
+
164
+ const prNumber = await this._resolvePullRequest();
165
+ if (!prNumber) {
166
+ this._logger.info(`No PR for ${this._sha} — skipping comment post.`);
167
+ return;
168
+ }
169
+ const designMarker = this._designNotificationMarker(context);
170
+ const shouldAttemptDesignNotification = hasRealDiff && Boolean(this._slackDesignWebhookUrl);
171
+ const body = this._buildCommentBody(params, counts, state);
172
+ const previousBody = await this._upsertComment(prNumber, body);
173
+ const alreadyNotifiedDesign = this._hasDesignNotificationMarker(previousBody, context);
174
+ await this._syncApprovalLabels(prNumber, state);
175
+ if (hasRealDiff && alreadyNotifiedDesign) {
176
+ await this._persistDesignNotificationMarker(prNumber, body, designMarker);
177
+ } else if (shouldAttemptDesignNotification) {
178
+ const delivered = await this._notifyDesign(prNumber, params.reportUrl, counts);
179
+ if (delivered) {
180
+ await this._persistDesignNotificationMarker(prNumber, body, designMarker);
181
+ }
182
+ }
183
+ }
184
+
185
+ async _postCommitStatus({ state, context, description, targetUrl }) {
186
+ const body = { state, context, description };
187
+ if (targetUrl) body.target_url = targetUrl;
188
+ await this._gh('POST', `/repos/${this._owner}/${this._repo}/statuses/${this._sha}`, body);
189
+ this._logger.info(`Set '${context}' status to ${state} on ${this._sha}.`);
190
+ }
191
+
192
+ async _resolvePullRequest() {
193
+ if (this._prFromRef) return this._prFromRef;
194
+ if (this._eventName === 'pull_request' || this._eventName === 'pull_request_target') {
195
+ return null;
196
+ }
197
+ try {
198
+ const prs = await this._gh(
199
+ 'GET',
200
+ `/repos/${this._owner}/${this._repo}/commits/${this._sha}/pulls`
201
+ );
202
+ const open = (prs || []).find(
203
+ (p) => p.state === 'open' && p.head && p.head.sha === this._sha
204
+ );
205
+ return open ? open.number : null;
206
+ } catch (e) {
207
+ this._logger.warn(`PR lookup for ${this._sha} failed: ${e.message}`);
208
+ return null;
209
+ }
210
+ }
211
+
212
+ async _upsertComment(prNumber, body) {
213
+ const comments = await this._paginate(
214
+ `/repos/${this._owner}/${this._repo}/issues/${prNumber}/comments`
215
+ );
216
+ const marker = markerFor(this._options.statusContext || DEFAULT_CONTEXT);
217
+ const existing = comments.find(
218
+ (comment) =>
219
+ comment.user?.login === 'github-actions[bot]' &&
220
+ comment.body &&
221
+ comment.body.includes(marker)
222
+ );
223
+ if (existing) {
224
+ await this._gh(
225
+ 'PATCH',
226
+ `/repos/${this._owner}/${this._repo}/issues/comments/${existing.id}`,
227
+ {
228
+ body
229
+ }
230
+ );
231
+ this._logger.info(`Updated sticky comment ${existing.id} on PR #${prNumber}.`);
232
+ } else {
233
+ await this._gh('POST', `/repos/${this._owner}/${this._repo}/issues/${prNumber}/comments`, {
234
+ body
235
+ });
236
+ this._logger.info(`Created sticky comment on PR #${prNumber}.`);
237
+ }
238
+ return existing && existing.body ? existing.body : '';
239
+ }
240
+
241
+ _designNotificationMarker(context) {
242
+ return designNotificationMarker(context);
243
+ }
244
+
245
+ _hasDesignNotificationMarker(body, context) {
246
+ return hasDesignNotificationMarker(body, context);
247
+ }
248
+
249
+ async _persistDesignNotificationMarker(prNumber, body, marker) {
250
+ try {
251
+ await this._upsertComment(prNumber, `${body}\n${marker}\n`);
252
+ } catch (error) {
253
+ this._logger.warn(
254
+ `Slack notification was delivered, but its deduplication marker could not be persisted; visual CI is unchanged: ${error.message}`
255
+ );
256
+ }
257
+ }
258
+
259
+ _designReviewerMention() {
260
+ const slackUserId = this._githubPrAuthor ? this._slackUserMap[this._githubPrAuthor] : null;
261
+ return slackUserId ? `<@${slackUserId}>` : null;
262
+ }
263
+
264
+ _designPullRequestLabel(prNumber, prUrl) {
265
+ const prLink = `<${prUrl}|PR #${prNumber}>`;
266
+ if (!this._githubPrTitle) return prLink;
267
+
268
+ const withoutConventionalPrefix = this._githubPrTitle.replace(
269
+ /^(?:feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(?:\([^)]+\))?!?:\s*/i,
270
+ ''
271
+ );
272
+ const excerpt =
273
+ withoutConventionalPrefix.length > PR_TITLE_EXCERPT_LENGTH
274
+ ? `${withoutConventionalPrefix.slice(0, PR_TITLE_EXCERPT_LENGTH - 3).trimEnd()}...`
275
+ : withoutConventionalPrefix;
276
+ return `${prLink} · ${escapeSlackText(excerpt)}`;
277
+ }
278
+
279
+ async _notifyDesign(prNumber, reportUrl, counts) {
280
+ const visualContext =
281
+ (this._options.pathPrefix || 'storybook') === 'pages' ? 'pages' : 'stories';
282
+ const summary = [
283
+ counts.changed > 0 ? `${counts.changed} changed` : null,
284
+ counts.deleted > 0 ? `${counts.deleted} deleted` : null
285
+ ]
286
+ .filter(Boolean)
287
+ .join(', ');
288
+ const prUrl = `${this._serverUrl}/${this._owner}/${this._repo}/pull/${prNumber}`;
289
+ const text = [
290
+ 'VISUAL REVIEW',
291
+ this._designReviewerMention(),
292
+ this._designPullRequestLabel(prNumber, prUrl),
293
+ visualContext,
294
+ summary,
295
+ reportUrl ? `<${reportUrl}|View diff>` : null
296
+ ]
297
+ .filter(Boolean)
298
+ .join(' | ');
299
+
300
+ try {
301
+ const response = await fetch(this._slackDesignWebhookUrl, {
302
+ method: 'POST',
303
+ headers: { 'Content-Type': 'application/json' },
304
+ body: JSON.stringify({ text })
305
+ });
306
+ if (!response.ok) {
307
+ this._logger.warn(
308
+ `Slack design webhook returned ${response.status}; visual CI is unchanged.`
309
+ );
310
+ return false;
311
+ }
312
+ this._logger.info(`Notified design of ${visualContext} review for PR #${prNumber}.`);
313
+ return true;
314
+ } catch (e) {
315
+ this._logger.warn(`Slack design webhook failed; visual CI is unchanged: ${e.message}`);
316
+ return false;
317
+ }
318
+ }
319
+
320
+ _approvalLabel() {
321
+ return visualApprovalLabelFor(this._options.pathPrefix || 'storybook');
322
+ }
323
+
324
+ async _syncApprovalLabels(prNumber, state) {
325
+ try {
326
+ const scopedLabel = this._approvalLabel();
327
+ if (state === 'failure') {
328
+ await this._ensureLabel(VISUAL_APPROVAL_LABEL, 'd73a4a', 'Visual review is required');
329
+ await this._ensureLabel(
330
+ scopedLabel,
331
+ 'd73a4a',
332
+ `Visual review is required for the ${scopedLabel.slice('visual: '.length)} diff`
333
+ );
334
+ await this._gh('POST', `/repos/${this._owner}/${this._repo}/issues/${prNumber}/labels`, {
335
+ labels: [VISUAL_APPROVAL_LABEL, scopedLabel]
336
+ });
337
+ this._logger.info(`Marked PR #${prNumber} as awaiting ${scopedLabel}.`);
338
+ return;
339
+ }
340
+
341
+ await this._removeLabel(prNumber, scopedLabel);
342
+ const labels = await this._gh(
343
+ 'GET',
344
+ `/repos/${this._owner}/${this._repo}/issues/${prNumber}/labels`
345
+ );
346
+ const hasOtherVisualApproval = (labels || []).some(
347
+ (label) =>
348
+ label.name !== scopedLabel &&
349
+ typeof label.name === 'string' &&
350
+ label.name.startsWith('visual: ')
351
+ );
352
+ if (!hasOtherVisualApproval) await this._removeLabel(prNumber, VISUAL_APPROVAL_LABEL);
353
+ this._logger.info(`Cleared ${scopedLabel} from PR #${prNumber}.`);
354
+ } catch (e) {
355
+ this._logger.warn(`Could not sync visual-approval labels for PR #${prNumber}: ${e.message}`);
356
+ }
357
+ }
358
+
359
+ async _ensureLabel(name, color, description) {
360
+ try {
361
+ await this._gh(
362
+ 'GET',
363
+ `/repos/${this._owner}/${this._repo}/labels/${encodeURIComponent(name)}`
364
+ );
365
+ } catch (e) {
366
+ if (!e.message.includes(': 404')) throw e;
367
+ await this._gh('POST', `/repos/${this._owner}/${this._repo}/labels`, {
368
+ name,
369
+ color,
370
+ description
371
+ });
372
+ }
373
+ }
374
+
375
+ async _removeLabel(prNumber, name) {
376
+ try {
377
+ await this._gh(
378
+ 'DELETE',
379
+ `/repos/${this._owner}/${this._repo}/issues/${prNumber}/labels/${encodeURIComponent(name)}`
380
+ );
381
+ } catch (e) {
382
+ if (!e.message.includes(': 404')) throw e;
383
+ }
384
+ }
385
+
386
+ _buildCommentBody(params, counts, state) {
387
+ const cap = this._options.sampleCap ?? 5;
388
+ const pathPrefix = this._options.pathPrefix || 'storybook';
389
+ const reportBase = this._customDomain
390
+ ? `https://${this._customDomain}/${pathPrefix}/${this._sha}`
391
+ : null;
392
+ const reportUrl = reportBase ? `${reportBase}/index.html` : params.reportUrl;
393
+ const rawUrl = reportBase ? `${reportBase}/out.json` : null;
394
+ const shortSha = this._sha.slice(0, 7);
395
+ const context = this._options.statusContext || DEFAULT_CONTEXT;
396
+
397
+ const marker = markerFor(context);
398
+ const isPages = pathPrefix === 'pages';
399
+ const heading = isPages ? '📸 Page visual diff' : '📸 Storybook visual diff';
400
+
401
+ const lines = [];
402
+ lines.push(marker);
403
+ lines.push(`<!-- sha: ${this._sha} -->`);
404
+ lines.push('');
405
+ lines.push(`### ${heading}`);
406
+ lines.push('');
407
+ lines.push(
408
+ `Changed: **${counts.changed}** · New: **${counts.new}** · Deleted: **${counts.deleted}** · Passed: ${counts.passed}`
409
+ );
410
+ lines.push('');
411
+
412
+ if (state === 'failure' && this._isEmptyBaseline(counts)) {
413
+ lines.push(
414
+ `> ⚠️ **No baseline found.** All ${counts.new} ${counts.new === 1 ? 'story' : 'stories'} registered as new and none matched a prior snapshot, so reg-suit compared against an empty baseline. No published snapshot was found at the current target-branch commit or its recent first-parent ancestors. Repair the target branch's baseline publish and re-run, or approve to adopt these screenshots as the baseline.`
415
+ );
416
+ lines.push('');
417
+ lines.push(`- [ ] **Re-run comparison** for \`${shortSha}\``);
418
+ lines.push(`- [ ] **Approve screenshots** for \`${shortSha}\``);
419
+ lines.push('');
420
+ lines.push(
421
+ `_Tick **Re-run comparison** to diff again against the latest published baseline, or **Approve screenshots** to flip the \`${context}\` status to success. Both boxes reset on every push and are bound to the SHA above._`
422
+ );
423
+ lines.push('');
424
+ } else if (state === 'failure') {
425
+ lines.push(`- [ ] **Approve screenshots** for \`${shortSha}\``);
426
+ lines.push('');
427
+ lines.push(
428
+ `_Tick the box to flip the \`${context}\` commit status to success. The box resets on every push — your approval is bound to the SHA above._`
429
+ );
430
+ lines.push('');
431
+ } else if (counts.new > 0) {
432
+ lines.push(
433
+ `_Auto-approved: ${counts.new} new ${counts.new === 1 ? 'story' : 'stories'}, no changed/deleted items._`
434
+ );
435
+ lines.push('');
436
+ } else {
437
+ lines.push('_No visual changes._');
438
+ lines.push('');
439
+ }
440
+
441
+ if (reportUrl) lines.push(`- [Full HTML report](${reportUrl})`);
442
+ if (rawUrl)
443
+ lines.push(
444
+ `- [Raw JSON (\`out.json\`)](${rawUrl}) — machine-readable counts + per-story paths`
445
+ );
446
+ if (reportUrl || rawUrl) lines.push('');
447
+
448
+ if (reportBase) {
449
+ this._appendChanged(
450
+ lines,
451
+ params.comparisonResult.failedItems,
452
+ counts.changed,
453
+ reportBase,
454
+ cap
455
+ );
456
+ this._appendNew(lines, params.comparisonResult.newItems, counts.new, reportBase, cap);
457
+ this._appendDeleted(
458
+ lines,
459
+ params.comparisonResult.deletedItems,
460
+ counts.deleted,
461
+ reportBase,
462
+ cap
463
+ );
464
+ }
465
+
466
+ if (state === 'failure') this._appendAgentHint(lines);
467
+
468
+ const fullPayload = {
469
+ sha: this._sha,
470
+ state,
471
+ context,
472
+ report: reportUrl,
473
+ raw: rawUrl,
474
+ counts,
475
+ changed: params.comparisonResult.failedItems.map((s) => {
476
+ const p = encodePathSegments(s);
477
+ return {
478
+ story: s,
479
+ ...(reportBase && {
480
+ expected: `${reportBase}/expected/${p}`,
481
+ actual: `${reportBase}/actual/${p}`,
482
+ diff: `${reportBase}/diff/${p}`
483
+ })
484
+ };
485
+ }),
486
+ new: params.comparisonResult.newItems.map((s) => {
487
+ const p = encodePathSegments(s);
488
+ return {
489
+ story: s,
490
+ ...(reportBase && { actual: `${reportBase}/actual/${p}` })
491
+ };
492
+ }),
493
+ deleted: params.comparisonResult.deletedItems.map((s) => {
494
+ const p = encodePathSegments(s);
495
+ return {
496
+ story: s,
497
+ ...(reportBase && { expected: `${reportBase}/expected/${p}` })
498
+ };
499
+ })
500
+ };
501
+ const PAYLOAD_LIMIT = 60_000;
502
+ let payload = JSON.stringify(fullPayload);
503
+ if (payload.length > PAYLOAD_LIMIT) {
504
+ this._logger.info(
505
+ `reg-suit-data payload ${payload.length} chars exceeds ${PAYLOAD_LIMIT}; falling back to summary-only.`
506
+ );
507
+ payload = JSON.stringify({
508
+ sha: this._sha,
509
+ state,
510
+ context,
511
+ report: reportUrl,
512
+ raw: rawUrl,
513
+ counts,
514
+ truncated: true
515
+ });
516
+ }
517
+ lines.push('');
518
+ lines.push('<!-- reg-suit-data:');
519
+ lines.push(payload);
520
+ lines.push('-->');
521
+
522
+ return lines.join('\n');
523
+ }
524
+
525
+ _appendChanged(lines, items, total, base, cap) {
526
+ if (items.length === 0) return;
527
+ lines.push(`#### Changed (${total})`);
528
+ lines.push('');
529
+ lines.push('| Story | Before | After | Diff |');
530
+ lines.push('|---|---|---|---|');
531
+ for (const item of items.slice(0, cap)) {
532
+ const p = encodePathSegments(item);
533
+ lines.push(
534
+ `| ${escapeMarkdownTableCell(item)} | ![](${base}/expected/${p}) | ![](${base}/actual/${p}) | ![](${base}/diff/${p}) |`
535
+ );
536
+ }
537
+ this._appendOverflow(lines, total, cap, base);
538
+ lines.push('');
539
+ }
540
+
541
+ _appendNew(lines, items, total, base, cap) {
542
+ if (items.length === 0) return;
543
+ lines.push(`#### New (${total})`);
544
+ lines.push('');
545
+ for (const item of items.slice(0, cap)) {
546
+ const p = encodePathSegments(item);
547
+ lines.push(
548
+ `<details><summary><code>${escapeHtml(item)}</code></summary>\n\n![](${base}/actual/${p})\n\n</details>`
549
+ );
550
+ }
551
+ this._appendOverflow(lines, total, cap, base);
552
+ lines.push('');
553
+ }
554
+
555
+ _appendDeleted(lines, items, total, base, cap) {
556
+ if (items.length === 0) return;
557
+ lines.push(`#### Deleted (${total})`);
558
+ lines.push('');
559
+ for (const item of items.slice(0, cap)) {
560
+ const p = encodePathSegments(item);
561
+ lines.push(
562
+ `<details><summary><code>${escapeHtml(item)}</code></summary>\n\n![](${base}/expected/${p})\n\n</details>`
563
+ );
564
+ }
565
+ this._appendOverflow(lines, total, cap, base);
566
+ lines.push('');
567
+ }
568
+
569
+ _appendOverflow(lines, total, cap, base) {
570
+ if (total > cap) {
571
+ lines.push('');
572
+ lines.push(`…${total - cap} more in the [full report](${base}/index.html).`);
573
+ }
574
+ }
575
+
576
+ _appendAgentHint(lines) {
577
+ lines.push('<details><summary>🤖 Triaging this as an AI agent?</summary>');
578
+ lines.push('');
579
+ lines.push('```text');
580
+ lines.push('Read the reg-suit-data JSON below (counts + per-story expected/actual/diff');
581
+ lines.push('URLs + the head sha this comment is bound to), then classify by counts:');
582
+ lines.push('- changed>0 on stories your diff TOUCHED -> real visual change; a human');
583
+ lines.push(
584
+ " approves via the Approve-screenshots box (sha-bound, perm-gated) -- don't fake it."
585
+ );
586
+ lines.push('- changed>0 on stories you did NOT touch -> pixel flake; fix at the root');
587
+ lines.push(
588
+ ' (freeze animations, raise matchingThreshold, render portals inline), not a re-run.'
589
+ );
590
+ lines.push('- new>0 AND passed==0 -> empty baseline; run');
591
+ lines.push(" check the PR's current base SHA and recent first-parent push CI runs:");
592
+ lines.push(' still running -> re-run; all unpublished -> repair the base baseline.');
593
+ lines.push(
594
+ '- deleted>0 -> story removed/renamed; intended->approve, else fix.'
595
+ );
596
+ lines.push(
597
+ 'These are commit statuses set inside a job -> re-run the whole run, not failed-jobs.'
598
+ );
599
+ lines.push('```');
600
+ lines.push('');
601
+ lines.push("_Consult this repository's visual-regression guidance for the full playbook._");
602
+ lines.push('');
603
+ }
604
+
605
+ _statusDescription(state, counts) {
606
+ if (state === 'success') {
607
+ if (counts.new > 0) return `auto-approved: ${counts.new} new, ${counts.passed} passed`;
608
+ return `${counts.passed} stories unchanged`;
609
+ }
610
+ if (this._isEmptyBaseline(counts)) {
611
+ return `no baseline found (${counts.new} new, 0 passed) — re-run once snapshots publish`;
612
+ }
613
+ return `${counts.changed} changed, ${counts.new} new, ${counts.deleted} deleted`;
614
+ }
615
+
616
+ _isEmptyBaseline(counts) {
617
+ return counts.new > 0 && counts.passed === 0 && counts.changed === 0 && counts.deleted === 0;
618
+ }
619
+
620
+ async _gh(method, apiPath, body) {
621
+ const init = {
622
+ method,
623
+ headers: {
624
+ Authorization: `Bearer ${this._token}`,
625
+ Accept: 'application/vnd.github+json',
626
+ 'X-GitHub-Api-Version': '2022-11-28',
627
+ 'User-Agent': 'benchcutlogic-reg-notify-plugin'
628
+ }
629
+ };
630
+ if (body !== undefined) {
631
+ init.headers['Content-Type'] = 'application/json';
632
+ init.body = JSON.stringify(body);
633
+ }
634
+ const res = await fetch(`${this._apiUrl}${apiPath}`, init);
635
+ if (!res.ok) {
636
+ const text = await res.text();
637
+ throw new Error(`GitHub API ${method} ${apiPath}: ${res.status} ${text}`);
638
+ }
639
+ if (res.status === 204) return null;
640
+ return res.json();
641
+ }
642
+
643
+ async _paginate(apiPath) {
644
+ const results = [];
645
+ let url = `${this._apiUrl}${apiPath}${apiPath.includes('?') ? '&' : '?'}per_page=100`;
646
+ while (url) {
647
+ const res = await fetch(url, {
648
+ headers: {
649
+ Authorization: `Bearer ${this._token}`,
650
+ Accept: 'application/vnd.github+json',
651
+ 'X-GitHub-Api-Version': '2022-11-28',
652
+ 'User-Agent': 'benchcutlogic-reg-notify-plugin'
653
+ }
654
+ });
655
+ if (!res.ok) throw new Error(`GitHub API GET ${url}: ${res.status}`);
656
+ const page = await res.json();
657
+ results.push(...page);
658
+ url = parseNextLink(res.headers.get('link'));
659
+ }
660
+ return results;
661
+ }
662
+ }
663
+
664
+ function parseNextLink(linkHeader) {
665
+ if (!linkHeader) return null;
666
+ const m = linkHeader.match(/<([^>]+)>;\s*rel="next"/);
667
+ return m ? m[1] : null;
668
+ }
669
+
670
+ function encodePathSegments(p) {
671
+ return p.split('/').map(encodeURIComponent).join('/');
672
+ }
673
+
674
+ function normalizeStoryText(value) {
675
+ return String(value).replace(/[\r\n]+/g, ' ');
676
+ }
677
+
678
+ function escapeInlineCode(value) {
679
+ const text = normalizeStoryText(value);
680
+ const longestFence = Math.max(0, ...(text.match(/`+/g) || []).map((fence) => fence.length));
681
+ const fence = '`'.repeat(longestFence + 1);
682
+ return `${fence}${text}${fence}`;
683
+ }
684
+
685
+ function escapeMarkdownTableCell(value) {
686
+ return escapeInlineCode(normalizeStoryText(value).replaceAll('|', '\\|'));
687
+ }
688
+
689
+ function escapeHtml(value) {
690
+ return normalizeStoryText(value)
691
+ .replaceAll('&', '&amp;')
692
+ .replaceAll('<', '&lt;')
693
+ .replaceAll('>', '&gt;')
694
+ .replaceAll('"', '&quot;')
695
+ .replaceAll("'", '&#39;');
696
+ }
697
+
698
+ function escapeSlackText(text) {
699
+ return text.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
700
+ }
701
+
702
+ const pluginFactory = () => ({ notifier: new ForgeNotifier() });
703
+
704
+ module.exports = pluginFactory;
705
+ module.exports.default = pluginFactory;
706
+ module.exports.ForgeNotifier = ForgeNotifier;
707
+ module.exports.markerFor = markerFor;
708
+ module.exports.DEFAULT_CONTEXT = DEFAULT_CONTEXT;
709
+ module.exports.VISUAL_APPROVAL_LABEL = VISUAL_APPROVAL_LABEL;
710
+ module.exports.visualApprovalLabelFor = visualApprovalLabelFor;
711
+ module.exports.parseSlackUserMap = parseSlackUserMap;
712
+ module.exports.designNotificationMarker = designNotificationMarker;
713
+ module.exports.hasDesignNotificationMarker = hasDesignNotificationMarker;