@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 +47 -1
- package/lib/data/create-page-list.d.ts +21 -0
- package/lib/data/create-page-list.js +49 -5
- package/lib/data/create-resources.d.ts +152 -8
- package/lib/data/create-resources.js +321 -40
- package/lib/report.d.ts +10 -0
- package/lib/report.js +2 -2
- package/lib/sheets/create-sheets.d.ts +15 -20
- package/lib/sheets/create-sheets.js +62 -83
- package/lib/sheets/run-finalize-resources.d.ts +31 -0
- package/lib/sheets/run-finalize-resources.js +35 -0
- package/lib/sheets/types.d.ts +29 -0
- package/lib/utils/canonicalize-url.d.ts +53 -0
- package/lib/utils/canonicalize-url.js +105 -0
- package/lib/utils/sort-resources-by-url.d.ts +66 -0
- package/lib/utils/sort-resources-by-url.js +220 -0
- package/package.json +6 -6
|
@@ -1,36 +1,8 @@
|
|
|
1
1
|
import c from 'ansi-colors';
|
|
2
2
|
import { sheetLog } from '../debug.js';
|
|
3
3
|
import { hasPropFilter } from '../utils/has-prop-filter.js';
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
* 行データを Google Sheets に送信する。行数が {@link SEND_CHUNK_SIZE} を超える場合は
|
|
7
|
-
* チャンク分割して逐次送信する。
|
|
8
|
-
* @param sheet
|
|
9
|
-
* @param rows
|
|
10
|
-
* @param name
|
|
11
|
-
* @param lanes
|
|
12
|
-
* @param laneId
|
|
13
|
-
* @param onProgress 送信の進捗を 0.0〜1.0 の fraction で通知するコールバック。
|
|
14
|
-
* Phase 2/3 のヘッダー加重平均に送信進捗を反映させるために使用する。
|
|
15
|
-
*/
|
|
16
|
-
async function sendRowsInChunks(sheet, rows, name, lanes, laneId, onProgress) {
|
|
17
|
-
if (rows.length <= SEND_CHUNK_SIZE) {
|
|
18
|
-
lanes?.update(laneId, `${name}: Sending ${rows.length} rows%dots%`);
|
|
19
|
-
onProgress?.(1);
|
|
20
|
-
await sheet.addRowData(rows, true);
|
|
21
|
-
}
|
|
22
|
-
else {
|
|
23
|
-
let sent = 0;
|
|
24
|
-
for (let i = 0; i < rows.length; i += SEND_CHUNK_SIZE) {
|
|
25
|
-
const chunk = rows.slice(i, i + SEND_CHUNK_SIZE);
|
|
26
|
-
sent += chunk.length;
|
|
27
|
-
const pct = Math.round((sent / rows.length) * 100);
|
|
28
|
-
lanes?.update(laneId, `${name}: Sending rows ${sent}/${rows.length} (${pct}%)%dots%`);
|
|
29
|
-
onProgress?.(sent / rows.length);
|
|
30
|
-
await sheet.addRowData(chunk, true);
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
}
|
|
4
|
+
import { sortResourcesByUrl } from '../utils/sort-resources-by-url.js';
|
|
5
|
+
import { runFinalizeResources } from './run-finalize-resources.js';
|
|
34
6
|
/**
|
|
35
7
|
* Google Sheets にシートを作成し、データを投入してフォーマットする。
|
|
36
8
|
*
|
|
@@ -45,31 +17,26 @@ async function sendRowsInChunks(sheet, rows, name, lanes, laneId, onProgress) {
|
|
|
45
17
|
* → Phase 5 (Formatting sheets)
|
|
46
18
|
* ```
|
|
47
19
|
*
|
|
48
|
-
* ##
|
|
49
|
-
*
|
|
50
|
-
* ### ヘッダー: 加重平均による集計
|
|
20
|
+
* ## 行送信戦略
|
|
51
21
|
*
|
|
52
|
-
* Phase 2/3
|
|
22
|
+
* Phase 2 / 3 はページ・リソースを反復しながら、生成した行を都度
|
|
23
|
+
* `sheet.appendRow(...rows)` に渡してストリーミング送信する。`sheet.appendRow()` は
|
|
24
|
+
* `@d-zero/google-sheets` 側で 2500 行ごとに自動 flush する(呼び出し元は
|
|
25
|
+
* チャンクサイズを意識しない)。バッチ終端で `sheet.flush()` を呼んで残余を排出する。
|
|
53
26
|
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
* Referrers RT は Sending rows 7500/13256 — ヘッダーが全体を見ていない。
|
|
27
|
+
* 遅延セル(`createCellData(() => ...)` の thunk)を含む行が混ざった場合、
|
|
28
|
+
* `appendRow()` はその時点で自動 flush を停止し、明示的な `flush()` 呼び出しまで
|
|
29
|
+
* バッファに保留する(順序保証)。Page List の「Internal Referrers」列がこの
|
|
30
|
+
* 仕組みに乗っており、バッチ終端の `flush()` で初めて評価される。
|
|
59
31
|
*
|
|
60
|
-
*
|
|
61
|
-
* 全シートの平均値をヘッダーに表示する:
|
|
32
|
+
* ## Lanes 進捗表示
|
|
62
33
|
*
|
|
63
|
-
*
|
|
64
|
-
* - **送信フェーズ**: `0.5 + (sentRows / totalRows) * 0.5` → 50%〜100%
|
|
65
|
-
* (`sendRowsInChunks` の `onProgress` コールバック経由)
|
|
66
|
-
* - **完了**: 1.0 (100%)
|
|
34
|
+
* ### ヘッダー: 加重平均による集計
|
|
67
35
|
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
* レート制限により生成と同程度の時間がかかるため、等配分が妥当
|
|
36
|
+
* Phase 2/3 のヘッダーは全子タスク(シート)の進捗 (`pageNum / max`) の
|
|
37
|
+
* 平均をパーセント表示する。生成と送信が同一の `appendRow` 呼び出しで一体化
|
|
38
|
+
* しているため、ヘッダーは単一の fraction で済む(旧実装にあった生成 0〜50% /
|
|
39
|
+
* 送信 50〜100% の二段重み付けは不要になった)。
|
|
73
40
|
*
|
|
74
41
|
* ### レーン: フェーズ遷移に応じた状態表示
|
|
75
42
|
*
|
|
@@ -286,36 +253,27 @@ export async function createSheets(params) {
|
|
|
286
253
|
sheetLog('Running eachPage for %d routine(s)', eachPageRoutineList.length);
|
|
287
254
|
await Promise.all(eachPageRoutineList.map(async (setting) => {
|
|
288
255
|
const id = getSheetId(setting.name);
|
|
289
|
-
let num = 1;
|
|
290
|
-
const rows = [];
|
|
291
256
|
const name = setting.name;
|
|
257
|
+
const sheet = await sheets.create(name);
|
|
258
|
+
let num = 1;
|
|
292
259
|
let prevPage = null;
|
|
293
260
|
for (const page of pages) {
|
|
294
261
|
const pageNum = offset + num;
|
|
295
|
-
lanes?.update(id, `${name}:
|
|
296
|
-
sheetProgress.set(name,
|
|
262
|
+
lanes?.update(id, `${name}: Processing ${pageNum}/${max} (sent ${sheet.sentCount})%dots%`);
|
|
263
|
+
sheetProgress.set(name, pageNum / max);
|
|
297
264
|
updatePhase2Header();
|
|
298
265
|
const data = await setting.eachPage(page, pageNum, max, prevPage);
|
|
299
266
|
prevPage = page;
|
|
300
|
-
if (
|
|
301
|
-
|
|
302
|
-
continue;
|
|
303
|
-
}
|
|
304
|
-
for (const row of data) {
|
|
305
|
-
rows.push(row);
|
|
267
|
+
if (data) {
|
|
268
|
+
await sheet.appendRow(...data);
|
|
306
269
|
}
|
|
307
270
|
num++;
|
|
308
271
|
}
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
await sendRowsInChunks(sheet, rows, name, lanes, id, (fraction) => {
|
|
312
|
-
sheetProgress.set(name, 0.5 + fraction * 0.5);
|
|
313
|
-
updatePhase2Header();
|
|
314
|
-
});
|
|
315
|
-
sheetLog('[%s] Send complete (offset=%d)', name, offset);
|
|
272
|
+
await sheet.flush();
|
|
273
|
+
sheetLog('[%s] Send complete (offset=%d, %d rows)', name, offset, sheet.sentCount);
|
|
316
274
|
sheetProgress.set(name, 1);
|
|
317
275
|
updatePhase2Header();
|
|
318
|
-
markDone(name, `${
|
|
276
|
+
markDone(name, `${sheet.sentCount} rows`);
|
|
319
277
|
}));
|
|
320
278
|
}
|
|
321
279
|
});
|
|
@@ -326,8 +284,21 @@ export async function createSheets(params) {
|
|
|
326
284
|
sheetLog('Phase 3: Starting resource processing');
|
|
327
285
|
setPhaseHeader();
|
|
328
286
|
dimInactiveSheets(3);
|
|
329
|
-
const
|
|
330
|
-
sheetLog('Resources loaded: %d',
|
|
287
|
+
const rawResources = await archive.getResources();
|
|
288
|
+
sheetLog('Resources loaded: %d', rawResources.length);
|
|
289
|
+
// Resources は DB の挿入順で返るため、出力前に URL の自然順に
|
|
290
|
+
// 並び替える。ただし `skipSortResources: true` を宣言した setting
|
|
291
|
+
// は自分で集約してから sort する責任を持つ(dedupe mode のような
|
|
292
|
+
// 「1M 件を sort してから 63K に集約」は無駄なので、集約後に
|
|
293
|
+
// 小さな集合だけ sort する)。少なくとも 1 つの setting が
|
|
294
|
+
// sort を必要とするなら、ループ前に 1 度だけ実行して共有する。
|
|
295
|
+
const needsSort = eachResourceRoutineList.some((s) => !s.skipSortResources);
|
|
296
|
+
let sortedResources = null;
|
|
297
|
+
if (needsSort) {
|
|
298
|
+
updatePhaseHeader('Sorting resources by URL');
|
|
299
|
+
sortedResources = sortResourcesByUrl(rawResources);
|
|
300
|
+
sheetLog('Resources sorted by natural URL order');
|
|
301
|
+
}
|
|
331
302
|
const resourceProgress = new Map();
|
|
332
303
|
for (const setting of eachResourceRoutineList) {
|
|
333
304
|
resourceProgress.set(setting.name, 0);
|
|
@@ -346,28 +317,34 @@ export async function createSheets(params) {
|
|
|
346
317
|
}
|
|
347
318
|
await Promise.all(eachResourceRoutineList.map(async (setting) => {
|
|
348
319
|
const id = getSheetId(setting.name);
|
|
349
|
-
const
|
|
350
|
-
const
|
|
320
|
+
const name = setting.name;
|
|
321
|
+
const sheet = await sheets.create(name);
|
|
322
|
+
const resources = setting.skipSortResources || !sortedResources
|
|
323
|
+
? rawResources
|
|
324
|
+
: sortedResources;
|
|
351
325
|
let i = 0;
|
|
352
326
|
for (const resource of resources) {
|
|
353
327
|
i++;
|
|
354
|
-
lanes?.update(id, `${
|
|
355
|
-
resourceProgress.set(
|
|
328
|
+
lanes?.update(id, `${name}: Processing ${i}/${resources.length} (sent ${sheet.sentCount})%dots%`);
|
|
329
|
+
resourceProgress.set(name, i / resources.length);
|
|
356
330
|
updatePhase3Header();
|
|
357
331
|
const resourceData = await setting.eachResource(resource);
|
|
358
332
|
if (resourceData) {
|
|
359
|
-
|
|
333
|
+
await sheet.appendRow(...resourceData);
|
|
360
334
|
}
|
|
361
335
|
}
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
336
|
+
await runFinalizeResources({
|
|
337
|
+
setting,
|
|
338
|
+
sheet,
|
|
339
|
+
lanes,
|
|
340
|
+
laneId: id,
|
|
341
|
+
sheetName: name,
|
|
366
342
|
});
|
|
367
|
-
|
|
368
|
-
|
|
343
|
+
await sheet.flush();
|
|
344
|
+
sheetLog('[%s] Resource send complete (%d rows)', name, sheet.sentCount);
|
|
345
|
+
resourceProgress.set(name, 1);
|
|
369
346
|
updatePhase3Header();
|
|
370
|
-
markDone(
|
|
347
|
+
markDone(name, `${sheet.sentCount} rows`);
|
|
371
348
|
}));
|
|
372
349
|
sheetLog('Phase 3 complete');
|
|
373
350
|
}
|
|
@@ -388,7 +365,9 @@ export async function createSheets(params) {
|
|
|
388
365
|
}
|
|
389
366
|
const sheet = await sheets.create(name);
|
|
390
367
|
sheetLog('[%s] Sending %d rows', name, data.length);
|
|
391
|
-
|
|
368
|
+
lanes?.update(id, `${name}: Sending ${data.length} rows%dots%`);
|
|
369
|
+
await sheet.appendRow(...data);
|
|
370
|
+
await sheet.flush();
|
|
392
371
|
sheetLog('[%s] Plugin data send complete', name);
|
|
393
372
|
if (!completionDetails.has(name)) {
|
|
394
373
|
markDone(name, `${data.length} rows`);
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { CreateSheetSetting } from './types.js';
|
|
2
|
+
import type { Lanes } from '@d-zero/dealer';
|
|
3
|
+
import type { Sheet } from '@d-zero/google-sheets';
|
|
4
|
+
/**
|
|
5
|
+
* Parameters for {@link runFinalizeResources}.
|
|
6
|
+
*/
|
|
7
|
+
export interface RunFinalizeResourcesParams {
|
|
8
|
+
/** Sheet setting that may declare a `finalizeResources` hook. */
|
|
9
|
+
readonly setting: CreateSheetSetting;
|
|
10
|
+
/** Google Sheets wrapper that buffers and sends rows. */
|
|
11
|
+
readonly sheet: Sheet;
|
|
12
|
+
/** Optional Lanes instance for terminal progress display. */
|
|
13
|
+
readonly lanes?: Lanes;
|
|
14
|
+
/** Lane ID assigned to this sheet. */
|
|
15
|
+
readonly laneId: number;
|
|
16
|
+
/** Display name of the sheet (used in progress messages). */
|
|
17
|
+
readonly sheetName: string;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Calls the `finalizeResources` hook (Phase 3 terminator) and streams the
|
|
21
|
+
* aggregated rows through `sheet.appendRow(...rows)`, subscribing to
|
|
22
|
+
* `sheet.onProgress` so chunk-flush progress is mirrored to Lanes.
|
|
23
|
+
*
|
|
24
|
+
* - No-op when the setting has no `finalizeResources` hook.
|
|
25
|
+
* - No-op when the hook returns `null` / empty array.
|
|
26
|
+
* - Always resets `sheet.onProgress` in a `finally` block, even when
|
|
27
|
+
* `appendRow` throws — preventing a stale handler from leaking into
|
|
28
|
+
* a different sheet's lane.
|
|
29
|
+
* @param params - Hook invocation context (see {@link RunFinalizeResourcesParams}).
|
|
30
|
+
*/
|
|
31
|
+
export declare function runFinalizeResources(params: RunFinalizeResourcesParams): Promise<void>;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { sheetLog } from '../debug.js';
|
|
2
|
+
/**
|
|
3
|
+
* Calls the `finalizeResources` hook (Phase 3 terminator) and streams the
|
|
4
|
+
* aggregated rows through `sheet.appendRow(...rows)`, subscribing to
|
|
5
|
+
* `sheet.onProgress` so chunk-flush progress is mirrored to Lanes.
|
|
6
|
+
*
|
|
7
|
+
* - No-op when the setting has no `finalizeResources` hook.
|
|
8
|
+
* - No-op when the hook returns `null` / empty array.
|
|
9
|
+
* - Always resets `sheet.onProgress` in a `finally` block, even when
|
|
10
|
+
* `appendRow` throws — preventing a stale handler from leaking into
|
|
11
|
+
* a different sheet's lane.
|
|
12
|
+
* @param params - Hook invocation context (see {@link RunFinalizeResourcesParams}).
|
|
13
|
+
*/
|
|
14
|
+
export async function runFinalizeResources(params) {
|
|
15
|
+
const { setting, sheet, lanes, laneId, sheetName } = params;
|
|
16
|
+
if (!setting.finalizeResources)
|
|
17
|
+
return;
|
|
18
|
+
lanes?.update(laneId, `${sheetName}: Finalizing aggregated rows%dots%`);
|
|
19
|
+
sheetLog('[%s] finalizeResources start', sheetName);
|
|
20
|
+
const finalRows = await setting.finalizeResources();
|
|
21
|
+
if (!finalRows || finalRows.length === 0)
|
|
22
|
+
return;
|
|
23
|
+
const total = finalRows.length;
|
|
24
|
+
lanes?.update(laneId, `${sheetName}: Sending 0/${total} aggregated rows%dots%`);
|
|
25
|
+
sheet.onProgress = (sent) => {
|
|
26
|
+
lanes?.update(laneId, `${sheetName}: Sending ${sent}/${total} aggregated rows%dots%`);
|
|
27
|
+
};
|
|
28
|
+
try {
|
|
29
|
+
await sheet.appendRow(...finalRows);
|
|
30
|
+
}
|
|
31
|
+
finally {
|
|
32
|
+
sheet.onProgress = undefined;
|
|
33
|
+
}
|
|
34
|
+
sheetLog('[%s] finalizeResources emitted %d rows', sheetName, total);
|
|
35
|
+
}
|
package/lib/sheets/types.d.ts
CHANGED
|
@@ -71,10 +71,39 @@ export interface CreateSheetSetting {
|
|
|
71
71
|
eachPage?: (page: Page, num: number, total: number, prevPage: Page | null) => Promiseable<Cell[][] | null | void>;
|
|
72
72
|
/**
|
|
73
73
|
* Generates row data for a single network resource.
|
|
74
|
+
*
|
|
75
|
+
* To accumulate state across all resources and emit aggregated rows
|
|
76
|
+
* once at the end, use {@link CreateSheetSetting.finalizeResources}
|
|
77
|
+
* instead of trying to detect the final iteration here.
|
|
74
78
|
* @param resource - The resource record from the archive.
|
|
75
79
|
* @returns Row data, `null`/`void` to skip.
|
|
76
80
|
*/
|
|
77
81
|
eachResource?: (resource: Resource) => Promiseable<Cell[][] | null | void>;
|
|
82
|
+
/**
|
|
83
|
+
* When `true`, the Phase 3 dispatcher does **not** sort the
|
|
84
|
+
* resources array before calling `eachResource`; the setting takes
|
|
85
|
+
* full responsibility for ordering its own output (typically by
|
|
86
|
+
* sorting the aggregated rows inside `finalizeResources`).
|
|
87
|
+
*
|
|
88
|
+
* Useful for dedupe-style settings where sorting the raw 1M+
|
|
89
|
+
* resource list up front is wasted work — the aggregated output
|
|
90
|
+
* is orders of magnitude smaller, so sorting *after* aggregation
|
|
91
|
+
* is far cheaper. Defaults to `false` (sorted insertion order).
|
|
92
|
+
*/
|
|
93
|
+
skipSortResources?: boolean;
|
|
94
|
+
/**
|
|
95
|
+
* Phase 3 terminator hook called exactly once after the entire
|
|
96
|
+
* `eachResource` loop completes (before the final
|
|
97
|
+
* `sheet.flush()`). Use for factories that accumulate state during
|
|
98
|
+
* `eachResource` and want to emit aggregated rows in one batch —
|
|
99
|
+
* e.g. dedupe-by-canonical-URL aggregation.
|
|
100
|
+
*
|
|
101
|
+
* Decoupled from `eachResource` so the contract does not depend on
|
|
102
|
+
* the Phase 3 implementation (sequential vs. parallel iteration,
|
|
103
|
+
* exact `num/total` semantics, etc.).
|
|
104
|
+
* @returns Row data to append, `null`/`void` to emit nothing.
|
|
105
|
+
*/
|
|
106
|
+
finalizeResources?: () => Promiseable<Cell[][] | null | void>;
|
|
78
107
|
/**
|
|
79
108
|
* Generates additional rows from plugin report data.
|
|
80
109
|
* Called once after the factory, not per-page. Runs in parallel
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonicalize a resource URL by stripping query parameter *values*
|
|
3
|
+
* while preserving every other part of the URL.
|
|
4
|
+
*
|
|
5
|
+
* - Scheme / host / port / path are returned verbatim.
|
|
6
|
+
* - The query string is rewritten to a sorted, deduplicated list of
|
|
7
|
+
* parameter keys joined by `&`, with all values discarded.
|
|
8
|
+
* - URLs without a query string are returned unchanged.
|
|
9
|
+
*
|
|
10
|
+
* This is intentionally simpler than {@link URL}/`URLSearchParams`: it
|
|
11
|
+
* neither percent-decodes nor reorders anything outside the query
|
|
12
|
+
* string, so two raw URLs that differ only in per-request query values
|
|
13
|
+
* collapse to the same canonical form without changing path-embedded
|
|
14
|
+
* identifiers (e.g. tracking IDs in `/pagead/viewthroughconversion/<id>/`).
|
|
15
|
+
* @param url - The raw resource URL as stored in the archive. The
|
|
16
|
+
* archive stores URLs in `withoutHash` form (no `#fragment`); if
|
|
17
|
+
* you pass a URL with a fragment, the fragment will leak into the
|
|
18
|
+
* last value but the canonical key list is unaffected.
|
|
19
|
+
* @returns The canonicalized URL.
|
|
20
|
+
* @example
|
|
21
|
+
* ```ts
|
|
22
|
+
* canonicalizeUrl('https://x.com/p/123?b=Y&a=X&a=Z');
|
|
23
|
+
* // → 'https://x.com/p/123?a&b'
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
export declare function canonicalizeUrl(url: string): string;
|
|
27
|
+
/**
|
|
28
|
+
* Parses the query string of a URL and returns its `(key, value)` pairs
|
|
29
|
+
* in source order. Keys are kept as written (no percent-decoding, no
|
|
30
|
+
* sort, no dedupe) so callers can distinguish e.g. `a=1&a=2` as two
|
|
31
|
+
* separate pairs. Values are the raw substring after the first `=`;
|
|
32
|
+
* pairs with no `=` get an empty-string value, and pairs with no key
|
|
33
|
+
* are skipped.
|
|
34
|
+
*
|
|
35
|
+
* Returns an empty array for URLs without a query string or with an
|
|
36
|
+
* empty query string.
|
|
37
|
+
*
|
|
38
|
+
* **Fragment caveat:** This function does not strip `#fragment` from
|
|
39
|
+
* the URL. The archive's `resources.url` column already stores URLs
|
|
40
|
+
* in `withoutHash` form so this is normally a no-op, but callers
|
|
41
|
+
* passing in arbitrary URLs should strip the fragment first if they
|
|
42
|
+
* care about clean values.
|
|
43
|
+
* @param url - The raw resource URL as stored in the archive.
|
|
44
|
+
* @example
|
|
45
|
+
* ```ts
|
|
46
|
+
* extractQueryPairs('https://x.com/p?a=1&b=2&a=3');
|
|
47
|
+
* // → [{ key: 'a', value: '1' }, { key: 'b', value: '2' }, { key: 'a', value: '3' }]
|
|
48
|
+
* ```
|
|
49
|
+
*/
|
|
50
|
+
export declare function extractQueryPairs(url: string): Array<{
|
|
51
|
+
readonly key: string;
|
|
52
|
+
readonly value: string;
|
|
53
|
+
}>;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Splits a raw query string body (the substring **after** the leading
|
|
3
|
+
* `?`, with no `#fragment` attached) into `(key, value)` pairs in
|
|
4
|
+
* source order. Internal helper shared between {@link canonicalizeUrl}
|
|
5
|
+
* and {@link extractQueryPairs} so the two stay consistent.
|
|
6
|
+
*
|
|
7
|
+
* - No percent-decoding, no sort, no dedupe — callers handle those.
|
|
8
|
+
* - Pairs with an empty key are skipped (matches URL semantics: a
|
|
9
|
+
* leading `&` or `=value` is ignored).
|
|
10
|
+
* - Pairs without `=` get an empty-string value.
|
|
11
|
+
*
|
|
12
|
+
* Returns an empty array for the empty query string.
|
|
13
|
+
* @param query - The query string body without the leading `?`.
|
|
14
|
+
*/
|
|
15
|
+
function parseQueryPairs(query) {
|
|
16
|
+
if (query.length === 0) {
|
|
17
|
+
return [];
|
|
18
|
+
}
|
|
19
|
+
const pairs = [];
|
|
20
|
+
for (const pair of query.split('&')) {
|
|
21
|
+
const eq = pair.indexOf('=');
|
|
22
|
+
const key = eq === -1 ? pair : pair.slice(0, eq);
|
|
23
|
+
if (key.length === 0) {
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
const value = eq === -1 ? '' : pair.slice(eq + 1);
|
|
27
|
+
pairs.push({ key, value });
|
|
28
|
+
}
|
|
29
|
+
return pairs;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Canonicalize a resource URL by stripping query parameter *values*
|
|
33
|
+
* while preserving every other part of the URL.
|
|
34
|
+
*
|
|
35
|
+
* - Scheme / host / port / path are returned verbatim.
|
|
36
|
+
* - The query string is rewritten to a sorted, deduplicated list of
|
|
37
|
+
* parameter keys joined by `&`, with all values discarded.
|
|
38
|
+
* - URLs without a query string are returned unchanged.
|
|
39
|
+
*
|
|
40
|
+
* This is intentionally simpler than {@link URL}/`URLSearchParams`: it
|
|
41
|
+
* neither percent-decodes nor reorders anything outside the query
|
|
42
|
+
* string, so two raw URLs that differ only in per-request query values
|
|
43
|
+
* collapse to the same canonical form without changing path-embedded
|
|
44
|
+
* identifiers (e.g. tracking IDs in `/pagead/viewthroughconversion/<id>/`).
|
|
45
|
+
* @param url - The raw resource URL as stored in the archive. The
|
|
46
|
+
* archive stores URLs in `withoutHash` form (no `#fragment`); if
|
|
47
|
+
* you pass a URL with a fragment, the fragment will leak into the
|
|
48
|
+
* last value but the canonical key list is unaffected.
|
|
49
|
+
* @returns The canonicalized URL.
|
|
50
|
+
* @example
|
|
51
|
+
* ```ts
|
|
52
|
+
* canonicalizeUrl('https://x.com/p/123?b=Y&a=X&a=Z');
|
|
53
|
+
* // → 'https://x.com/p/123?a&b'
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
export function canonicalizeUrl(url) {
|
|
57
|
+
const qIndex = url.indexOf('?');
|
|
58
|
+
if (qIndex === -1) {
|
|
59
|
+
return url;
|
|
60
|
+
}
|
|
61
|
+
const head = url.slice(0, qIndex);
|
|
62
|
+
const query = url.slice(qIndex + 1);
|
|
63
|
+
if (query.length === 0) {
|
|
64
|
+
return head + '?';
|
|
65
|
+
}
|
|
66
|
+
const pairs = parseQueryPairs(query);
|
|
67
|
+
const keys = pairs.map((pair) => pair.key).toSorted();
|
|
68
|
+
const unique = [];
|
|
69
|
+
for (let i = 0; i < keys.length; i++) {
|
|
70
|
+
if (i === 0 || keys[i] !== keys[i - 1]) {
|
|
71
|
+
unique.push(keys[i]);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return head + '?' + unique.join('&');
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Parses the query string of a URL and returns its `(key, value)` pairs
|
|
78
|
+
* in source order. Keys are kept as written (no percent-decoding, no
|
|
79
|
+
* sort, no dedupe) so callers can distinguish e.g. `a=1&a=2` as two
|
|
80
|
+
* separate pairs. Values are the raw substring after the first `=`;
|
|
81
|
+
* pairs with no `=` get an empty-string value, and pairs with no key
|
|
82
|
+
* are skipped.
|
|
83
|
+
*
|
|
84
|
+
* Returns an empty array for URLs without a query string or with an
|
|
85
|
+
* empty query string.
|
|
86
|
+
*
|
|
87
|
+
* **Fragment caveat:** This function does not strip `#fragment` from
|
|
88
|
+
* the URL. The archive's `resources.url` column already stores URLs
|
|
89
|
+
* in `withoutHash` form so this is normally a no-op, but callers
|
|
90
|
+
* passing in arbitrary URLs should strip the fragment first if they
|
|
91
|
+
* care about clean values.
|
|
92
|
+
* @param url - The raw resource URL as stored in the archive.
|
|
93
|
+
* @example
|
|
94
|
+
* ```ts
|
|
95
|
+
* extractQueryPairs('https://x.com/p?a=1&b=2&a=3');
|
|
96
|
+
* // → [{ key: 'a', value: '1' }, { key: 'b', value: '2' }, { key: 'a', value: '3' }]
|
|
97
|
+
* ```
|
|
98
|
+
*/
|
|
99
|
+
export function extractQueryPairs(url) {
|
|
100
|
+
const qIndex = url.indexOf('?');
|
|
101
|
+
if (qIndex === -1) {
|
|
102
|
+
return [];
|
|
103
|
+
}
|
|
104
|
+
return parseQueryPairs(url.slice(qIndex + 1));
|
|
105
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Natural-order string comparator, ported from Martin Pool's
|
|
3
|
+
* `strnatcmp.c` (sourcefrog/natsort, originally derived from Stuart
|
|
4
|
+
* Cheshire's 1996 Macintosh natural sort). Faithful to the C
|
|
5
|
+
* reference's dispatch:
|
|
6
|
+
*
|
|
7
|
+
* - Skip leading ASCII whitespace on both sides.
|
|
8
|
+
* - When both sides have a digit run:
|
|
9
|
+
* - If **either** run starts with `'0'`, treat them as fractional
|
|
10
|
+
* and use {@link compareLeft} (left-aligned digit-by-digit).
|
|
11
|
+
* - Otherwise use {@link compareRight} (length-first, with bias for
|
|
12
|
+
* ties).
|
|
13
|
+
* - End-of-string on both sides means equal.
|
|
14
|
+
* - Otherwise fold ASCII letters to lower case and compare one
|
|
15
|
+
* UTF-16 code unit.
|
|
16
|
+
*
|
|
17
|
+
* Allocates no intermediate strings: only `charCodeAt` and integer
|
|
18
|
+
* arithmetic. That makes the function safe to invoke O(N log N)
|
|
19
|
+
* times during a 1M+ element sort without inflating the V8 heap with
|
|
20
|
+
* derived `SeqString` allocations.
|
|
21
|
+
*
|
|
22
|
+
* **Benchmark reference (Node 24, M-class CPU):** 100K-entry sort
|
|
23
|
+
* completes in ~650 ms with median heap delta ratio
|
|
24
|
+
* `heapDelta(100K) / heapDelta(10K) ≈ 5–15×`. If either measurement
|
|
25
|
+
* jumps by an order of magnitude (multi-second elapsed, ratio > 100),
|
|
26
|
+
* suspect a regression that reintroduced per-compare string
|
|
27
|
+
* allocation or `Intl.Collator` dispatch.
|
|
28
|
+
*
|
|
29
|
+
* **UTF-16 semantics:** index moves one code unit per step. ASCII
|
|
30
|
+
* URLs (the only kind the archive currently stores) are entirely
|
|
31
|
+
* BMP, so this is equivalent to per-character iteration. URLs that
|
|
32
|
+
* contain surrogate pairs (e.g. raw emoji in path segments) compare
|
|
33
|
+
* as UTF-16 code unit sequences, which is deterministic but not
|
|
34
|
+
* equivalent to Unicode code-point order. That matches `strnatcmp.c`
|
|
35
|
+
* — it also operates on bytes, not Unicode scalars.
|
|
36
|
+
* @param a - First URL.
|
|
37
|
+
* @param b - Second URL.
|
|
38
|
+
* @returns Negative if `a < b`, positive if `a > b`, zero if equal.
|
|
39
|
+
*/
|
|
40
|
+
export declare function naturalCompare(a: string, b: string): number;
|
|
41
|
+
/**
|
|
42
|
+
* Sorts archive resources by their URL in natural order, returning a
|
|
43
|
+
* new array (the input is left untouched). Uses
|
|
44
|
+
* {@link naturalCompare} as the comparator, so embedded integers
|
|
45
|
+
* compare by value (`image-2.jpg` < `image-10.jpg`) and ASCII case
|
|
46
|
+
* is folded.
|
|
47
|
+
*
|
|
48
|
+
* The sort is stable (V8 TimSort). Each comparison allocates no
|
|
49
|
+
* intermediate strings, so the only extra memory is V8's TimSort
|
|
50
|
+
* auxiliary buffer — O(N) pointer-sized entries, not O(N × URL length).
|
|
51
|
+
* @param resources - The list of resources to sort. Only the `url`
|
|
52
|
+
* field is read.
|
|
53
|
+
* @returns A new array sorted by URL in natural order.
|
|
54
|
+
* @example
|
|
55
|
+
* ```ts
|
|
56
|
+
* sortResourcesByUrl([
|
|
57
|
+
* { url: 'https://x/img-10.jpg' },
|
|
58
|
+
* { url: 'https://x/img-2.jpg' },
|
|
59
|
+
* { url: 'https://x/img-1.jpg' },
|
|
60
|
+
* ]);
|
|
61
|
+
* // → [{ url: 'https://x/img-1.jpg' }, { url: 'https://x/img-2.jpg' }, { url: 'https://x/img-10.jpg' }]
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
export declare function sortResourcesByUrl<T extends {
|
|
65
|
+
readonly url: string;
|
|
66
|
+
}>(resources: readonly T[]): T[];
|