@nitpicker/report-google-sheets 0.19.0 → 0.20.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 (56) hide show
  1. package/lib/data/create-discrepancies.d.ts +10 -12
  2. package/lib/data/create-discrepancies.js +27 -31
  3. package/lib/data/create-image-list.d.ts +26 -6
  4. package/lib/data/create-image-list.js +65 -39
  5. package/lib/data/create-links.d.ts +18 -1
  6. package/lib/data/create-links.js +91 -55
  7. package/lib/data/create-page-list.d.ts +24 -24
  8. package/lib/data/create-page-list.js +177 -225
  9. package/lib/data/create-referrers-relational-table.d.ts +13 -7
  10. package/lib/data/create-referrers-relational-table.js +57 -47
  11. package/lib/data/create-resources-relational-table.d.ts +7 -0
  12. package/lib/data/create-resources-relational-table.js +41 -33
  13. package/lib/data/create-resources.d.ts +24 -124
  14. package/lib/data/create-resources.js +100 -264
  15. package/lib/data/create-violations.d.ts +7 -6
  16. package/lib/data/create-violations.js +34 -19
  17. package/lib/dedupe-progress-message.d.ts +17 -0
  18. package/lib/dedupe-progress-message.js +26 -0
  19. package/lib/format-progress-count.d.ts +19 -0
  20. package/lib/format-progress-count.js +22 -0
  21. package/lib/open-report-archive.d.ts +54 -0
  22. package/lib/open-report-archive.js +76 -0
  23. package/lib/report.d.ts +16 -12
  24. package/lib/report.js +101 -94
  25. package/lib/reports/get-plugin-reports.d.ts +14 -6
  26. package/lib/reports/get-plugin-reports.js +14 -34
  27. package/lib/sheets/create-sheets.d.ts +66 -36
  28. package/lib/sheets/create-sheets.js +228 -362
  29. package/lib/sheets/estimate-cell-budget.d.ts +55 -0
  30. package/lib/sheets/estimate-cell-budget.js +56 -0
  31. package/lib/sheets/types.d.ts +111 -91
  32. package/lib/test-helpers/assert-no-lazy-cells.d.ts +16 -0
  33. package/lib/test-helpers/assert-no-lazy-cells.js +23 -0
  34. package/lib/test-helpers/cell-inspection.d.ts +20 -0
  35. package/lib/test-helpers/cell-inspection.js +21 -0
  36. package/lib/test-helpers/create-mock-sheet.d.ts +30 -0
  37. package/lib/test-helpers/create-mock-sheet.js +71 -0
  38. package/lib/test-helpers/one-chunk.d.ts +8 -0
  39. package/lib/test-helpers/one-chunk.js +11 -0
  40. package/lib/utils/join-urls-for-note.d.ts +27 -0
  41. package/lib/utils/join-urls-for-note.js +48 -0
  42. package/lib/utils/truncate-note-text.d.ts +15 -0
  43. package/lib/utils/truncate-note-text.js +23 -0
  44. package/package.json +7 -9
  45. package/lib/archive.d.ts +0 -29
  46. package/lib/archive.js +0 -49
  47. package/lib/sheets/run-finalize-resources.d.ts +0 -40
  48. package/lib/sheets/run-finalize-resources.js +0 -44
  49. package/lib/types.d.ts +0 -11
  50. package/lib/types.js +0 -1
  51. package/lib/utils/canonicalize-url.d.ts +0 -53
  52. package/lib/utils/canonicalize-url.js +0 -105
  53. package/lib/utils/has-prop-filter.d.ts +0 -18
  54. package/lib/utils/has-prop-filter.js +0 -19
  55. package/lib/utils/sort-resources-by-url.d.ts +0 -69
  56. package/lib/utils/sort-resources-by-url.js +0 -223
@@ -1,8 +1,8 @@
1
- import { reportLog } from '../debug.js';
1
+ import { getResourceReferrerUrlsByResourceIds, streamAllResourcesRaw, streamResourceGroups, } from '@nitpicker/query';
2
2
  import { createCellData } from '../sheets/create-cell-data.js';
3
3
  import { defaultCellFormat } from '../sheets/default-cell-format.js';
