link-cache 0.3.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/LICENSE +201 -0
- package/README.md +86 -0
- package/check/index.mjs +130 -0
- package/package.json +42 -0
- package/refcache/index.mjs +332 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# link-cache
|
|
2
|
+
|
|
3
|
+
Zero-dependency helper CLIs for **cached** link checking with [Lychee][], for
|
|
4
|
+
any static site that builds to a `public/` directory (Docsy, Hugo, and others).
|
|
5
|
+
Two tools:
|
|
6
|
+
|
|
7
|
+
- **`lychee-norm-cache`** — run lychee over your built `public/` output, then
|
|
8
|
+
normalize `.lycheecache` so reruns and commits stay byte stable.
|
|
9
|
+
- **`refcache`** — inspect and prune that `.lycheecache` (the "refcache"): list
|
|
10
|
+
the oldest entries, prune a count or percentage, or print a summary.
|
|
11
|
+
|
|
12
|
+
With a committed `lychee.toml` and `.lycheecache`, these give a site a
|
|
13
|
+
self-contained, cached link-checking setup: fast reruns, and diffs that only
|
|
14
|
+
change when links actually change.
|
|
15
|
+
|
|
16
|
+
## Requirements
|
|
17
|
+
|
|
18
|
+
- The [lychee][] binary on your `PATH`.
|
|
19
|
+
- A `lychee.toml` at your site root (lychee's config and ignore rules).
|
|
20
|
+
- A built site under `public/` (run your site build first).
|
|
21
|
+
- [Node.js][] ≥ 24.
|
|
22
|
+
- Optional: the [`gh`][gh] CLI — `lychee-norm-cache` bridges its token to lychee
|
|
23
|
+
to raise the github.com rate limit when `GITHUB_TOKEN` isn't already set.
|
|
24
|
+
|
|
25
|
+
## Install
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
npm install --save-dev link-cache
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Or, to install from GitHub rather than the npm registry:
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
npm install --save-dev github:chalin/link-cache#semver:^0.3.0
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
This puts both bins on your project's `PATH`.
|
|
38
|
+
|
|
39
|
+
## Usage
|
|
40
|
+
|
|
41
|
+
Wire the bins into your `package.json` scripts (bare names — `npm run` puts
|
|
42
|
+
`node_modules/.bin` on the `PATH`):
|
|
43
|
+
|
|
44
|
+
```json
|
|
45
|
+
"scripts": {
|
|
46
|
+
"check:links": "lychee-norm-cache",
|
|
47
|
+
"refcache": "refcache"
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
npm run check:links # check links, then sort/normalize the cache
|
|
53
|
+
npm run refcache -- --summary # cache stats (count, oldest, status, ages)
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
> [!WARNING]
|
|
57
|
+
>
|
|
58
|
+
> Don't invoke these bins via `npx`: this package isn't on the npm registry, so
|
|
59
|
+
> on a stale or missing `node_modules`, `npx` falls back to the public registry
|
|
60
|
+
> and runs **whatever package holds the name there** (the `lychee-norm-cache`
|
|
61
|
+
> name is squatted). Bare bin names in `npm run` scripts resolve locally or fail
|
|
62
|
+
> loudly — they never touch the registry.
|
|
63
|
+
|
|
64
|
+
`lychee-norm-cache` runs in the current directory (your site root) and forwards
|
|
65
|
+
any extra arguments to lychee. Run either tool with `--help` for its full
|
|
66
|
+
options, and `lychee --help` for the link-checking flags `lychee-norm-cache`
|
|
67
|
+
forwards (e.g. `--offline`, `--max-cache-age 0`).
|
|
68
|
+
|
|
69
|
+
## Development
|
|
70
|
+
|
|
71
|
+
The published CLIs have **zero runtime dependencies**; Prettier is the only dev
|
|
72
|
+
dependency. Run the checks (format + tests) with:
|
|
73
|
+
|
|
74
|
+
```sh
|
|
75
|
+
npm install
|
|
76
|
+
npm run check
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Tests use Node's built-in test runner (`node --test`) and need no network or the
|
|
80
|
+
lychee binary.
|
|
81
|
+
|
|
82
|
+
<!-- prettier-ignore-start -->
|
|
83
|
+
[Lychee]: https://github.com/lycheeverse/lychee
|
|
84
|
+
[Node.js]: https://nodejs.org/
|
|
85
|
+
[gh]: https://cli.github.com/
|
|
86
|
+
<!-- prettier-ignore-end -->
|
package/check/index.mjs
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The `lychee-norm-cache` bin: run lychee over a built site and normalize
|
|
3
|
+
// .lycheecache for byte-stable reruns. Runs in the cwd (the site root), so any
|
|
4
|
+
// site with a lychee.toml can reuse it. Run with `--help` for usage.
|
|
5
|
+
//
|
|
6
|
+
// When GITHUB_TOKEN is unset, a token is bridged from the gh CLI — lychee reads
|
|
7
|
+
// GITHUB_TOKEN, which also lifts the github.com rate limit; CI sets it directly.
|
|
8
|
+
|
|
9
|
+
import { spawnSync } from 'node:child_process';
|
|
10
|
+
import {
|
|
11
|
+
existsSync,
|
|
12
|
+
readFileSync,
|
|
13
|
+
realpathSync,
|
|
14
|
+
statSync,
|
|
15
|
+
writeFileSync,
|
|
16
|
+
} from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import { fileURLToPath } from 'node:url';
|
|
19
|
+
|
|
20
|
+
const INSTALL_HINT = 'https://github.com/lycheeverse/lychee#installation';
|
|
21
|
+
|
|
22
|
+
const USAGE = `Usage: lychee-norm-cache [lychee args...]
|
|
23
|
+
|
|
24
|
+
Run lychee over this site's built ./public output, then normalize .lycheecache
|
|
25
|
+
so reruns stay byte stable. Bridges a GitHub token from the gh CLI when
|
|
26
|
+
GITHUB_TOKEN isn't set; extra arguments pass through to lychee.
|
|
27
|
+
|
|
28
|
+
-h, --help show this help
|
|
29
|
+
|
|
30
|
+
Requires the lychee binary on your PATH and a lychee.toml at the site root.
|
|
31
|
+
Run \`lychee --help\` for all link-checking options.`;
|
|
32
|
+
|
|
33
|
+
// --- pure helpers (unit-tested) --------------------------------------------
|
|
34
|
+
|
|
35
|
+
// Prefer an existing GITHUB_TOKEN; otherwise fall back to the gh CLI; '' if neither.
|
|
36
|
+
export function resolveToken({ env = process.env, runGh = ghAuthToken } = {}) {
|
|
37
|
+
const fromEnv = (env.GITHUB_TOKEN ?? '').trim();
|
|
38
|
+
if (fromEnv) return fromEnv;
|
|
39
|
+
return (runGh() ?? '').trim();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Sort .lycheecache by raw byte value (matching `LC_ALL=C sort`) and terminate
|
|
43
|
+
// with a single newline, so lychee's nondeterministic cache writes diff cleanly.
|
|
44
|
+
// Byte order via Buffer.compare — not JS string order, which compares UTF-16
|
|
45
|
+
// code units and can diverge from LC_ALL=C on non-ASCII URLs.
|
|
46
|
+
export function sortCacheText(text) {
|
|
47
|
+
const lines = text.split('\n');
|
|
48
|
+
if (lines.length && lines[lines.length - 1] === '') lines.pop();
|
|
49
|
+
if (lines.length === 0) return '';
|
|
50
|
+
lines.sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b)));
|
|
51
|
+
return lines.join('\n') + '\n';
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Return the site's public/ dir under the given cwd, or null if missing.
|
|
55
|
+
// The path is kept lexical (symlinks unresolved): sites often symlink public/
|
|
56
|
+
// to a separate diffable repo, and the /public/-anchored exclude_path patterns
|
|
57
|
+
// in lychee.toml silently stop matching if the path handed to lychee no longer
|
|
58
|
+
// contains the /public component.
|
|
59
|
+
export function publicDirOf(cwd) {
|
|
60
|
+
const publicDir = path.join(cwd, 'public');
|
|
61
|
+
try {
|
|
62
|
+
if (!statSync(publicDir).isDirectory()) return null;
|
|
63
|
+
} catch {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
return publicDir;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// --- lychee invocation -----------------------------------------------------
|
|
70
|
+
|
|
71
|
+
function ghAuthToken() {
|
|
72
|
+
const r = spawnSync('gh', ['auth', 'token'], { encoding: 'utf8' });
|
|
73
|
+
return r.error || r.status !== 0 ? '' : (r.stdout ?? '').trim();
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function hasLychee() {
|
|
77
|
+
return !spawnSync('lychee', ['--version'], { stdio: 'ignore' }).error;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function main(argv) {
|
|
81
|
+
if (argv.includes('-h') || argv.includes('--help')) {
|
|
82
|
+
console.log(USAGE);
|
|
83
|
+
return 0;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (!hasLychee()) {
|
|
87
|
+
process.stderr.write(`[help] lychee not found. Install: ${INSTALL_HINT}\n`);
|
|
88
|
+
return 1;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const cwd = process.cwd();
|
|
92
|
+
const publicDir = publicDirOf(cwd);
|
|
93
|
+
if (!publicDir) {
|
|
94
|
+
process.stderr.write(
|
|
95
|
+
`[help] ${path.join(cwd, 'public')} not found. Build the site first.\n`,
|
|
96
|
+
);
|
|
97
|
+
return 1;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const token = resolveToken();
|
|
101
|
+
const status =
|
|
102
|
+
spawnSync(
|
|
103
|
+
'lychee',
|
|
104
|
+
['--config', 'lychee.toml', '--root-dir', publicDir, ...argv, publicDir],
|
|
105
|
+
{ stdio: 'inherit', env: { ...process.env, GITHUB_TOKEN: token } },
|
|
106
|
+
).status ?? 1;
|
|
107
|
+
|
|
108
|
+
// Normalize the cache even on failure, so a partial run still leaves a stable
|
|
109
|
+
// .lycheecache.
|
|
110
|
+
const cachePath = path.join(cwd, '.lycheecache');
|
|
111
|
+
if (existsSync(cachePath)) {
|
|
112
|
+
writeFileSync(cachePath, sortCacheText(readFileSync(cachePath, 'utf8')));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return status;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Real-path compare, not `file://${argv[1]}`: npm links bins as symlinks, so
|
|
119
|
+
// argv[1] is the symlink while import.meta.url is the real path.
|
|
120
|
+
function isEntryPoint() {
|
|
121
|
+
try {
|
|
122
|
+
return realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
|
|
123
|
+
} catch {
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (isEntryPoint()) {
|
|
129
|
+
process.exit(main(process.argv.slice(2)));
|
|
130
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "link-cache",
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Zero-dependency helper CLIs for cached Lychee link-checking: lychee-norm-cache (run + normalize .lycheecache) and refcache (inspect/prune the cache).",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"lychee",
|
|
7
|
+
"link-checker",
|
|
8
|
+
"link-checking",
|
|
9
|
+
"cache",
|
|
10
|
+
"cli"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://github.com/chalin/link-cache#readme",
|
|
13
|
+
"bugs": "https://github.com/chalin/link-cache/issues",
|
|
14
|
+
"repository": "github:chalin/link-cache",
|
|
15
|
+
"license": "Apache-2.0",
|
|
16
|
+
"author": "Patrice Chalin",
|
|
17
|
+
"type": "module",
|
|
18
|
+
"bin": {
|
|
19
|
+
"lychee-norm-cache": "check/index.mjs",
|
|
20
|
+
"refcache": "refcache/index.mjs"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"check/index.mjs",
|
|
24
|
+
"refcache/index.mjs"
|
|
25
|
+
],
|
|
26
|
+
"scripts": {
|
|
27
|
+
"check": "npm run check:format && npm test",
|
|
28
|
+
"check:format": "prettier --check .",
|
|
29
|
+
"fix:format": "prettier --write .",
|
|
30
|
+
"test": "node --test"
|
|
31
|
+
},
|
|
32
|
+
"prettier": {
|
|
33
|
+
"proseWrap": "always",
|
|
34
|
+
"singleQuote": true
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"prettier": "^3.9.4"
|
|
38
|
+
},
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": ">=24"
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The `refcache` bin: inspect and prune a Lychee refcache. Read-only unless
|
|
3
|
+
// `--prune` is given, and never hits the network. Run with `--help` for usage.
|
|
4
|
+
//
|
|
5
|
+
// Refcache line format: URL,STATUS,UNIX_TIMESTAMP — the URL is CSV-quoted when
|
|
6
|
+
// it contains a comma, so STATUS and TIMESTAMP are read from the final two
|
|
7
|
+
// fields.
|
|
8
|
+
|
|
9
|
+
import { readFileSync, realpathSync, writeFileSync } from 'node:fs';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
|
|
12
|
+
const DAY = 86400;
|
|
13
|
+
const BUCKET_COUNT = 5;
|
|
14
|
+
const DEFAULT_PATH = '.lycheecache';
|
|
15
|
+
|
|
16
|
+
// --- parsing ---------------------------------------------------------------
|
|
17
|
+
|
|
18
|
+
function parseLine(raw) {
|
|
19
|
+
const lastComma = raw.lastIndexOf(',');
|
|
20
|
+
if (lastComma < 0) return null;
|
|
21
|
+
const ts = Number(raw.slice(lastComma + 1));
|
|
22
|
+
const head = raw.slice(0, lastComma);
|
|
23
|
+
const statusComma = head.lastIndexOf(',');
|
|
24
|
+
if (statusComma < 0) return null;
|
|
25
|
+
const status = head.slice(statusComma + 1).trim();
|
|
26
|
+
const url = head.slice(0, statusComma);
|
|
27
|
+
if (!Number.isInteger(ts) || status === '') return null;
|
|
28
|
+
return { url, status, ts };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Parse the whole file, keeping the original lines (so a prune can rewrite the
|
|
32
|
+
// file with a minimal, still-sorted diff) and tagging each entry with its line
|
|
33
|
+
// index.
|
|
34
|
+
export function parseCache(text) {
|
|
35
|
+
const lines = text.split('\n');
|
|
36
|
+
const entries = [];
|
|
37
|
+
let malformed = 0;
|
|
38
|
+
lines.forEach((raw, index) => {
|
|
39
|
+
if (raw.trim() === '') return;
|
|
40
|
+
const parsed = parseLine(raw);
|
|
41
|
+
if (!parsed) {
|
|
42
|
+
malformed += 1;
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
entries.push({ ...parsed, index });
|
|
46
|
+
});
|
|
47
|
+
return { lines, entries, malformed };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// --- selection / pruning ---------------------------------------------------
|
|
51
|
+
|
|
52
|
+
export function selectOldest(entries, n) {
|
|
53
|
+
return [...entries]
|
|
54
|
+
.sort((a, b) => a.ts - b.ts || a.index - b.index)
|
|
55
|
+
.slice(0, Math.max(0, n));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function resolvePruneCount(spec, total) {
|
|
59
|
+
const m = /^(\d+)(%?)$/.exec(String(spec));
|
|
60
|
+
if (!m) throw new Error(`--prune needs NUM or NUM%, got: ${spec}`);
|
|
61
|
+
const num = Number(m[1]);
|
|
62
|
+
const count = m[2] ? Math.floor((total * num) / 100) : num;
|
|
63
|
+
return Math.min(count, total);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// --- stats -----------------------------------------------------------------
|
|
67
|
+
|
|
68
|
+
// Equal-width age histogram over 0..maxAge with an open-ended final bucket. The
|
|
69
|
+
// width adapts to the data, so the split stays useful whether the cache spans a
|
|
70
|
+
// couple of weeks or a year.
|
|
71
|
+
function ageHistogram(ages, maxAgeDays) {
|
|
72
|
+
if (ages.length === 0) return [];
|
|
73
|
+
const width = Math.max(1, Math.ceil((maxAgeDays + 1) / BUCKET_COUNT));
|
|
74
|
+
const buckets = Array.from({ length: BUCKET_COUNT }, (_, i) => {
|
|
75
|
+
const lo = i * width;
|
|
76
|
+
const last = i === BUCKET_COUNT - 1;
|
|
77
|
+
return { label: last ? `≥${lo}d` : `${lo}–${lo + width}d`, count: 0 };
|
|
78
|
+
});
|
|
79
|
+
for (const age of ages) {
|
|
80
|
+
const i = Math.max(0, Math.min(BUCKET_COUNT - 1, Math.floor(age / width)));
|
|
81
|
+
buckets[i].count += 1;
|
|
82
|
+
}
|
|
83
|
+
return buckets;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function computeStats(
|
|
87
|
+
entries,
|
|
88
|
+
{ now = Date.now() / 1000, malformed = 0, pruned = 0 } = {},
|
|
89
|
+
) {
|
|
90
|
+
const statusCounts = new Map();
|
|
91
|
+
const ages = [];
|
|
92
|
+
let oldestTs = null;
|
|
93
|
+
let newestTs = null;
|
|
94
|
+
|
|
95
|
+
for (const entry of entries) {
|
|
96
|
+
statusCounts.set(entry.status, (statusCounts.get(entry.status) ?? 0) + 1);
|
|
97
|
+
if (oldestTs === null || entry.ts < oldestTs) oldestTs = entry.ts;
|
|
98
|
+
if (newestTs === null || entry.ts > newestTs) newestTs = entry.ts;
|
|
99
|
+
ages.push(Math.floor((now - entry.ts) / DAY));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const byStatus = [...statusCounts.entries()].sort(
|
|
103
|
+
(a, b) => b[1] - a[1] || a[0].localeCompare(b[0]),
|
|
104
|
+
);
|
|
105
|
+
|
|
106
|
+
const at = (ts) =>
|
|
107
|
+
ts === null ? null : { ts, ageDays: Math.floor((now - ts) / DAY) };
|
|
108
|
+
const oldest = at(oldestTs);
|
|
109
|
+
|
|
110
|
+
return {
|
|
111
|
+
count: entries.length,
|
|
112
|
+
malformed,
|
|
113
|
+
pruned,
|
|
114
|
+
byStatus,
|
|
115
|
+
oldest,
|
|
116
|
+
newest: at(newestTs),
|
|
117
|
+
ageBuckets: ageHistogram(ages, oldest ? oldest.ageDays : 0),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// --- rendering -------------------------------------------------------------
|
|
122
|
+
|
|
123
|
+
const pad2 = (n) => String(n).padStart(2, '0');
|
|
124
|
+
|
|
125
|
+
// Local-time `YYYY-MM-DD HH:MM:SS ZONE` — entries minutes apart share a date, so
|
|
126
|
+
// the time disambiguates them. Shown in the user's timezone (with a short zone
|
|
127
|
+
// label) to save them the UTC math.
|
|
128
|
+
const localStamp = (ts) => {
|
|
129
|
+
const d = new Date(ts * 1000);
|
|
130
|
+
const date = `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
|
|
131
|
+
const time = `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`;
|
|
132
|
+
const zone = new Intl.DateTimeFormat('en-US', { timeZoneName: 'short' })
|
|
133
|
+
.formatToParts(d)
|
|
134
|
+
.find((p) => p.type === 'timeZoneName')?.value;
|
|
135
|
+
return zone ? `${date} ${time} ${zone}` : `${date} ${time}`;
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
const displayUrl = (url) =>
|
|
139
|
+
url.startsWith('"') && url.endsWith('"')
|
|
140
|
+
? url.slice(1, -1).replace(/""/g, '"')
|
|
141
|
+
: url;
|
|
142
|
+
|
|
143
|
+
export function formatList(entries, n, { now = Date.now() / 1000 } = {}) {
|
|
144
|
+
const chosen = selectOldest(entries, n);
|
|
145
|
+
const head = `${chosen.length} oldest ${chosen.length === 1 ? 'entry' : 'entries'}:`;
|
|
146
|
+
const rows = chosen.map((e) => {
|
|
147
|
+
const ageDays = Math.floor((now - e.ts) / DAY);
|
|
148
|
+
return ` ${localStamp(e.ts)} ${String(ageDays).padStart(4)}d ${e.status} ${displayUrl(e.url)}`;
|
|
149
|
+
});
|
|
150
|
+
return [head, ...rows].join('\n');
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function formatStats(stats, { now = Date.now() / 1000, path } = {}) {
|
|
154
|
+
const lines = [];
|
|
155
|
+
lines.push(`Lychee refcache${path ? `: ${path}` : ''}`);
|
|
156
|
+
lines.push(` Entries: ${stats.count}`);
|
|
157
|
+
if (stats.pruned) {
|
|
158
|
+
const before = stats.count + stats.pruned;
|
|
159
|
+
lines.push(` Pruned: ${stats.pruned} (${before} → ${stats.count})`);
|
|
160
|
+
}
|
|
161
|
+
if (stats.malformed) lines.push(` Malformed lines: ${stats.malformed}`);
|
|
162
|
+
|
|
163
|
+
if (stats.oldest && stats.newest) {
|
|
164
|
+
lines.push(
|
|
165
|
+
` Oldest: ${localStamp(stats.oldest.ts)} (${stats.oldest.ageDays} days ago)`,
|
|
166
|
+
);
|
|
167
|
+
lines.push(
|
|
168
|
+
` Newest: ${localStamp(stats.newest.ts)} (${stats.newest.ageDays} days ago)`,
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
lines.push(' Status:');
|
|
173
|
+
for (const [status, n] of stats.byStatus) {
|
|
174
|
+
lines.push(` ${status.padEnd(5)} ${n}`);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (stats.ageBuckets.length) {
|
|
178
|
+
lines.push(' Age:');
|
|
179
|
+
const w = Math.max(...stats.ageBuckets.map((b) => b.label.length));
|
|
180
|
+
for (const { label, count } of stats.ageBuckets) {
|
|
181
|
+
lines.push(` ${label.padEnd(w)} ${count}`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
return lines.join('\n');
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// --- ordered execution -----------------------------------------------------
|
|
189
|
+
|
|
190
|
+
// Run the parsed ops in order over the evolving cache. Pure: returns the text to
|
|
191
|
+
// print and the lines to write (null when nothing was pruned); no I/O.
|
|
192
|
+
export function runOps(parsed, ops, { now = Date.now() / 1000, path } = {}) {
|
|
193
|
+
const removed = new Set();
|
|
194
|
+
let pruned = 0;
|
|
195
|
+
const out = [];
|
|
196
|
+
const current = () => parsed.entries.filter((e) => !removed.has(e.index));
|
|
197
|
+
|
|
198
|
+
for (const op of ops) {
|
|
199
|
+
if (op.kind === 'list') {
|
|
200
|
+
out.push(formatList(current(), Number(op.value), { now }));
|
|
201
|
+
} else if (op.kind === 'prune') {
|
|
202
|
+
const cur = current();
|
|
203
|
+
const k = resolvePruneCount(op.value, cur.length);
|
|
204
|
+
for (const victim of selectOldest(cur, k)) removed.add(victim.index);
|
|
205
|
+
pruned += k;
|
|
206
|
+
out.push(
|
|
207
|
+
`Pruned ${k} oldest ${k === 1 ? 'entry' : 'entries'} (${cur.length} → ${cur.length - k}).`,
|
|
208
|
+
);
|
|
209
|
+
} else if (op.kind === 'summary') {
|
|
210
|
+
const stats = computeStats(current(), {
|
|
211
|
+
now,
|
|
212
|
+
malformed: parsed.malformed,
|
|
213
|
+
pruned,
|
|
214
|
+
});
|
|
215
|
+
out.push(formatStats(stats, { now, path }));
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const writeLines =
|
|
220
|
+
pruned > 0 ? parsed.lines.filter((_, i) => !removed.has(i)) : null;
|
|
221
|
+
return { output: out.join('\n\n'), writeLines, pruned };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// --- CLI -------------------------------------------------------------------
|
|
225
|
+
|
|
226
|
+
const FLAGS = new Map([
|
|
227
|
+
['-l', 'list'],
|
|
228
|
+
['--list', 'list'],
|
|
229
|
+
['-p', 'prune'],
|
|
230
|
+
['--prune', 'prune'],
|
|
231
|
+
['-s', 'summary'],
|
|
232
|
+
['--summary', 'summary'],
|
|
233
|
+
]);
|
|
234
|
+
|
|
235
|
+
export function parseArgs(argv) {
|
|
236
|
+
const ops = [];
|
|
237
|
+
const seen = new Set();
|
|
238
|
+
let path = null;
|
|
239
|
+
let help = false;
|
|
240
|
+
|
|
241
|
+
for (let i = 0; i < argv.length; i++) {
|
|
242
|
+
const a = argv[i];
|
|
243
|
+
if (a === '-h' || a === '--help') {
|
|
244
|
+
help = true;
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
const kind = FLAGS.get(a);
|
|
248
|
+
if (kind) {
|
|
249
|
+
if (seen.has(kind)) throw new Error(`repeated flag: ${a}`);
|
|
250
|
+
seen.add(kind);
|
|
251
|
+
if (kind === 'summary') {
|
|
252
|
+
ops.push({ kind });
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
const value = argv[++i];
|
|
256
|
+
if (value === undefined) throw new Error(`${a} requires a value`);
|
|
257
|
+
if (kind === 'list' && !/^\d+$/.test(value)) {
|
|
258
|
+
throw new Error(`--list needs a count, got: ${value}`);
|
|
259
|
+
}
|
|
260
|
+
if (kind === 'prune' && !/^\d+%?$/.test(value)) {
|
|
261
|
+
throw new Error(`--prune needs NUM or NUM%, got: ${value}`);
|
|
262
|
+
}
|
|
263
|
+
ops.push({ kind, value });
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
if (a.startsWith('-')) throw new Error(`unknown flag: ${a}`);
|
|
267
|
+
if (path !== null) throw new Error(`unexpected extra argument: ${a}`);
|
|
268
|
+
path = a;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
return { ops, path: path ?? DEFAULT_PATH, help };
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
const USAGE = `Usage: refcache [REFCACHE_FILE] [options]
|
|
275
|
+
|
|
276
|
+
Inspect and prune a Lychee refcache (default: ${DEFAULT_PATH}). Options run in
|
|
277
|
+
the order given, over the evolving cache, so \`-l 5 -p 5\` lists the 5 oldest
|
|
278
|
+
about to be pruned, while \`-p 5 -l 5\` lists the next 5 after pruning.
|
|
279
|
+
|
|
280
|
+
-l, --list NUM list the NUM oldest entries
|
|
281
|
+
-p, --prune NUM[%] drop the NUM (or NUM%) oldest entries, then rewrite
|
|
282
|
+
-s, --summary print a summary (counts, ages, status, histogram)
|
|
283
|
+
-h, --help show this help
|
|
284
|
+
|
|
285
|
+
With no options, prints the summary. A flag may not be repeated.`;
|
|
286
|
+
|
|
287
|
+
function main(argv) {
|
|
288
|
+
let args;
|
|
289
|
+
try {
|
|
290
|
+
args = parseArgs(argv);
|
|
291
|
+
} catch (err) {
|
|
292
|
+
console.error(`[error] ${err.message}\n`);
|
|
293
|
+
console.error(USAGE);
|
|
294
|
+
process.exit(2);
|
|
295
|
+
}
|
|
296
|
+
if (args.help) {
|
|
297
|
+
console.log(USAGE);
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
let text;
|
|
302
|
+
try {
|
|
303
|
+
text = readFileSync(args.path, 'utf8');
|
|
304
|
+
} catch {
|
|
305
|
+
console.error(`[error] cannot read refcache file: ${args.path}`);
|
|
306
|
+
process.exit(1);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const now = Date.now() / 1000;
|
|
310
|
+
const ops = args.ops.length ? args.ops : [{ kind: 'summary' }];
|
|
311
|
+
const { output, writeLines } = runOps(parseCache(text), ops, {
|
|
312
|
+
now,
|
|
313
|
+
path: args.path,
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
if (output) console.log(output);
|
|
317
|
+
if (writeLines) writeFileSync(args.path, writeLines.join('\n'));
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// Real-path compare, not `file://${argv[1]}`: npm links bins as symlinks, so
|
|
321
|
+
// argv[1] is the symlink while import.meta.url is the real path.
|
|
322
|
+
function isEntryPoint() {
|
|
323
|
+
try {
|
|
324
|
+
return realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
|
|
325
|
+
} catch {
|
|
326
|
+
return false;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
if (isEntryPoint()) {
|
|
331
|
+
main(process.argv.slice(2));
|
|
332
|
+
}
|