@nitpicker/report-google-sheets 0.8.0 → 0.11.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/README.md CHANGED
@@ -6,7 +6,53 @@
6
6
 
7
7
  `.nitpicker` アーカイブ内のクロールデータと分析結果を Google Sheets に出力します。ページ一覧・リンク・リソース・画像・違反レポートなど、複数のシートを自動生成します。
8
8
 
9
- このパッケージは [Nitpicker](../../README.md) モノレポの内部パッケージです。単体での利用は想定していません。
9
+ このパッケージは [Nitpicker](../../../README.md) モノレポの内部パッケージです。単体での利用は想定していません。
10
+
11
+ ## 設計のポイント
12
+
13
+ - **5 フェーズ構成**: `Phase 1 (シート作成)` → `Phase 2 (ページ反復) / Phase 3 (リソース反復) / Phase 4 (プラグインデータ)` 並列 → `Phase 5 (フォーマット)`。詳細は [ARCHITECTURE.md §8](../../../ARCHITECTURE.md#8-report-の詳細)。
14
+ - **ストリーミング送信**: 各シートの行生成は `sheet.appendRow(...rows)` でストリーミング送信。`@d-zero/google-sheets` が内部で 2500 行ごとに自動 flush するため、呼び出し元のメモリ滞留はチャンクサイズ分に抑えられる。
15
+ - **Resources シートの dedupe モード**: `--dedupe-resources` で canonical URL ごとに集約。広告・解析タグで per-request unique なクエリが爆発するサイトで、Google Sheets の **1 ドキュメント 10,000,000 セル上限** を回避するための機能(実例: 1.6M raw → 63K rows、96% 削減)。
16
+ - **Phase 3 finalize での進捗表示**: 集約後の大量行を `appendRow(...finalRows)` で一括送信する間も、`Sheet.onProgress` を購読して chunk flush ごとに Lanes に `Sending N/total` を反映する。実装は [`src/sheets/run-finalize-resources.ts`](./src/sheets/run-finalize-resources.ts)。
17
+
18
+ ## 拡張ポイント(新規シート追加時)
19
+
20
+ 新しいシートを追加するときの典型パターン:
21
+
22
+ | やりたいこと | 使う hook |
23
+ | ---------------------------------------------- | ----------------------------------------------------------- |
24
+ | ページごとに行を生成 | `eachPage` |
25
+ | ページ反復前に状態を蓄積(例: 親子関係マップ) | `preEachPage` |
26
+ | リソースごとに行を生成 | `eachResource` |
27
+ | リソース反復の終端で集約結果を 1 回だけ送信 | `eachResource` で Map に蓄積 → `finalizeResources` で flush |
28
+ | プラグインデータ等、反復不要で一括送信 | `addRows`(Phase 2/3 と並列実行) |
29
+ | データ送信後にフォーマット適用 | `updateSheet` |
30
+
31
+ > **集約系シートで `eachResource` 内の `num`/`total` を見て最後だけ emit する設計は禁止**。Phase 3 が将来並列化されると壊れる。必ず `finalizeResources` hook を使うこと([ARCHITECTURE.md の説明](../../../ARCHITECTURE.md#行送信戦略))。
32
+
33
+ ## トラブルシューティング
34
+
35
+ | 症状 | 原因と対処 |
36
+ | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
37
+ | `Error: This document is too large to continue editing.` | Google Sheets の 10M セル上限到達。`--dedupe-resources` を有効にして Resources を集約する。 |
38
+ | Phase 3 で「Sending N/total」の N が止まったまま | 進捗表示は `Sheet.onProgress` 駆動。`@d-zero/google-sheets` を 0.9.0 以上に保つ必要がある。 |
39
+ | `RangeError: Maximum call stack size exceeded` (Phase 3 finalize) | `appendRow(...finalRows)` のスプレッドが V8 引数上限(実用上 6.5 万件付近)を超えた。`finalizeResources` の戻り値件数が更に増えた場合は chunk 単位で複数回 `appendRow` を呼ぶよう書き換える。[ARCHITECTURE.md の既知の制約セクション](../../../ARCHITECTURE.md#行送信戦略)を参照。 |
40
+ | sort に長時間ブロックされて HTTPS が EPIPE で落ちる | `sortResourcesByUrl` は Pool `strnatcmp` の派生文字列ゼロ実装。`Intl.Collator.compare` や Schwartzian transform への書き換えは禁止(過去にやって両方とも本番障害を起こした)。詳細は [ARCHITECTURE.md](../../../ARCHITECTURE.md#行送信戦略)。 |
41
+
42
+ ## テスト
43
+
44
+ ```bash
45
+ yarn vitest run packages/@nitpicker/report-google-sheets
46
+ ```
47
+
48
+ E2E は `yarn vitest run --config vitest.e2e.config.ts` でリポジトリ全体一括(Google Sheets API モックは未整備のため、本番送信パスは手動検証)。
49
+
50
+ ## 参照
51
+
52
+ - [ARCHITECTURE.md §8 Report の詳細](../../../ARCHITECTURE.md#8-report-の詳細) — フェーズ詳細、行送信戦略、sort 実装の根拠
53
+ - [`@d-zero/google-sheets`](https://www.npmjs.com/package/@d-zero/google-sheets) — Sheet ストリーミング送信 API
54
+ - [Google Sheets API 制限](https://developers.google.com/sheets/api/limits) — 10M セル上限、batchUpdate サイズ
55
+ - [Martin Pool, "Natural Order String Comparison"](https://sourcefrog.net/projects/natsort/) — sort 実装の出典
10
56
 
11
57
  ## ライセンス
12
58
 
@@ -24,6 +24,27 @@ import type { CreateSheet } from '../sheets/types.js';
24
24
  * - Error-like titles and non-success status codes
25
25
  *
26
26
  * Unused path columns (beyond the deepest URL) are hidden automatically.
27
+ *
28
+ * ## Lazy thunk in "Internal Referrers"
29
+ *
30
+ * The "Internal Referrers" column is emitted via `createCellData(() => ...)`
31
+ * — a thunk that reads `parentRefs` / `indexRefs` at `provide()` time. The
32
+ * thunk is deliberately deferred because sibling index pages mutate the
33
+ * shared maps as the batch iterates, so the final referrer count is only
34
+ * accurate after every page has been processed.
35
+ *
36
+ * `@d-zero/google-sheets` detects this lazy cell (via the
37
+ * `Cell.prototype.provide` identity check) and switches the sheet's
38
+ * `appendRow()` into buffered mode automatically. The buffered rows are
39
+ * sent on the explicit `sheet.flush()` call at batch end, by which time
40
+ * the maps are fully populated.
41
+ *
42
+ * If a future refactor removes the thunk pattern from this column, the
43
+ * sheet can be sent as a pure stream — no per-sheet configuration change
44
+ * is needed since the library auto-detects. The corresponding spec
45
+ * (`create-page-list.spec.ts`) asserts the presence of at least one lazy
46
+ * cell so the maintainer who removes the thunk will see the test fail and
47
+ * be prompted to reconsider whether the change is intentional.
27
48
  * @param reports - Analyze plugin reports to extract per-page data columns from
28
49
  */
29
50
  export declare const createPageList: CreateSheet;
@@ -30,6 +30,27 @@ const log = pLog.extend('PageList');
30
30
  * - Error-like titles and non-success status codes
31
31
  *
32
32
  * Unused path columns (beyond the deepest URL) are hidden automatically.
33
+ *
34
+ * ## Lazy thunk in "Internal Referrers"
35
+ *
36
+ * The "Internal Referrers" column is emitted via `createCellData(() => ...)`
37
+ * — a thunk that reads `parentRefs` / `indexRefs` at `provide()` time. The
38
+ * thunk is deliberately deferred because sibling index pages mutate the
39
+ * shared maps as the batch iterates, so the final referrer count is only
40
+ * accurate after every page has been processed.
41
+ *
42
+ * `@d-zero/google-sheets` detects this lazy cell (via the
43
+ * `Cell.prototype.provide` identity check) and switches the sheet's
44
+ * `appendRow()` into buffered mode automatically. The buffered rows are
45
+ * sent on the explicit `sheet.flush()` call at batch end, by which time
46
+ * the maps are fully populated.
47
+ *
48
+ * If a future refactor removes the thunk pattern from this column, the
49
+ * sheet can be sent as a pure stream — no per-sheet configuration change
50
+ * is needed since the library auto-detects. The corresponding spec
51
+ * (`create-page-list.spec.ts`) asserts the presence of at least one lazy
52
+ * cell so the maintainer who removes the thunk will see the test fail and
53
+ * be prompted to reconsider whether the change is intentional.
33
54
  * @param reports - Analyze plugin reports to extract per-page data columns from
34
55
  */
35
56
  export const createPageList = (reports) => {
@@ -61,6 +82,7 @@ export const createPageList = (reports) => {
61
82
  'Status Code',
62
83
  'Redirect From',
63
84
  'Language',
85
+ 'charset',
64
86
  'Internal Links',
65
87
  'Internal Bad Links',
66
88
  'External Links',
@@ -71,15 +93,24 @@ export const createPageList = (reports) => {
71
93
  'noindex',
72
94
  'nofollow',
73
95
  'noarchive',
96
+ 'robots:raw',
74
97
  'canonical',
75
- 'alternate',
98
+ 'manifest',
99
+ 'theme-color',
76
100
  'twitter:card',
101
+ 'twitter:site',
102
+ 'twitter:creator',
77
103
  'og:site_name',
78
104
  'og:url',
79
105
  'og:title',
80
106
  'og:description',
81
107
  'og:type',
82
108
  'og:image',
109
+ 'og:image:alt',
110
+ 'og:locale',
111
+ 'og:article:published_time',
112
+ 'jsonld_count',
113
+ 'tags_providers',
83
114
  ];
84
115
  for (const report of reports) {
85
116
  if (report.pageData) {
@@ -181,6 +212,7 @@ export const createPageList = (reports) => {
181
212
  note: page.redirectFrom.map((r) => r.url).join('\n'),
182
213
  }, defaultCellFormat),
183
214
  createCellData({ value: page.lang || 'N/A' }, defaultCellFormat),
215
+ createCellData({ value: page.charset }, defaultCellFormat),
184
216
  createCellData({ value: iLinks }, defaultCellFormat),
185
217
  createCellData({ value: iBadLinks.length, note: iBadLinks.join('\n') }, defaultCellFormat),
186
218
  createCellData({ value: xLinks }, defaultCellFormat),
@@ -199,12 +231,16 @@ export const createPageList = (reports) => {
199
231
  }), defaultCellFormat),
200
232
  createCellData({ value: page.description }, defaultCellFormat),
201
233
  createCellData({ value: page.keywords }, defaultCellFormat),
202
- createCellData({ value: !!page.noindex }, defaultCellFormat),
203
- createCellData({ value: !!page.nofollow }, defaultCellFormat),
204
- createCellData({ value: !!page.noarchive }, defaultCellFormat),
234
+ createCellData({ value: page.robots_noindex }, defaultCellFormat),
235
+ createCellData({ value: page.robots_nofollow }, defaultCellFormat),
236
+ createCellData({ value: page.robots_noarchive }, defaultCellFormat),
237
+ createCellData({ value: page.robots_raw }, defaultCellFormat),
205
238
  createCellData({ value: page.canonical }, defaultCellFormat),
206
- createCellData({ value: page.alternate }, defaultCellFormat),
239
+ createCellData({ value: page.metaFlat.manifest }, defaultCellFormat),
240
+ createCellData({ value: page.metaFlat.themeColor }, defaultCellFormat),
207
241
  createCellData({ value: page.twitter_card }, defaultCellFormat),
242
+ createCellData({ value: page.metaFlat.twitter_site }, defaultCellFormat),
243
+ createCellData({ value: page.metaFlat.twitter_creator }, defaultCellFormat),
208
244
  createCellData({ value: page.og_site_name }, defaultCellFormat),
209
245
  createCellData({
210
246
  value: page.og_url,
@@ -214,6 +250,14 @@ export const createPageList = (reports) => {
214
250
  createCellData({ value: page.og_description }, defaultCellFormat),
215
251
  createCellData({ value: page.og_type }, defaultCellFormat),
216
252
  createCellData({ value: page.og_image }, defaultCellFormat),
253
+ createCellData({ value: page.metaFlat.og_image_alt }, defaultCellFormat),
254
+ createCellData({ value: page.metaFlat.og_locale }, defaultCellFormat),
255
+ createCellData({ value: page.metaFlat.og_article_published_time }, defaultCellFormat),
256
+ // Denormalised aggregates: written at scrape time so no per-page
257
+ // GROUP BY is needed here. `tagsProvidersCsv` is comma-separated
258
+ // for native Google Sheets list rendering.
259
+ createCellData({ value: page.jsonldCount }, defaultCellFormat),
260
+ createCellData({ value: page.tagsProvidersCsv }, defaultCellFormat),
217
261
  ];
218
262
  for (const report of reportPageData) {
219
263
  const tableData = report.pageData.data[page.url.href];
@@ -1,13 +1,157 @@
1
1
  import type { CreateSheet } from '../sheets/types.js';
2
2
  /**
3
- * Creates the "Resources" sheet configuration.
3
+ * Options for the {@link createResources} factory.
4
+ */
5
+ export interface CreateResourcesOptions {
6
+ /**
7
+ * Collapse raw resource rows that share the same canonical URL
8
+ * (query *values* stripped, query *keys* sorted) into one row per
9
+ * `(canonical URL, status, contentType)` combination. Adds a `Count`
10
+ * column showing how many raw resources each row collapses.
11
+ *
12
+ * Path-embedded identifiers (e.g. tracking IDs in
13
+ * `/pagead/viewthroughconversion/<id>/`) are preserved, so the
14
+ * aggregated rows still expose every tracker present in the archive.
15
+ *
16
+ * Defaults to `false` (raw mode — one row per raw resource URL).
17
+ */
18
+ readonly dedupe?: boolean;
19
+ }
20
+ /**
21
+ * Safety cap for the joined referrer URL list inserted into a cell note.
22
+ * Google Sheets caps cell content / notes around 50,000 characters; we
23
+ * truncate well below that to leave room for the "and N more" suffix.
24
+ */
25
+ export declare const NOTE_MAX_LENGTH = 49000;
26
+ /**
27
+ * Maximum number of unique values to keep per query parameter key in
28
+ * dedupe mode. The Query Pattern cell only shows unique counts, but
29
+ * we keep a small sample for cell notes and to avoid unbounded memory
30
+ * growth on trackers that send a unique-per-request value
31
+ * (e.g. session IDs).
32
+ */
33
+ export declare const MAX_PARAM_VALUE_SAMPLES = 100;
34
+ /**
35
+ * Per-key tracker for query parameter values inside a dedupe entry.
36
+ * `values` is capped at {@link MAX_PARAM_VALUE_SAMPLES}; once the cap
37
+ * is reached, further observations increment `overflowedCount`
38
+ * instead of growing the set. {@link formatQueryPattern} uses
39
+ * `overflowedCount > 0` as the precise condition for appending `+`
40
+ * to the cell — so `key=100` means "exactly 100 sampled, no
41
+ * observation was lost", and `key=100+` means "the sample set lost
42
+ * at least one observation after the cap".
43
+ */
44
+ export interface ParamValueTracker {
45
+ /** Sampled unique values (bounded by {@link MAX_PARAM_VALUE_SAMPLES}). */
46
+ readonly values: Set<string>;
47
+ /** Observations that arrived after the sample set was full and therefore could not enter the set. */
48
+ overflowedCount: number;
49
+ }
50
+ /**
51
+ * In-memory aggregation entry for dedupe mode. One per
52
+ * `(canonical, status, contentType)` combination.
53
+ */
54
+ export interface DedupeEntry {
55
+ /** Canonical URL representing this entry. */
56
+ readonly canonical: string;
57
+ /** HTTP status code shared by all raw resources in this entry. */
58
+ readonly status: number | null;
59
+ /** HTTP status text — first non-null value observed. */
60
+ statusText: string | null;
61
+ /** Content type shared by all raw resources in this entry. */
62
+ readonly contentType: string | null;
63
+ /** Smallest non-null content length observed. */
64
+ contentLengthMin: number | null;
65
+ /** Largest non-null content length observed. */
66
+ contentLengthMax: number | null;
67
+ /** Number of raw resources collapsed into this entry. */
68
+ count: number;
69
+ /** Union of referrer page URLs across all raw resources in this entry. */
70
+ readonly referrers: Set<string>;
71
+ /** Per-query-key value trackers; absent for resources without a query string. */
72
+ readonly paramValues: Map<string, ParamValueTracker>;
73
+ }
74
+ /**
75
+ * Builds the Map key for a dedupe entry.
76
+ *
77
+ * Concatenates `status`, `contentType`, and `canonical` with a
78
+ * non-printable separator. A dedicated `null` marker keeps `null`
79
+ * distinct from `''` for `contentType`, and from `0` for `status`,
80
+ * so e.g. `(canonical, 200, null)` and `(canonical, 200, '')` land
81
+ * in different aggregation buckets.
82
+ *
83
+ * String concatenation is used instead of {@link JSON.stringify}
84
+ * because this function is called once per raw resource — on a
85
+ * million-resource archive `JSON.stringify` allocated roughly a
86
+ * million transient `SeqString`s, dominating Phase 3 wall-clock
87
+ * time. Plain concatenation is several times faster and produces
88
+ * the same collision-free key.
89
+ * @param canonical - The canonicalized URL.
90
+ * @param status - HTTP status code (nullable).
91
+ * @param contentType - HTTP content type (nullable).
92
+ */
93
+ export declare function dedupeKey(canonical: string, status: number | null, contentType: string | null): string;
94
+ /**
95
+ * Joins referrer URLs into a single newline-separated string, truncating
96
+ * at `maxLength` to stay within Google Sheets' note size cap. When
97
+ * truncated, appends a `... and N more` line where `N` counts every URL
98
+ * that did not fit, including the one whose insertion would have
99
+ * crossed the limit.
100
+ * @param referrers - The set of unique referrer page URLs.
101
+ * @param maxLength - Optional override for the character cap (defaults to {@link NOTE_MAX_LENGTH}).
102
+ */
103
+ export declare function joinReferrersForNote(referrers: ReadonlySet<string>, maxLength?: number): string;
104
+ /**
105
+ * Formats the Query Pattern cell for a dedupe entry. Each tracked key
106
+ * gets a `key=N` token where `N` is the number of distinct values
107
+ * sampled. `+` is appended only when {@link ParamValueTracker.overflowedCount}
108
+ * is non-zero — i.e. when at least one observation arrived after the
109
+ * sample set was already full. Duplicate observations that arrive
110
+ * while the sample set still has capacity do NOT trigger `+`.
111
+ *
112
+ * This gives precise semantics:
113
+ *
114
+ * - `key=1` — exactly one distinct value, seen any number of times
115
+ * - `key=99` — 99 distinct values, sample set still had room
116
+ * - `key=100` — exactly 100 distinct values, no observation lost
117
+ * - `key=100+` — sample set was capped and at least one further
118
+ * observation could not be recorded (real cardinality unknown but
119
+ * at least 100)
120
+ *
121
+ * Keys are sorted alphabetically to match the canonical URL.
122
+ *
123
+ * Returns `null` for entries without any query parameters so the cell
124
+ * appears empty in Google Sheets.
125
+ * @param entry - The dedupe entry to format.
126
+ */
127
+ export declare function formatQueryPattern(entry: DedupeEntry): string | null;
128
+ /**
129
+ * Formats the Content Length cell value. Returns a single number when
130
+ * every raw resource in the group reported the same size, a `min-max`
131
+ * string when the size varies, or `null` when nothing was recorded.
132
+ * @param entry - The dedupe entry to format.
133
+ */
134
+ export declare function formatContentLength(entry: DedupeEntry): number | string | null;
135
+ /**
136
+ * Creates the "Resources" sheet configuration factory.
137
+ *
138
+ * Lists all network resources (CSS, JS, images, fonts, tracking pixels,
139
+ * etc.) discovered during crawling. Two modes are supported:
4
140
  *
5
- * Lists all network resources (CSS, JS, images, fonts, etc.) discovered
6
- * during crawling, with one row per unique resource URL. Each row includes
7
- * HTTP status, content type, size, and the number of pages that reference
8
- * the resource (with URLs listed in the cell note).
141
+ * - **Raw mode** (default): one row per raw resource URL. Six columns:
142
+ * URL, Status Code, Status Text, Content Type, Content Length,
143
+ * Referrers. Matches historical behavior.
144
+ * - **Dedupe mode** (`{ dedupe: true }`): collapses rows that share the
145
+ * same canonical URL (query values stripped, keys sorted) into one
146
+ * row per `(canonical URL, status, contentType)`. Adds a trailing
147
+ * `Count` column showing how many raw resources each row collapses.
148
+ * Useful when third-party tracking pixels generate millions of
149
+ * per-request unique URLs that would otherwise exceed the Google
150
+ * Sheets 10M-cell document limit.
9
151
  *
10
- * Uses `eachResource` (Phase 3) to iterate over the archive's resource
11
- * table rather than page-by-page iteration.
152
+ * In dedupe mode the factory accumulates state inside `eachResource`
153
+ * and emits the aggregated rows once via the `finalizeResources` hook,
154
+ * which Phase 3 calls exactly once after the per-resource loop completes.
155
+ * @param options - Optional configuration. See {@link CreateResourcesOptions}.
12
156
  */
13
- export declare const createResources: CreateSheet;
157
+ export declare function createResources(options?: CreateResourcesOptions): CreateSheet;