4
- import { canonicalizeUrl, extractQueryPairs } from '../utils/canonicalize-url.js';
5
- import { naturalCompare } from '../utils/sort-resources-by-url.js';
4
+ import { joinUrlsForNote } from '../utils/join-urls-for-note.js';
5
+ import { truncateNoteText } from '../utils/truncate-note-text.js';
6
6
  const RAW_HEADERS = [
7
7
  'URL',
8
8
  'Status Code',
@@ -21,214 +21,61 @@ const DEDUPE_HEADERS = [
21
21
  'Count',
22
22
  'Query Pattern',
23
23
  ];
24
- /**
25
- * Safety cap for the joined referrer URL list inserted into a cell note.
26
- * Google Sheets caps cell content / notes around 50,000 characters; we
27
- * truncate well below that to leave room for the "and N more" suffix.
28
- */
29
- export const NOTE_MAX_LENGTH = 49_000;
30
- /**
31
- * Maximum number of unique values to keep per query parameter key in
32
- * dedupe mode. The Query Pattern cell only shows unique counts, but
33
- * we keep a small sample for cell notes and to avoid unbounded memory
34
- * growth on trackers that send a unique-per-request value
35
- * (e.g. session IDs).
36
- */
37
- export const MAX_PARAM_VALUE_SAMPLES = 100;
38
- /**
39
- * Field separator and `null` marker used in {@link dedupeKey}. Both
40
- * are non-printable ASCII control characters that cannot appear in
41
- * an HTTP status code, `Content-Type`, or any URL we pull out of the
42
- * archive — so they are safe to use as in-band sentinels.
43
- */
44
- const DEDUPE_KEY_SEP = String.fromCodePoint(1);
45
- const DEDUPE_KEY_NULL = String.fromCodePoint(2);
46
- /**
47
- * Builds the Map key for a dedupe entry.
48
- *
49
- * Concatenates `status`, `contentType`, and `canonical` with a
50
- * non-printable separator. A dedicated `null` marker keeps `null`
51
- * distinct from `''` for `contentType`, and from `0` for `status`,
52
- * so e.g. `(canonical, 200, null)` and `(canonical, 200, '')` land
53
- * in different aggregation buckets.
54
- *
55
- * String concatenation is used instead of {@link JSON.stringify}
56
- * because this function is called once per raw resource — on a
57
- * million-resource archive `JSON.stringify` allocated roughly a
58
- * million transient `SeqString`s, dominating Phase 3 wall-clock
59
- * time. Plain concatenation is several times faster and produces
60
- * the same collision-free key.
61
- * @param canonical - The canonicalized URL.
62
- * @param status - HTTP status code (nullable).
63
- * @param contentType - HTTP content type (nullable).
64
- */
65
- export function dedupeKey(canonical, status, contentType) {
66
- const statusPart = status === null ? DEDUPE_KEY_NULL : String(status);
67
- const contentTypePart = contentType === null ? DEDUPE_KEY_NULL : contentType;
68
- return statusPart + DEDUPE_KEY_SEP + contentTypePart + DEDUPE_KEY_SEP + canonical;
69
- }
70
- /**
71
- * Joins referrer URLs into a single newline-separated string, truncating
72
- * at `maxLength` to stay within Google Sheets' note size cap. When
73
- * truncated, appends a `... and N more` line where `N` counts every URL
74
- * that did not fit, including the one whose insertion would have
75
- * crossed the limit.
76
- * @param referrers - The set of unique referrer page URLs.
77
- * @param maxLength - Optional override for the character cap (defaults to {@link NOTE_MAX_LENGTH}).
78
- */
79
- export function joinReferrersForNote(referrers, maxLength = NOTE_MAX_LENGTH) {
80
- const total = referrers.size;
81
- if (total === 0) {
82
- return '';
83
- }
84
- const kept = [];
85
- let used = 0;
86
- let seen = 0;
87
- for (const url of referrers) {
88
- seen++;
89
- const next = used + url.length + (kept.length > 0 ? 1 : 0);
90
- if (next > maxLength) {
91
- const remaining = total - seen + 1;
92
- kept.push(`... and ${remaining} more`);
93
- break;
94
- }
95
- kept.push(url);
96
- used = next;
97
- }
98
- return kept.join('\n');
99
- }
100
- /**
101
- * Records a single `(key, value)` pair from a raw resource URL into
102
- * the entry's per-key value tracker. New keys allocate a tracker; the
103
- * value Set stops growing past {@link MAX_PARAM_VALUE_SAMPLES}, after
104
- * which subsequent observations increment `overflowedCount` so
105
- * {@link formatQueryPattern} can detect lost resolution and append `+`.
106
- * @param entry - The dedupe entry to merge into.
107
- * @param key - The query parameter key.
108
- * @param value - The raw value substring (already extracted, not decoded).
109
- */
110
- function recordParamValue(entry, key, value) {
111
- let tracker = entry.paramValues.get(key);
112
- if (!tracker) {
113
- tracker = { values: new Set(), overflowedCount: 0 };
114
- entry.paramValues.set(key, tracker);
115
- }
116
- if (tracker.values.size < MAX_PARAM_VALUE_SAMPLES) {
117
- tracker.values.add(value);
118
- }
119
- else {
120
- tracker.overflowedCount++;
121
- }
122
- }
123
- /**
124
- * Formats the Query Pattern cell for a dedupe entry. Each tracked key
125
- * gets a `key=N` token where `N` is the number of distinct values
126
- * sampled. `+` is appended only when {@link ParamValueTracker.overflowedCount}
127
- * is non-zero — i.e. when at least one observation arrived after the
128
- * sample set was already full. Duplicate observations that arrive
129
- * while the sample set still has capacity do NOT trigger `+`.
130
- *
131
- * This gives precise semantics:
132
- *
133
- * - `key=1` — exactly one distinct value, seen any number of times
134
- * - `key=99` — 99 distinct values, sample set still had room
135
- * - `key=100` — exactly 100 distinct values, no observation lost
136
- * - `key=100+` — sample set was capped and at least one further
137
- * observation could not be recorded (real cardinality unknown but
138
- * at least 100)
139
- *
140
- * Keys are sorted alphabetically to match the canonical URL.
141
- *
142
- * Returns `null` for entries without any query parameters so the cell
143
- * appears empty in Google Sheets.
144
- * @param entry - The dedupe entry to format.
145
- */
146
- export function formatQueryPattern(entry) {
147
- if (entry.paramValues.size === 0) {
148
- return null;
149
- }
150
- const keys = [...entry.paramValues.keys()].toSorted();
151
- const parts = [];
152
- for (const key of keys) {
153
- const tracker = entry.paramValues.get(key);
154
- const overflowed = tracker.overflowedCount > 0;
155
- parts.push(`${key}=${tracker.values.size}${overflowed ? '+' : ''}`);
156
- }
157
- return parts.join(', ');
158
- }
159
24
  /**
160
25
  * Formats the Content Length cell value. Returns a single number when
161
26
  * every raw resource in the group reported the same size, a `min-max`
162
27
  * string when the size varies, or `null` when nothing was recorded.
163
- * @param entry - The dedupe entry to format.
28
+ * @param group - The resource group to format.
164
29
  */
165
- export function formatContentLength(entry) {
166
- if (entry.contentLengthMin == null) {
30
+ export function formatContentLength(group) {
31
+ if (group.contentLengthMin == null) {
167
32
  return null;
168
33
  }
169
- if (entry.contentLengthMin === entry.contentLengthMax) {
170
- return entry.contentLengthMin;
34
+ if (group.contentLengthMin === group.contentLengthMax) {
35
+ return group.contentLengthMin;
171
36
  }
172
- return `${entry.contentLengthMin}-${entry.contentLengthMax}`;
37
+ return `${group.contentLengthMin}-${group.contentLengthMax}`;
173
38
  }
174
39
  /**
175
- * Builds the cell row representation of a dedupe entry.
176
- * @param entry - The dedupe entry to serialize.
40
+ * Builds the cell row representation of a precomputed resource group.
41
+ * @param group - The resource group to serialize.
177
42
  */
178
- function dedupeEntryToRow(entry) {
43
+ function resourceGroupToRow(group) {
179
44
  return [
180
- createCellData({ value: entry.canonical }, defaultCellFormat),
181
- createCellData({ value: entry.status }, defaultCellFormat),
182
- createCellData({ value: entry.statusText }, defaultCellFormat),
183
- createCellData({ value: entry.contentType }, defaultCellFormat),
184
- createCellData({ value: formatContentLength(entry) }, defaultCellFormat),
45
+ createCellData({ value: group.canonicalUrl }, defaultCellFormat),
46
+ createCellData({ value: group.status }, defaultCellFormat),
47
+ createCellData({ value: group.statusText }, defaultCellFormat),
48
+ createCellData({ value: group.contentType }, defaultCellFormat),
49
+ createCellData({ value: formatContentLength(group) }, defaultCellFormat),
185
50
  createCellData({
186
- value: `${entry.referrers.size} pages`,
187
- note: joinReferrersForNote(entry.referrers),
51
+ value: `${group.referrerCount} pages`,
52
+ note: truncateNoteText(group.referrerNote ?? ''),
188
53
  }, defaultCellFormat),
189
- createCellData({ value: entry.count }, defaultCellFormat),
190
- createCellData({ value: formatQueryPattern(entry) }, defaultCellFormat),
54
+ createCellData({ value: group.count }, defaultCellFormat),
55
+ createCellData({ value: group.queryPattern }, defaultCellFormat),
191
56
  ];
192
57
  }
193
58
  /**
194
- * Builds the cell row for a single raw resource (raw mode).
195
- * @param resource - The resource record from the archive.
196
- * @param referrers - The referrer URLs associated with the resource.
59
+ * Counts every `resource_items` row, for raw mode's `estimateRowCount()`.
60
+ * @param accessor - The archive accessor to query.
197
61
  */
198
- function rawResourceToRow(resource, referrers) {
199
- return [
200
- createCellData({ value: resource.url }, defaultCellFormat),
201
- createCellData({ value: resource.status }, defaultCellFormat),
202
- createCellData({ value: resource.statusText }, defaultCellFormat),
203
- createCellData({ value: resource.contentType }, defaultCellFormat),
204
- createCellData({ value: resource.contentLength }, defaultCellFormat),
205
- createCellData({
206
- value: `${referrers.length} pages`,
207
- note: referrers.join('\n'),
208
- }, defaultCellFormat),
209
- ];
62
+ async function countResources(accessor) {
63
+ const knex = accessor.getKnex();
64
+ const [row] = await knex('resource_items').count({
65
+ count: '*',
66
+ });
67
+ return Number(row?.count ?? 0);
210
68
  }
211
69
  /**
212
- * Updates an existing dedupe entry with another raw resource that
213
- * resolved to the same `(canonical, status, contentType)` key. Encapsulates
214
- * the "first non-null" / "min-max" merge rules so they live in a single
215
- * inspectable function.
216
- * @param entry - The existing entry being merged into.
217
- * @param resource - The new raw resource being folded into the entry.
70
+ * Counts every `viewer_resource_groups` row, for dedupe mode's `estimateRowCount()`.
71
+ * @param accessor - The archive accessor to query.
218
72
  */
219
- function mergeIntoEntry(entry, resource) {
220
- if (entry.statusText == null && resource.statusText != null) {
221
- entry.statusText = resource.statusText;
222
- }
223
- const len = resource.contentLength;
224
- if (len != null) {
225
- if (entry.contentLengthMin == null || len < entry.contentLengthMin) {
226
- entry.contentLengthMin = len;
227
- }
228
- if (entry.contentLengthMax == null || len > entry.contentLengthMax) {
229
- entry.contentLengthMax = len;
230
- }
231
- }
73
+ async function countResourceGroups(accessor) {
74
+ const knex = accessor.getKnex();
75
+ const [row] = await knex('viewer_resource_groups').count({
76
+ count: '*',
77
+ });
78
+ return Number(row?.count ?? 0);
232
79
  }
233
80
  /**
234
81
  * Creates the "Resources" sheet configuration factory.
@@ -236,96 +83,85 @@ function mergeIntoEntry(entry, resource) {
236
83
  * Lists all network resources (CSS, JS, images, fonts, tracking pixels,
237
84
  * etc.) discovered during crawling. Two modes are supported:
238
85
  *
239
- * - **Raw mode** (default): one row per raw resource URL. Six columns:
240
- * URL, Status Code, Status Text, Content Type, Content Length,
241
- * Referrers. Matches historical behavior.
86
+ * - **Raw mode** (`{ dedupe: false }`, the default when `options` is
87
+ * omitted): one row per raw resource URL. Six columns: URL, Status Code,
88
+ * Status Text, Content Type, Content Length, Referrers. Streams
89
+ * `streamAllResourcesRaw` (write-model, `requiresReadModel` unset) and
90
+ * sends a row per chunk item immediately.
242
91
  * - **Dedupe mode** (`{ dedupe: true }`): collapses rows that share the
243
- * same canonical URL (query values stripped, keys sorted) into one
244
- * row per `(canonical URL, status, contentType)`. Adds a trailing
245
- * `Count` column showing how many raw resources each row collapses.
246
- * Useful when third-party tracking pixels generate millions of
247
- * per-request unique URLs that would otherwise exceed the Google
248
- * Sheets 10M-cell document limit.
92
+ * same canonical URL (query values stripped, keys sorted) into one row
93
+ * per `(canonical URL, status, contentType)`. Adds a trailing `Count`
94
+ * column showing how many raw resources each row collapses. Useful when
95
+ * third-party tracking pixels generate millions of per-request unique
96
+ * URLs that would otherwise exceed the Google Sheets 10M-cell document
97
+ * limit.
249
98
  *
250
- * In dedupe mode the factory accumulates state inside `eachResource`
251
- * and emits the aggregated rows once via the `finalizeResources` hook,
252
- * which Phase 3 calls exactly once after the per-resource loop completes.
99
+ * Dedupe mode's aggregation itself does not run here: it's precomputed
100
+ * once, at `viewer-build` time, into `viewer_resource_groups` (see
101
+ * `compute-resource-group-rows.ts`). This sheet only streams the
102
+ * already-grouped, already-sorted rows via `streamResourceGroups`, so
103
+ * `requiresReadModel: true`.
253
104
  * @param options - Optional configuration. See {@link CreateResourcesOptions}.
254
105
  */
255
106
  export function createResources(options) {
256
107
  const dedupe = options?.dedupe === true;
257
- return () => {
108
+ return (_reports, accessor) => {
258
109
  if (!dedupe) {
259
- const setting = {
110
+ return {
260
111
  name: 'Resources',
261
112
  createHeaders: () => [...RAW_HEADERS],
262
- async eachResource(resource) {
263
- reportLog(`Read: Resource referrers (Search: ${resource.url})`);
264
- const referrers = await resource.getReferrers();
265
- return [rawResourceToRow(resource, referrers)];
113
+ estimateRowCount: () => countResources(accessor),
114
+ async run({ sheet, maxRows, estimatedTotal, onProgress }) {
115
+ let sent = 0;
116
+ const total = estimatedTotal;
117
+ for await (const chunk of streamAllResourcesRaw(accessor)) {
118
+ const referrerUrlsByResourceId = await getResourceReferrerUrlsByResourceIds(accessor, chunk.map((row) => row.resourceId));
119
+ for (const row of chunk) {
120
+ if (sent >= maxRows) {
121
+ await sheet.flush();
122
+ return;
123
+ }
124
+ const referrerUrls = referrerUrlsByResourceId.get(row.resourceId) ?? [];
125
+ await sheet.appendRow([
126
+ createCellData({ value: row.url }, defaultCellFormat),
127
+ createCellData({ value: row.status }, defaultCellFormat),
128
+ createCellData({ value: row.statusText }, defaultCellFormat),
129
+ createCellData({ value: row.contentType }, defaultCellFormat),
130
+ createCellData({ value: row.contentLength }, defaultCellFormat),
131
+ createCellData({
132
+ value: `${referrerUrls.length} pages`,
133
+ note: joinUrlsForNote(referrerUrls),
134
+ }, defaultCellFormat),
135
+ ]);
136
+ sent++;
137
+ onProgress(sent, total);
138
+ }
139
+ }
140
+ await sheet.flush();
266
141
  },
267
142
  };
268
- return setting;
269
143
  }
270
- const entries = new Map();
271
- const setting = {
144
+ return {
272
145
  name: 'Resources',
273
- // Sorting the 1M+ raw resource list before aggregation is
274
- // wasted work: the 63K-row aggregated output is orders of
275
- // magnitude smaller, and we sort it inside finalizeResources
276
- // instead. This single flag flip turns a multi-minute sort
277
- // into a sub-second one on million-resource archives.
278
- skipSortResources: true,
146
+ requiresReadModel: true,
279
147
  createHeaders: () => [...DEDUPE_HEADERS],
280
- async eachResource(resource) {
281
- // A blob-routed resource (identity is a large `data:` URI, not a
282
- // URL — see `create-entity-tables.ts`'s `resource_items url /
283
- // blob mutual-exclusion CHECK`) has `url === null`; group all
284
- // such resources under one degenerate empty-string key rather
285
- // than crashing the report.
286
- const canonical = canonicalizeUrl(resource.url ?? '');
287
- const key = dedupeKey(canonical, resource.status, resource.contentType);
288
- let entry = entries.get(key);
289
- if (entry) {
290
- mergeIntoEntry(entry, resource);
291
- }
292
- else {
293
- entry = {
294
- canonical,
295
- status: resource.status,
296
- statusText: resource.statusText,
297
- contentType: resource.contentType,
298
- contentLengthMin: resource.contentLength,
299
- contentLengthMax: resource.contentLength,
300
- count: 0,
301
- referrers: new Set(),
302
- paramValues: new Map(),
303
- };
304
- entries.set(key, entry);
305
- }
306
- entry.count++;
307
- for (const { key: paramKey, value } of extractQueryPairs(resource.url ?? '')) {
308
- recordParamValue(entry, paramKey, value);
148
+ estimateRowCount: () => countResourceGroups(accessor),
149
+ async run({ sheet, maxRows, estimatedTotal, onProgress }) {
150
+ let sent = 0;
151
+ const total = estimatedTotal;
152
+ for await (const chunk of streamResourceGroups(accessor)) {
153
+ for (const group of chunk) {
154
+ if (sent >= maxRows) {
155
+ await sheet.flush();
156
+ return;
157
+ }
158
+ await sheet.appendRow(resourceGroupToRow(group));
159
+ sent++;
160
+ onProgress(sent, total);
161
+ }
309
162
  }
310
- reportLog(`Read: Resource referrers (Search: ${resource.url})`);
311
- const referrers = await resource.getReferrers();
312
- for (const ref of referrers) {
313
- entry.referrers.add(ref);
314
- }
315
- return null;
316
- },
317
- finalizeResources() {
318
- reportLog(`Dedupe complete: ${entries.size} canonical group(s) accumulated`);
319
- // Sort the aggregated entries by canonical URL in natural
320
- // order. This is N=tens-of-thousands rather than the
321
- // millions in `entries`, so the cost is negligible
322
- // compared to sorting the raw list up front.
323
- const sortedEntries = [...entries.values()].toSorted((a, b) => naturalCompare(a.canonical, b.canonical));
324
- const rows = sortedEntries.map(dedupeEntryToRow);
325
- entries.clear();
326
- return rows;
163
+ await sheet.flush();
327
164
  },
328
165
  };
329
- return setting;
330
166
  };
331
167
  }
@@ -2,11 +2,12 @@ import type { CreateSheet } from '../sheets/types.js';
2
2
  /**
3
3
  * Creates the "Violations" sheet configuration.
4
4
  *
5
- * Aggregates all violations from analyze plugin reports into a single
6
- * flat table. Uses `addRows` (Phase 4) rather than `eachPage` because
7
- * violation data comes from the report objects, not from per-page
8
- * archive iteration. This means it runs in parallel with page/resource
9
- * processing phases.
10
- * @param reports
5
+ * Streams `streamAllViolations` — a plain `analysis_violations.id` keyset
6
+ * pass, unlike the pre-rewrite version, which pre-loaded every violation
7
+ * into a `Report.violations` array before generation started (via
8
+ * `getPluginReports`). No read-model dependency: `analysis_violations` is a
9
+ * write-model table.
10
+ * @param _reports - Unused; the Violations sheet has no plugin-report dependency.
11
+ * @param accessor - The archive accessor to query.
11
12
  */
12
13
  export declare const createViolations: CreateSheet;
@@ -1,32 +1,45 @@
1
- import { pLog } from '../debug.js';
1
+ import { streamAllViolations } from '@nitpicker/query';
2
2
  import { createCellData } from '../sheets/create-cell-data.js';
3
3
  import { defaultCellFormat } from '../sheets/default-cell-format.js';
4
- const log = pLog.extend('Violations');
4
+ /**
5
+ * Counts every `analysis_violations` row, for `estimateRowCount()`.
6
+ * @param accessor - The archive accessor to query.
7
+ */
8
+ async function countViolations(accessor) {
9
+ const knex = accessor.getKnex();
10
+ const [row] = await knex('analysis_violations').count({
11
+ count: '*',
12
+ });
13
+ return Number(row?.count ?? 0);
14
+ }
5
15
  /**
6
16
  * Creates the "Violations" sheet configuration.
7
17
  *
8
- * Aggregates all violations from analyze plugin reports into a single
9
- * flat table. Uses `addRows` (Phase 4) rather than `eachPage` because
10
- * violation data comes from the report objects, not from per-page
11
- * archive iteration. This means it runs in parallel with page/resource
12
- * processing phases.
13
- * @param reports
18
+ * Streams `streamAllViolations` — a plain `analysis_violations.id` keyset
19
+ * pass, unlike the pre-rewrite version, which pre-loaded every violation
20
+ * into a `Report.violations` array before generation started (via
21
+ * `getPluginReports`). No read-model dependency: `analysis_violations` is a
22
+ * write-model table.
23
+ * @param _reports - Unused; the Violations sheet has no plugin-report dependency.
24
+ * @param accessor - The archive accessor to query.
14
25
  */
15
- export const createViolations = (reports) => {
26
+ export const createViolations = (_reports, accessor) => {
16
27
  return {
17
28
  name: 'Violations',
18
29
  createHeaders() {
19
30
  return ['Validator', 'Severity', 'Rule', 'Code', 'Message', 'URL'];
20
31
  },
21
- addRows: () => {
22
- const data = [];
23
- for (const report of reports) {
24
- if (!report.violations) {
25
- continue;
26
- }
27
- log('From %s', report.name);
28
- for (const violation of report.violations) {
29
- data.push([
32
+ estimateRowCount: () => countViolations(accessor),
33
+ async run({ sheet, maxRows, estimatedTotal, onProgress }) {
34
+ let sent = 0;
35
+ const total = estimatedTotal;
36
+ for await (const chunk of streamAllViolations(accessor)) {
37
+ for (const violation of chunk) {
38
+ if (sent >= maxRows) {
39
+ await sheet.flush();
40
+ return;
41
+ }
42
+ await sheet.appendRow([
30
43
  createCellData({ value: violation.validator }, defaultCellFormat),
31
44
  createCellData({ value: violation.severity }, defaultCellFormat),
32
45
  createCellData({ value: violation.rule }, defaultCellFormat),
@@ -34,9 +47,11 @@ export const createViolations = (reports) => {
34
47
  createCellData({ value: violation.message }, defaultCellFormat),
35
48
  createCellData({ value: violation.url }, defaultCellFormat),
36
49
  ]);
50
+ sent++;
51
+ onProgress(sent, total);
37
52
  }
38
53
  }
39
- return data;
54
+ await sheet.flush();
40
55
  },
41
56
  };
42
57
  };
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Wraps a message sink so consecutive identical messages are dropped —
3
+ * every `TaskList` row in `create-sheets.ts` feeds a per-row onProgress
4
+ * callback (fired every row in the underlying stream) straight into
5
+ * `ctx.progress()`; without this, a million-row sheet re-renders the row
6
+ * thousands of times for count deltas too small to change the rendered
7
+ * percentage text. Mirrors `@nitpicker/cli`'s `dedupe-progress-message.ts`;
8
+ * duplicated here rather than imported because `report-google-sheets`
9
+ * cannot depend on `cli` (the dependency direction is reversed).
10
+ * @param onMessage - Called only when the message differs from the last one.
11
+ * @returns A `(message: string) => void` sink with the same signature.
12
+ * @example
13
+ * ```ts
14
+ * const reportProgress = dedupeProgressMessage((message) => ctx.progress(message));
15
+ * ```
16
+ */
17
+ export declare function dedupeProgressMessage(onMessage: (message: string) => void): (message: string) => void;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Wraps a message sink so consecutive identical messages are dropped —
3
+ * every `TaskList` row in `create-sheets.ts` feeds a per-row onProgress
4
+ * callback (fired every row in the underlying stream) straight into
5
+ * `ctx.progress()`; without this, a million-row sheet re-renders the row
6
+ * thousands of times for count deltas too small to change the rendered
7
+ * percentage text. Mirrors `@nitpicker/cli`'s `dedupe-progress-message.ts`;
8
+ * duplicated here rather than imported because `report-google-sheets`
9
+ * cannot depend on `cli` (the dependency direction is reversed).
10
+ * @param onMessage - Called only when the message differs from the last one.
11
+ * @returns A `(message: string) => void` sink with the same signature.
12
+ * @example
13
+ * ```ts
14
+ * const reportProgress = dedupeProgressMessage((message) => ctx.progress(message));
15
+ * ```
16
+ */
17
+ export function dedupeProgressMessage(onMessage) {
18
+ let lastMessage = '';
19
+ return (message) => {
20
+ if (message === lastMessage) {
21
+ return;
22
+ }
23
+ lastMessage = message;
24
+ onMessage(message);
25
+ };
26
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Formats a processed/total pair as a human-readable `"1,234/5,000 rows
3
+ * (25%)"` fragment — so a reader doesn't have to guess what a bare `N/M`
4
+ * number means or do the percentage math themselves. Mirrors
5
+ * `@nitpicker/cli`'s `format-progress-count.ts`; duplicated here rather than
6
+ * imported because `report-google-sheets` cannot depend on `cli` (the
7
+ * dependency direction is reversed — `cli` depends on `report-google-sheets`).
8
+ * @param processed - Units processed so far.
9
+ * @param total - Total units to process.
10
+ * @param unit - Plural unit noun to display. Defaults to `"rows"`.
11
+ * @returns e.g. `"250/500 rows (50%)"`. `100%` when `total` is `0` (nothing
12
+ * to do counts as already done, not `0%`).
13
+ * @example
14
+ * ```ts
15
+ * formatProgressCount(250, 500); // "250/500 rows (50%)"
16
+ * formatProgressCount(23, 57, 'edges'); // "23/57 edges (40%)"
17
+ * ```
18
+ */
19
+ export declare function formatProgressCount(processed: number, total: number, unit?: string): string;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Formats a processed/total pair as a human-readable `"1,234/5,000 rows
3
+ * (25%)"` fragment — so a reader doesn't have to guess what a bare `N/M`
4
+ * number means or do the percentage math themselves. Mirrors
5
+ * `@nitpicker/cli`'s `format-progress-count.ts`; duplicated here rather than
6
+ * imported because `report-google-sheets` cannot depend on `cli` (the
7
+ * dependency direction is reversed — `cli` depends on `report-google-sheets`).
8
+ * @param processed - Units processed so far.
9
+ * @param total - Total units to process.
10
+ * @param unit - Plural unit noun to display. Defaults to `"rows"`.
11
+ * @returns e.g. `"250/500 rows (50%)"`. `100%` when `total` is `0` (nothing
12
+ * to do counts as already done, not `0%`).
13
+ * @example
14
+ * ```ts
15
+ * formatProgressCount(250, 500); // "250/500 rows (50%)"
16
+ * formatProgressCount(23, 57, 'edges'); // "23/57 edges (40%)"
17
+ * ```
18
+ */
19
+ export function formatProgressCount(processed, total, unit = 'rows') {
20
+ const percent = total > 0 ? Math.floor((processed / total) * 100) : 100;
21
+ return `${processed.toLocaleString()}/${total.toLocaleString()} ${unit} (${percent}%)`;
22
+ }