@yourfam/yf-npm-search 0.0.0-stage → 0.1.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 +21 -0
- package/README.md +89 -2
- package/bin/yf-npm-search.js +8 -0
- package/package.json +37 -6
- package/src/args.js +103 -0
- package/src/cli.js +266 -0
- package/src/colors.js +8 -0
- package/src/desktop.js +59 -0
- package/src/errors.js +7 -0
- package/src/format.js +41 -0
- package/src/model.js +110 -0
- package/src/npm.js +182 -0
- package/src/prompt.js +35 -0
- package/src/render.js +131 -0
- package/src/version.js +5 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 YourFam
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,90 @@
|
|
|
1
|
-
#
|
|
1
|
+
# yf-npm-search
|
|
2
|
+
|
|
3
|
+
One command. It reads the npm registry and prints one row per package. Scoped packages and their unscoped aliases are separate rows, listed one after the other. The console is the default. A Markdown file is written only when asked.
|
|
4
|
+
|
|
5
|
+
Node 20+. MIT. Zero runtime dependencies. `"type": "module"`.
|
|
6
|
+
|
|
7
|
+
| What | Name |
|
|
8
|
+
|---|---|
|
|
9
|
+
| GitHub | `YourFam/yf-npm-search` |
|
|
10
|
+
| npm | `@yourfam/yf-npm-search` |
|
|
11
|
+
| Command | `yf-npm-search` |
|
|
12
|
+
| Unscoped alias package | `yf-npm-search` |
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
npm install -g @yourfam/yf-npm-search
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Usage
|
|
21
|
+
|
|
22
|
+
```text
|
|
23
|
+
yf-npm-search @yourfam
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
The search text is required. Every positional argument is one search text, joined by single spaces:
|
|
27
|
+
|
|
28
|
+
```text
|
|
29
|
+
yf-npm-search merge conflict branches
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
### Console table
|
|
33
|
+
|
|
34
|
+
Six columns, always in this order:
|
|
35
|
+
|
|
36
|
+
`Name Version Published Publisher Developer Total`
|
|
37
|
+
|
|
38
|
+
- **Name** — the package name npm shows. A scoped name is bold; its alias sits on the next row, dim.
|
|
39
|
+
- **Version** — the latest published version.
|
|
40
|
+
- **Published** — the latest publish date, `dd-mmm-yyyy`.
|
|
41
|
+
- **Publisher** — the npm user who published that version.
|
|
42
|
+
- **Developer** — the `author` name from `package.json`.
|
|
43
|
+
- **Total** — download count for the last 18 months (the longest range the npm downloads API returns).
|
|
44
|
+
|
|
45
|
+
Families (a scoped package plus its alias, or a single row) sort by `Total` descending by default. The console prints 25 rows; the Markdown file, when written, contains every fetched row.
|
|
46
|
+
|
|
47
|
+
### Options
|
|
48
|
+
|
|
49
|
+
```text
|
|
50
|
+
--week Add last-week downloads to the Markdown file
|
|
51
|
+
--month Add last-month downloads to the Markdown file
|
|
52
|
+
--maintainers Add maintainer names to the Markdown file
|
|
53
|
+
--description Add the registry description to the Markdown file
|
|
54
|
+
--keywords Add keywords to the Markdown file
|
|
55
|
+
--url Add the https://npm.im/<name> link to the Markdown file
|
|
56
|
+
--sort <sort> Family order: downloads (default), recent, or name
|
|
57
|
+
--limit <n> Print n console rows (default 25)
|
|
58
|
+
--all Print every fetched row
|
|
59
|
+
--raw Do not call the cleanup service
|
|
60
|
+
--md [path] Write a Markdown file; prompt when path is omitted
|
|
61
|
+
--help, -h Print usage and exit
|
|
62
|
+
--version Print the installed version and exit
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Extra columns go to the Markdown file only, after `Total`, in the order above. The console never gains a seventh column.
|
|
66
|
+
|
|
67
|
+
### Markdown file
|
|
68
|
+
|
|
69
|
+
`--md <path>` writes the file without asking and checks the parent directory first. `--md` with no path, or an extra-column flag without `--md <path>`, prompts before any network call. In non-interactive mode the file is skipped and the console table is printed.
|
|
70
|
+
|
|
71
|
+
The suggested file is `yf-npm-search-<dd-mmm-yyyy>.md` on the Desktop (Windows, including an OneDrive-redirected Desktop; `~/Desktop` on macOS and Linux), or in the current directory when the Desktop cannot be resolved.
|
|
72
|
+
|
|
73
|
+
### Search text cleanup
|
|
74
|
+
|
|
75
|
+
A search text with whitespace is a sentence. On a terminal, without `--raw`, the command sends it to the cleanup service and asks you to confirm the cleaned words before calling npm. When the service is unreachable, over its limit, times out, or returns no words, the original text is searched.
|
|
76
|
+
|
|
77
|
+
## Cleanup service
|
|
78
|
+
|
|
79
|
+
The cleanup service is a separate deployment. It calls xAI and injects `XAI_API_KEY` via Doppler; the published package contains no key, Doppler token, or other secret. The command never receives the key.
|
|
80
|
+
|
|
81
|
+
The service URL is a public constant in `src/npm.js`. Set the real public URL there, or override it at runtime with the `YF_NPM_SEARCH_CLEANUP_URL` environment variable.
|
|
82
|
+
|
|
83
|
+
## Development
|
|
84
|
+
|
|
85
|
+
```sh
|
|
86
|
+
npm test
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Tests use Node's built-in test runner and cover argument parsing, formatting, family/sort logic, rendering, and color handling — no network required.
|
|
2
90
|
|
|
3
|
-
This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { main } from '../src/cli.js';
|
|
3
|
+
|
|
4
|
+
main().catch((err) => {
|
|
5
|
+
const message = err && err.message ? err.message : String(err);
|
|
6
|
+
process.stderr.write(message.endsWith('\n') ? message : message + '\n');
|
|
7
|
+
process.exit(err && typeof err.exitCode === 'number' ? err.exitCode : 2);
|
|
8
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,37 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@yourfam/yf-npm-search",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@yourfam/yf-npm-search",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "It reads the npm registry and prints one row per package. Scoped packages and their unscoped aliases are separate rows, listed one after the other. The console is the default. A Markdown file is written only when asked.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"yf-npm-search": "bin/yf-npm-search.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"src",
|
|
12
|
+
"README.md",
|
|
13
|
+
"LICENSE"
|
|
14
|
+
],
|
|
15
|
+
"scripts": {
|
|
16
|
+
"test": "node --test"
|
|
17
|
+
},
|
|
18
|
+
"engines": {
|
|
19
|
+
"node": ">=20"
|
|
20
|
+
},
|
|
21
|
+
"keywords": [
|
|
22
|
+
"npm",
|
|
23
|
+
"search",
|
|
24
|
+
"registry",
|
|
25
|
+
"cli",
|
|
26
|
+
"downloads",
|
|
27
|
+
"markdown"
|
|
28
|
+
],
|
|
29
|
+
"license": "MIT",
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "git+https://github.com/YourFam/yf-npm-search.git"
|
|
36
|
+
}
|
|
37
|
+
}
|
package/src/args.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
const BOOLEAN_FLAGS = new Set([
|
|
2
|
+
'week',
|
|
3
|
+
'month',
|
|
4
|
+
'maintainers',
|
|
5
|
+
'description',
|
|
6
|
+
'keywords',
|
|
7
|
+
'url',
|
|
8
|
+
'all',
|
|
9
|
+
'raw',
|
|
10
|
+
]);
|
|
11
|
+
|
|
12
|
+
const SORTS = new Set(['downloads', 'recent', 'name']);
|
|
13
|
+
|
|
14
|
+
export function parseArgs(argv) {
|
|
15
|
+
const opts = {
|
|
16
|
+
week: false,
|
|
17
|
+
month: false,
|
|
18
|
+
maintainers: false,
|
|
19
|
+
description: false,
|
|
20
|
+
keywords: false,
|
|
21
|
+
url: false,
|
|
22
|
+
all: false,
|
|
23
|
+
raw: false,
|
|
24
|
+
help: false,
|
|
25
|
+
version: false,
|
|
26
|
+
};
|
|
27
|
+
const positional = [];
|
|
28
|
+
let sort = 'downloads';
|
|
29
|
+
let limit = null;
|
|
30
|
+
let mdPath = null;
|
|
31
|
+
let mdFlag = false;
|
|
32
|
+
let error = null;
|
|
33
|
+
|
|
34
|
+
const fail = (message) => {
|
|
35
|
+
if (error === null) error = message;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
for (let i = 0; i < argv.length; i++) {
|
|
39
|
+
const token = argv[i];
|
|
40
|
+
|
|
41
|
+
if (token === '--help' || token === '-h') {
|
|
42
|
+
opts.help = true;
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (token === '--version') {
|
|
46
|
+
opts.version = true;
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (token === '--sort') {
|
|
51
|
+
const value = argv[i + 1];
|
|
52
|
+
if (value === undefined || value.startsWith('-')) {
|
|
53
|
+
fail('--sort requires a value.');
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
i++;
|
|
57
|
+
if (!SORTS.has(value)) {
|
|
58
|
+
fail(`Unknown sort: ${value}.`);
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
sort = value;
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (token === '--limit') {
|
|
66
|
+
const value = argv[i + 1];
|
|
67
|
+
if (value === undefined || value.startsWith('-') || !/^\d+$/.test(value) || Number(value) <= 0) {
|
|
68
|
+
fail('--limit requires a positive integer.');
|
|
69
|
+
if (value !== undefined && !value.startsWith('-')) i++;
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
i++;
|
|
73
|
+
limit = Number(value);
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (token === '--md') {
|
|
78
|
+
mdFlag = true;
|
|
79
|
+
const value = argv[i + 1];
|
|
80
|
+
if (value !== undefined && !value.startsWith('-')) {
|
|
81
|
+
i++;
|
|
82
|
+
mdPath = value;
|
|
83
|
+
} else {
|
|
84
|
+
mdPath = '';
|
|
85
|
+
}
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (BOOLEAN_FLAGS.has(token.slice(2))) {
|
|
90
|
+
opts[token.slice(2)] = true;
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (token.startsWith('-')) {
|
|
95
|
+
fail(`Unknown option: ${token}.`);
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
positional.push(token);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return { positional, opts, sort, limit, mdPath, mdFlag, error };
|
|
103
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { parseArgs } from './args.js';
|
|
4
|
+
import { createColors } from './colors.js';
|
|
5
|
+
import { isTty, ask } from './prompt.js';
|
|
6
|
+
import { suggestedFilePath } from './desktop.js';
|
|
7
|
+
import { version } from './version.js';
|
|
8
|
+
import { CliError } from './errors.js';
|
|
9
|
+
import {
|
|
10
|
+
searchPackages,
|
|
11
|
+
fetchRegistryDoc,
|
|
12
|
+
fetchDownloads,
|
|
13
|
+
eighteenMonthRange,
|
|
14
|
+
callCleanup,
|
|
15
|
+
Pool,
|
|
16
|
+
} from './npm.js';
|
|
17
|
+
import {
|
|
18
|
+
applyRegistryDoc,
|
|
19
|
+
classifyRows,
|
|
20
|
+
buildFamilies,
|
|
21
|
+
sortFamilies,
|
|
22
|
+
takeConsoleRows,
|
|
23
|
+
} from './model.js';
|
|
24
|
+
import { renderTable, renderMarkdown, EXTRA_COLUMN_KEYS } from './render.js';
|
|
25
|
+
|
|
26
|
+
const FOOTNOTE = 'Total = last 18 months (the longest range the npm downloads API returns).';
|
|
27
|
+
|
|
28
|
+
function collectExtraFlags(opts) {
|
|
29
|
+
return EXTRA_COLUMN_KEYS.filter((key) => opts[key]);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function isDirectory(dir) {
|
|
33
|
+
try {
|
|
34
|
+
return fs.statSync(dir).isDirectory();
|
|
35
|
+
} catch {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function promptForPath() {
|
|
41
|
+
while (true) {
|
|
42
|
+
const raw = (await ask('Path: ')).trim();
|
|
43
|
+
if (!raw) return null;
|
|
44
|
+
const resolved = path.resolve(raw);
|
|
45
|
+
const dir = path.dirname(resolved);
|
|
46
|
+
if (isDirectory(dir)) return resolved;
|
|
47
|
+
process.stdout.write(`Error: directory not found: ${dir}.\n`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function markdownPrompt(suggestedPath, extraFlags) {
|
|
52
|
+
const extraNames = extraFlags.map((flag) => `--${flag}`).join(', ');
|
|
53
|
+
while (true) {
|
|
54
|
+
if (extraFlags.length > 0) {
|
|
55
|
+
process.stdout.write('Console shows Name, Version, Published, Publisher, Developer, Total only.\n');
|
|
56
|
+
process.stdout.write(`Extra columns (${extraNames}) go to ${suggestedPath}.\n`);
|
|
57
|
+
}
|
|
58
|
+
const answer = (
|
|
59
|
+
await ask(
|
|
60
|
+
`Write Markdown file to ${suggestedPath}? [Y]es / [P]ath / [N]o (console only) / [E]xit: `,
|
|
61
|
+
)
|
|
62
|
+
)
|
|
63
|
+
.trim()
|
|
64
|
+
.toLowerCase();
|
|
65
|
+
if (answer === 'y') return { write: true, path: suggestedPath };
|
|
66
|
+
if (answer === 'n') return { write: false, path: null };
|
|
67
|
+
if (answer === 'e') process.exit(0);
|
|
68
|
+
if (answer === 'p') {
|
|
69
|
+
const resolvedPath = await promptForPath();
|
|
70
|
+
if (resolvedPath) return { write: true, path: resolvedPath };
|
|
71
|
+
}
|
|
72
|
+
// any other answer repeats the question
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function confirmSearchTerms(cleaned, original) {
|
|
77
|
+
while (true) {
|
|
78
|
+
process.stdout.write(`Search: ${cleaned}\n`);
|
|
79
|
+
const answer = (
|
|
80
|
+
await ask(`Use these terms? [Y]es / [R]aw ("${original}") / [E]xit: `)
|
|
81
|
+
)
|
|
82
|
+
.trim()
|
|
83
|
+
.toLowerCase();
|
|
84
|
+
if (answer === 'y') return cleaned;
|
|
85
|
+
if (answer === 'r') return original;
|
|
86
|
+
if (answer === 'e') process.exit(0);
|
|
87
|
+
// any other answer repeats the question
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function loadRows(packages, writeMd, opts) {
|
|
92
|
+
const pool = new Pool(8);
|
|
93
|
+
const rows = [];
|
|
94
|
+
const tasks = [];
|
|
95
|
+
|
|
96
|
+
for (const pkg of packages) {
|
|
97
|
+
const row = {
|
|
98
|
+
name: pkg.name,
|
|
99
|
+
version: pkg.version ?? '',
|
|
100
|
+
published: pkg.date ?? '',
|
|
101
|
+
description: pkg.description ?? '',
|
|
102
|
+
publisher: '-',
|
|
103
|
+
developer: '-',
|
|
104
|
+
maintainers: [],
|
|
105
|
+
keywords: pkg.keywords ?? [],
|
|
106
|
+
total: 0,
|
|
107
|
+
week: null,
|
|
108
|
+
month: null,
|
|
109
|
+
};
|
|
110
|
+
rows.push(row);
|
|
111
|
+
|
|
112
|
+
tasks.push(
|
|
113
|
+
pool.run(async () => {
|
|
114
|
+
const doc = await fetchRegistryDoc(row.name);
|
|
115
|
+
applyRegistryDoc(row, doc);
|
|
116
|
+
}),
|
|
117
|
+
);
|
|
118
|
+
|
|
119
|
+
tasks.push(
|
|
120
|
+
pool.run(async () => {
|
|
121
|
+
row.total = await fetchDownloads(row.name, eighteenMonthRange());
|
|
122
|
+
}),
|
|
123
|
+
);
|
|
124
|
+
|
|
125
|
+
if (writeMd && opts.week) {
|
|
126
|
+
tasks.push(
|
|
127
|
+
pool.run(async () => {
|
|
128
|
+
row.week = await fetchDownloads(row.name, 'last-week');
|
|
129
|
+
}),
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
if (writeMd && opts.month) {
|
|
133
|
+
tasks.push(
|
|
134
|
+
pool.run(async () => {
|
|
135
|
+
row.month = await fetchDownloads(row.name, 'last-month');
|
|
136
|
+
}),
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
await Promise.all(tasks);
|
|
142
|
+
return rows;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function usage() {
|
|
146
|
+
return `Usage: yf-npm-search <search text> [options]
|
|
147
|
+
|
|
148
|
+
One command. It reads the npm registry and prints one row per package.
|
|
149
|
+
Scoped packages and their unscoped aliases are separate rows.
|
|
150
|
+
|
|
151
|
+
Options:
|
|
152
|
+
--week Add last-week downloads to the Markdown file
|
|
153
|
+
--month Add last-month downloads to the Markdown file
|
|
154
|
+
--maintainers Add maintainer names to the Markdown file
|
|
155
|
+
--description Add the registry description to the Markdown file
|
|
156
|
+
--keywords Add keywords to the Markdown file
|
|
157
|
+
--url Add the https://npm.im/<name> link to the Markdown file
|
|
158
|
+
--sort <sort> Family order: downloads (default), recent, or name
|
|
159
|
+
--limit <n> Print n console rows (default 25)
|
|
160
|
+
--all Print every fetched row
|
|
161
|
+
--raw Do not call the cleanup service
|
|
162
|
+
--md [path] Write a Markdown file; prompt when path is omitted
|
|
163
|
+
--help, -h Print this usage and exit
|
|
164
|
+
--version Print the installed version and exit`;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export async function main(argv = process.argv.slice(2)) {
|
|
168
|
+
const parsed = parseArgs(argv);
|
|
169
|
+
const { opts } = parsed;
|
|
170
|
+
|
|
171
|
+
if (opts.help) {
|
|
172
|
+
process.stdout.write(usage() + '\n');
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
if (opts.version) {
|
|
176
|
+
process.stdout.write(version + '\n');
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
if (parsed.error) {
|
|
180
|
+
throw new CliError(`Error: ${parsed.error}`);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const text = parsed.positional.join(' ');
|
|
184
|
+
if (!text) {
|
|
185
|
+
throw new CliError('Error: a search text is required.');
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const extraFlags = collectExtraFlags(opts);
|
|
189
|
+
const interactive = isTty(process.stdin) && isTty(process.stdout);
|
|
190
|
+
|
|
191
|
+
// Decide the Markdown target before any network call.
|
|
192
|
+
let mdPath = null;
|
|
193
|
+
let writeMd = false;
|
|
194
|
+
|
|
195
|
+
if (parsed.mdPath) {
|
|
196
|
+
const dir = path.dirname(path.resolve(parsed.mdPath));
|
|
197
|
+
if (!isDirectory(dir)) {
|
|
198
|
+
throw new CliError(`Error: directory not found: ${dir}.`);
|
|
199
|
+
}
|
|
200
|
+
mdPath = parsed.mdPath;
|
|
201
|
+
writeMd = true;
|
|
202
|
+
} else if (parsed.mdFlag || extraFlags.length > 0) {
|
|
203
|
+
if (interactive) {
|
|
204
|
+
const result = await markdownPrompt(suggestedFilePath(), extraFlags);
|
|
205
|
+
writeMd = result.write;
|
|
206
|
+
mdPath = result.write ? result.path : null;
|
|
207
|
+
} else {
|
|
208
|
+
if (extraFlags.length > 0) {
|
|
209
|
+
process.stderr.write('Note: extra columns require --md <path> in non-interactive mode.\n');
|
|
210
|
+
}
|
|
211
|
+
writeMd = false;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Clean up the search text (a sentence with whitespace) before calling npm.
|
|
216
|
+
let searchText = text;
|
|
217
|
+
if (/\s/.test(text) && !opts.raw && interactive) {
|
|
218
|
+
const cleaned = await callCleanup(text);
|
|
219
|
+
if (cleaned) {
|
|
220
|
+
searchText = await confirmSearchTerms(cleaned, text);
|
|
221
|
+
} else {
|
|
222
|
+
process.stdout.write(`Search: ${text}\n`);
|
|
223
|
+
searchText = text;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Load every row before printing anything.
|
|
228
|
+
const { packages, total } = await searchPackages(searchText);
|
|
229
|
+
const rows = await loadRows(packages, writeMd, opts);
|
|
230
|
+
classifyRows(rows);
|
|
231
|
+
const families = sortFamilies(buildFamilies(rows), parsed.sort);
|
|
232
|
+
const orderedRows = families.flatMap((family) => family.rows);
|
|
233
|
+
|
|
234
|
+
const limit = opts.all ? orderedRows.length : (parsed.limit ?? 25);
|
|
235
|
+
const consoleRows = takeConsoleRows(families, limit);
|
|
236
|
+
|
|
237
|
+
const colors = createColors(isTty(process.stdout) && !process.env.NO_COLOR);
|
|
238
|
+
|
|
239
|
+
// Write the Markdown file before printing the console table.
|
|
240
|
+
if (writeMd) {
|
|
241
|
+
const markdownLines = [renderMarkdown(orderedRows, extraFlags), '', FOOTNOTE];
|
|
242
|
+
if (total > orderedRows.length) {
|
|
243
|
+
markdownLines.push(`Showing ${orderedRows.length} of ${total}.`);
|
|
244
|
+
}
|
|
245
|
+
fs.writeFileSync(mdPath, markdownLines.join('\n') + '\n');
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const lines = [];
|
|
249
|
+
lines.push(renderTable(consoleRows, colors));
|
|
250
|
+
lines.push('');
|
|
251
|
+
lines.push(colors.dim(FOOTNOTE));
|
|
252
|
+
|
|
253
|
+
if (consoleRows.length < orderedRows.length) {
|
|
254
|
+
const truncation = writeMd
|
|
255
|
+
? `Showing ${consoleRows.length} of ${orderedRows.length} rows in console (all ${orderedRows.length} written to ${mdPath}). Pass --all for full console output.`
|
|
256
|
+
: `Showing ${consoleRows.length} of ${orderedRows.length} rows. Pass --all for all rows, or --md to export.`;
|
|
257
|
+
lines.push(colors.dim(truncation));
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
if (total > orderedRows.length) {
|
|
261
|
+
lines.push(colors.dim(`Showing ${orderedRows.length} of ${total}.`));
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
process.stdout.write(lines.join('\n') + '\n');
|
|
265
|
+
}
|
|
266
|
+
|
package/src/colors.js
ADDED
package/src/desktop.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import os from 'node:os';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import { execFileSync } from 'node:child_process';
|
|
5
|
+
import { formatLocalDate } from './format.js';
|
|
6
|
+
|
|
7
|
+
function expandEnvVars(value) {
|
|
8
|
+
return value.replace(/%([^%]+)%/g, (_, name) => process.env[name] ?? `%${name}%`);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function windowsDesktopCandidates() {
|
|
12
|
+
const candidates = [];
|
|
13
|
+
try {
|
|
14
|
+
const output = execFileSync(
|
|
15
|
+
'reg',
|
|
16
|
+
[
|
|
17
|
+
'query',
|
|
18
|
+
'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders',
|
|
19
|
+
'/v',
|
|
20
|
+
'Desktop',
|
|
21
|
+
],
|
|
22
|
+
{ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] },
|
|
23
|
+
);
|
|
24
|
+
const match = output.match(/Desktop\s+REG_(?:EXPAND_)?SZ\s+(.+)/i);
|
|
25
|
+
if (match) candidates.push(expandEnvVars(match[1].trim()));
|
|
26
|
+
} catch {
|
|
27
|
+
// registry lookup is best-effort
|
|
28
|
+
}
|
|
29
|
+
if (process.env.USERPROFILE) candidates.push(path.join(process.env.USERPROFILE, 'Desktop'));
|
|
30
|
+
if (process.env.OneDrive) candidates.push(path.join(process.env.OneDrive, 'Desktop'));
|
|
31
|
+
if (process.env.OneDriveConsumer) {
|
|
32
|
+
candidates.push(path.join(process.env.OneDriveConsumer, 'Desktop'));
|
|
33
|
+
}
|
|
34
|
+
return candidates;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function desktopDirectory() {
|
|
38
|
+
let candidates;
|
|
39
|
+
if (process.platform === 'win32') {
|
|
40
|
+
candidates = windowsDesktopCandidates();
|
|
41
|
+
} else {
|
|
42
|
+
candidates = [path.join(os.homedir(), 'Desktop')];
|
|
43
|
+
}
|
|
44
|
+
for (const candidate of candidates) {
|
|
45
|
+
if (!candidate) continue;
|
|
46
|
+
try {
|
|
47
|
+
if (fs.existsSync(candidate) && fs.statSync(candidate).isDirectory()) return candidate;
|
|
48
|
+
} catch {
|
|
49
|
+
// keep looking
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function suggestedFilePath() {
|
|
56
|
+
const base = `yf-npm-search-${formatLocalDate()}.md`;
|
|
57
|
+
const dir = desktopDirectory();
|
|
58
|
+
return dir ? path.join(dir, base) : path.join(process.cwd(), base);
|
|
59
|
+
}
|
package/src/errors.js
ADDED
package/src/format.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export const MONTHS = [
|
|
2
|
+
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
|
|
3
|
+
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
|
|
4
|
+
];
|
|
5
|
+
|
|
6
|
+
function pad2(n) {
|
|
7
|
+
return String(n).padStart(2, '0');
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function formatDate(iso) {
|
|
11
|
+
if (!iso) return '-';
|
|
12
|
+
const date = new Date(iso);
|
|
13
|
+
if (Number.isNaN(date.getTime())) return '-';
|
|
14
|
+
return `${pad2(date.getUTCDate())}-${MONTHS[date.getUTCMonth()]}-${date.getUTCFullYear()}`;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function formatLocalDate(date = new Date()) {
|
|
18
|
+
return `${pad2(date.getDate())}-${MONTHS[date.getMonth()]}-${date.getFullYear()}`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function developerName(author) {
|
|
22
|
+
if (author == null) return '-';
|
|
23
|
+
if (typeof author === 'object') {
|
|
24
|
+
if (typeof author.name === 'string' && author.name.trim()) return author.name.trim();
|
|
25
|
+
return '-';
|
|
26
|
+
}
|
|
27
|
+
const text = String(author);
|
|
28
|
+
const index = text.search(/[<(]/);
|
|
29
|
+
const name = (index === -1 ? text : text.slice(0, index)).trim();
|
|
30
|
+
return name || '-';
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function sanitizeCell(value) {
|
|
34
|
+
return String(value).replace(/[\r\n]+/g, ' ').replace(/\|/g, '\\|');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function detectAlias(description) {
|
|
38
|
+
if (!description) return null;
|
|
39
|
+
const match = String(description).match(/Unscoped alias of\s+(@\S+)/);
|
|
40
|
+
return match ? match[1] : null;
|
|
41
|
+
}
|
package/src/model.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { detectAlias, developerName } from './format.js';
|
|
2
|
+
|
|
3
|
+
export function applyRegistryDoc(row, doc) {
|
|
4
|
+
const latest = doc && doc['dist-tags'] && doc['dist-tags'].latest
|
|
5
|
+
? doc['dist-tags'].latest
|
|
6
|
+
: row.version;
|
|
7
|
+
const versionData = doc && doc.versions && doc.versions[latest] ? doc.versions[latest] : {};
|
|
8
|
+
|
|
9
|
+
row.version = latest || row.version;
|
|
10
|
+
row.published = (doc && doc.time && doc.time[latest]) || row.published;
|
|
11
|
+
row.description = versionData.description ?? doc?.description ?? row.description ?? '';
|
|
12
|
+
|
|
13
|
+
const publisher =
|
|
14
|
+
versionData._npmUser?.name ??
|
|
15
|
+
versionData.maintainers?.[0]?.name ??
|
|
16
|
+
doc?.maintainers?.[0]?.name ??
|
|
17
|
+
'';
|
|
18
|
+
row.publisher = publisher || '-';
|
|
19
|
+
|
|
20
|
+
const author = versionData.author ?? doc?.author ?? null;
|
|
21
|
+
row.developer = developerName(author);
|
|
22
|
+
|
|
23
|
+
const maintainers = versionData.maintainers ?? doc?.maintainers ?? [];
|
|
24
|
+
row.maintainers = Array.isArray(maintainers)
|
|
25
|
+
? maintainers.map((m) => m?.name ?? m?.username ?? '').filter(Boolean)
|
|
26
|
+
: [];
|
|
27
|
+
|
|
28
|
+
const keywords = versionData.keywords ?? doc?.keywords ?? row.keywords ?? [];
|
|
29
|
+
row.keywords = Array.isArray(keywords) ? keywords.map(String) : [];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function classifyRows(rows) {
|
|
33
|
+
for (const row of rows) {
|
|
34
|
+
row.isScoped = row.name.startsWith('@');
|
|
35
|
+
row.aliasOf = row.isScoped ? null : detectAlias(row.description);
|
|
36
|
+
row.isAlias = !row.isScoped && row.aliasOf !== null;
|
|
37
|
+
}
|
|
38
|
+
const scopedNames = new Set(rows.filter((r) => r.isScoped).map((r) => r.name));
|
|
39
|
+
for (const row of rows) {
|
|
40
|
+
row.isLoneAlias = row.isAlias && !scopedNames.has(row.aliasOf);
|
|
41
|
+
}
|
|
42
|
+
return rows;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function buildFamilies(rows) {
|
|
46
|
+
const families = [];
|
|
47
|
+
const consumed = new Set();
|
|
48
|
+
|
|
49
|
+
for (const row of rows) {
|
|
50
|
+
if (consumed.has(row.name)) continue;
|
|
51
|
+
|
|
52
|
+
if (row.isScoped) {
|
|
53
|
+
const alias = rows.find((r) => r.isAlias && r.aliasOf === row.name && !r.isLoneAlias);
|
|
54
|
+
const familyRows = [row];
|
|
55
|
+
if (alias) {
|
|
56
|
+
familyRows.push(alias);
|
|
57
|
+
consumed.add(alias.name);
|
|
58
|
+
}
|
|
59
|
+
consumed.add(row.name);
|
|
60
|
+
families.push(makeFamily(familyRows));
|
|
61
|
+
} else if (row.isAlias && !row.isLoneAlias) {
|
|
62
|
+
continue; // handled with its scoped parent
|
|
63
|
+
} else {
|
|
64
|
+
consumed.add(row.name);
|
|
65
|
+
families.push(makeFamily([row]));
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
return families;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function makeFamily(familyRows) {
|
|
73
|
+
let dateMs = 0;
|
|
74
|
+
for (const row of familyRows) {
|
|
75
|
+
const time = Date.parse(row.published);
|
|
76
|
+
if (!Number.isNaN(time) && time > dateMs) dateMs = time;
|
|
77
|
+
}
|
|
78
|
+
return {
|
|
79
|
+
name: familyRows[0].name,
|
|
80
|
+
total: familyRows[0].total,
|
|
81
|
+
dateMs,
|
|
82
|
+
rows: familyRows,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function compareName(a, b) {
|
|
87
|
+
return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function sortFamilies(families, sort) {
|
|
91
|
+
families.sort((a, b) => {
|
|
92
|
+
if (sort === 'name') return compareName(a, b);
|
|
93
|
+
if (sort === 'recent') {
|
|
94
|
+
if (a.dateMs !== b.dateMs) return b.dateMs - a.dateMs;
|
|
95
|
+
return compareName(a, b);
|
|
96
|
+
}
|
|
97
|
+
if (a.total !== b.total) return b.total - a.total;
|
|
98
|
+
return compareName(a, b);
|
|
99
|
+
});
|
|
100
|
+
return families;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function takeConsoleRows(families, limit) {
|
|
104
|
+
const rows = [];
|
|
105
|
+
for (const family of families) {
|
|
106
|
+
if (rows.length >= limit) break;
|
|
107
|
+
rows.push(...family.rows);
|
|
108
|
+
}
|
|
109
|
+
return rows;
|
|
110
|
+
}
|
package/src/npm.js
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { CliError } from './errors.js';
|
|
2
|
+
|
|
3
|
+
const SEARCH_BASE = 'https://registry.npmjs.org/-/v1/search';
|
|
4
|
+
const REGISTRY_BASE = 'https://registry.npmjs.org';
|
|
5
|
+
const DOWNLOADS_BASE = 'https://api.npmjs.org/downloads/point';
|
|
6
|
+
|
|
7
|
+
// Public cleanup service URL. The service is deployed separately (it injects
|
|
8
|
+
// XAI_API_KEY via Doppler; this package never receives that key). Replace this
|
|
9
|
+
// placeholder with the real public URL, or override it with
|
|
10
|
+
// YF_NPM_SEARCH_CLEANUP_URL at runtime.
|
|
11
|
+
export const CLEANUP_SERVICE_URL =
|
|
12
|
+
process.env.YF_NPM_SEARCH_CLEANUP_URL || 'https://cleanup.yourfam.co/yf-npm-search';
|
|
13
|
+
|
|
14
|
+
function encodePackage(name) {
|
|
15
|
+
return name.includes('/') ? name.replace('/', '%2F') : name;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function sleep(ms) {
|
|
19
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// The npm downloads API (api.npmjs.org) enforces a burst limit that recovers
|
|
23
|
+
// in about one second. Pacing download requests keeps the run under that
|
|
24
|
+
// limit while still honoring the "at most 8 concurrent requests" rule.
|
|
25
|
+
class RateLimiter {
|
|
26
|
+
constructor(minIntervalMs) {
|
|
27
|
+
this.minIntervalMs = minIntervalMs;
|
|
28
|
+
this.next = 0;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async acquire() {
|
|
32
|
+
const now = Date.now();
|
|
33
|
+
if (now < this.next) {
|
|
34
|
+
await sleep(this.next - now);
|
|
35
|
+
}
|
|
36
|
+
this.next = Date.now() + this.minIntervalMs;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const downloadsLimiter = new RateLimiter(200);
|
|
41
|
+
|
|
42
|
+
async function fetchJson(url, what, { notFoundIsEmpty = false } = {}) {
|
|
43
|
+
for (let attempt = 0; ; attempt++) {
|
|
44
|
+
const controller = new AbortController();
|
|
45
|
+
const timer = setTimeout(() => controller.abort(), 30000);
|
|
46
|
+
let res;
|
|
47
|
+
try {
|
|
48
|
+
res = await fetch(url, { signal: controller.signal, headers: { accept: 'application/json' } });
|
|
49
|
+
} catch {
|
|
50
|
+
clearTimeout(timer);
|
|
51
|
+
throw new CliError(`Error: ${what} failed.`);
|
|
52
|
+
}
|
|
53
|
+
clearTimeout(timer);
|
|
54
|
+
|
|
55
|
+
if (res.status === 429 && attempt < 3) {
|
|
56
|
+
const retryAfter = res.headers.get('retry-after');
|
|
57
|
+
const parsed = Number(retryAfter);
|
|
58
|
+
let waitMs = Number.isFinite(parsed) && parsed > 0
|
|
59
|
+
? parsed * 1000
|
|
60
|
+
: 1000 * Math.pow(2, attempt);
|
|
61
|
+
waitMs += Math.floor(Math.random() * 1000);
|
|
62
|
+
await sleep(waitMs);
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
if (notFoundIsEmpty && res.status === 404) {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
if (!res.ok) {
|
|
69
|
+
throw new CliError(`Error: ${what} failed.`);
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
return await res.json();
|
|
73
|
+
} catch {
|
|
74
|
+
throw new CliError(`Error: ${what} failed.`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export async function searchPackages(text) {
|
|
80
|
+
const packages = [];
|
|
81
|
+
let total = 0;
|
|
82
|
+
let from = 0;
|
|
83
|
+
let first = true;
|
|
84
|
+
|
|
85
|
+
while (packages.length < 1000) {
|
|
86
|
+
const url = `${SEARCH_BASE}?text=${encodeURIComponent(text)}&size=250&from=${from}`;
|
|
87
|
+
const data = await fetchJson(url, 'the search request');
|
|
88
|
+
if (first) {
|
|
89
|
+
total = data && typeof data.total === 'number' ? data.total : 0;
|
|
90
|
+
first = false;
|
|
91
|
+
}
|
|
92
|
+
const objects = data && Array.isArray(data.objects) ? data.objects : [];
|
|
93
|
+
for (const object of objects) {
|
|
94
|
+
if (object && object.package) packages.push(object.package);
|
|
95
|
+
if (packages.length >= 1000) break;
|
|
96
|
+
}
|
|
97
|
+
if (objects.length < 250) break;
|
|
98
|
+
from += 250;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return { packages, total };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export async function fetchRegistryDoc(name) {
|
|
105
|
+
const url = `${REGISTRY_BASE}/${encodePackage(name)}`;
|
|
106
|
+
return fetchJson(url, `the registry request for ${name}`);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function twoDigit(n) {
|
|
110
|
+
return String(n).padStart(2, '0');
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function toDateString(date) {
|
|
114
|
+
return `${date.getUTCFullYear()}-${twoDigit(date.getUTCMonth() + 1)}-${twoDigit(date.getUTCDate())}`;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function eighteenMonthRange() {
|
|
118
|
+
const end = new Date();
|
|
119
|
+
const start = new Date(end);
|
|
120
|
+
start.setUTCMonth(start.getUTCMonth() - 18);
|
|
121
|
+
return `${toDateString(start)}:${toDateString(end)}`;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export async function fetchDownloads(name, period) {
|
|
125
|
+
await downloadsLimiter.acquire();
|
|
126
|
+
const url = `${DOWNLOADS_BASE}/${period}/${encodePackage(name)}`;
|
|
127
|
+
const data = await fetchJson(url, `the downloads request for ${name}`, { notFoundIsEmpty: true });
|
|
128
|
+
return data && typeof data.downloads === 'number' ? data.downloads : 0;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export async function callCleanup(text) {
|
|
132
|
+
const controller = new AbortController();
|
|
133
|
+
const timer = setTimeout(() => controller.abort(), 4000);
|
|
134
|
+
try {
|
|
135
|
+
const res = await fetch(CLEANUP_SERVICE_URL, {
|
|
136
|
+
method: 'POST',
|
|
137
|
+
headers: { 'content-type': 'application/json' },
|
|
138
|
+
body: JSON.stringify({ text }),
|
|
139
|
+
signal: controller.signal,
|
|
140
|
+
});
|
|
141
|
+
if (!res.ok) return null;
|
|
142
|
+
const words = (await res.text()).trim();
|
|
143
|
+
return words || null;
|
|
144
|
+
} catch {
|
|
145
|
+
return null;
|
|
146
|
+
} finally {
|
|
147
|
+
clearTimeout(timer);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export class Pool {
|
|
152
|
+
constructor(limit) {
|
|
153
|
+
this.limit = limit;
|
|
154
|
+
this.active = 0;
|
|
155
|
+
this.queue = [];
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
run(fn) {
|
|
159
|
+
return new Promise((resolve, reject) => {
|
|
160
|
+
const task = async () => {
|
|
161
|
+
try {
|
|
162
|
+
resolve(await fn());
|
|
163
|
+
} catch (error) {
|
|
164
|
+
reject(error);
|
|
165
|
+
} finally {
|
|
166
|
+
this.active--;
|
|
167
|
+
this._next();
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
this.queue.push(task);
|
|
171
|
+
this._next();
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
_next() {
|
|
176
|
+
while (this.active < this.limit && this.queue.length) {
|
|
177
|
+
this.active++;
|
|
178
|
+
const task = this.queue.shift();
|
|
179
|
+
task();
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
package/src/prompt.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import readline from 'node:readline';
|
|
2
|
+
|
|
3
|
+
export function isTty(stream) {
|
|
4
|
+
return Boolean(stream && stream.isTTY);
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function ask(question) {
|
|
8
|
+
return new Promise((resolve) => {
|
|
9
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
10
|
+
|
|
11
|
+
const finish = () => {
|
|
12
|
+
try {
|
|
13
|
+
rl.close();
|
|
14
|
+
} catch {
|
|
15
|
+
// ignore
|
|
16
|
+
}
|
|
17
|
+
process.exit(0);
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
const onSigint = () => finish();
|
|
21
|
+
const onSigtstp = () => finish();
|
|
22
|
+
|
|
23
|
+
process.once('SIGINT', onSigint);
|
|
24
|
+
process.once('SIGTSTP', onSigtstp);
|
|
25
|
+
rl.once('close', finish);
|
|
26
|
+
|
|
27
|
+
rl.question(question, (answer) => {
|
|
28
|
+
process.removeListener('SIGINT', onSigint);
|
|
29
|
+
process.removeListener('SIGTSTP', onSigtstp);
|
|
30
|
+
rl.removeListener('close', finish);
|
|
31
|
+
rl.close();
|
|
32
|
+
resolve(answer);
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
}
|
package/src/render.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { formatDate, sanitizeCell } from './format.js';
|
|
2
|
+
|
|
3
|
+
const COLS = [
|
|
4
|
+
{ key: 'name', header: 'Name', align: 'left' },
|
|
5
|
+
{ key: 'version', header: 'Version', align: 'left' },
|
|
6
|
+
{ key: 'published', header: 'Published', align: 'left' },
|
|
7
|
+
{ key: 'publisher', header: 'Publisher', align: 'left' },
|
|
8
|
+
{ key: 'developer', header: 'Developer', align: 'left' },
|
|
9
|
+
{ key: 'total', header: 'Total', align: 'right' },
|
|
10
|
+
];
|
|
11
|
+
|
|
12
|
+
export const EXTRA_COLUMN_KEYS = ['week', 'month', 'maintainers', 'description', 'keywords', 'url'];
|
|
13
|
+
|
|
14
|
+
const EXTRA_COLS = [
|
|
15
|
+
{ key: 'week', header: 'Week' },
|
|
16
|
+
{ key: 'month', header: 'Month' },
|
|
17
|
+
{ key: 'maintainers', header: 'Maintainers' },
|
|
18
|
+
{ key: 'description', header: 'Description' },
|
|
19
|
+
{ key: 'keywords', header: 'Keywords' },
|
|
20
|
+
{ key: 'url', header: 'URL' },
|
|
21
|
+
];
|
|
22
|
+
|
|
23
|
+
function namePlain(row) {
|
|
24
|
+
return row.isLoneAlias ? `${row.name} alias` : row.name;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function nameColored(row, colors) {
|
|
28
|
+
if (row.isScoped) return colors.bold(row.name);
|
|
29
|
+
if (row.isAlias) {
|
|
30
|
+
const base = colors.dim(row.name);
|
|
31
|
+
return row.isLoneAlias ? `${base} ${colors.dim('alias')}` : base;
|
|
32
|
+
}
|
|
33
|
+
return row.name;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function displayRow(row, colors) {
|
|
37
|
+
const published = formatDate(row.published);
|
|
38
|
+
return {
|
|
39
|
+
namePlain: namePlain(row),
|
|
40
|
+
nameColored: nameColored(row, colors),
|
|
41
|
+
versionPlain: row.version,
|
|
42
|
+
versionColored: colors.green(row.version),
|
|
43
|
+
publishedPlain: published,
|
|
44
|
+
publishedColored: published,
|
|
45
|
+
publisherPlain: row.publisher,
|
|
46
|
+
publisherColored: row.publisher,
|
|
47
|
+
developerPlain: row.developer,
|
|
48
|
+
developerColored: row.developer,
|
|
49
|
+
totalPlain: String(row.total),
|
|
50
|
+
totalColored: colors.bold(String(row.total)),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function renderTable(rows, colors) {
|
|
55
|
+
const displays = rows.map((row) => displayRow(row, colors));
|
|
56
|
+
|
|
57
|
+
const widths = COLS.map((col) => {
|
|
58
|
+
let width = col.header.length;
|
|
59
|
+
for (const display of displays) {
|
|
60
|
+
const value = display[`${col.key}Plain`];
|
|
61
|
+
if (value.length > width) width = value.length;
|
|
62
|
+
}
|
|
63
|
+
return width;
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
const totalWidth = widths.reduce((sum, width) => sum + width, 0) + 2 * (COLS.length - 1);
|
|
67
|
+
|
|
68
|
+
const pad = (colored, plain, width, align) => {
|
|
69
|
+
const gap = width - plain.length;
|
|
70
|
+
return align === 'right' ? ' '.repeat(gap) + colored : colored + ' '.repeat(gap);
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const rule = colors.dim('-'.repeat(totalWidth));
|
|
74
|
+
const headerCells = COLS.map((col, i) =>
|
|
75
|
+
pad(colors.dim(col.header), col.header, widths[i], col.align),
|
|
76
|
+
);
|
|
77
|
+
|
|
78
|
+
const lines = [rule, headerCells.join(' '), rule];
|
|
79
|
+
for (const display of displays) {
|
|
80
|
+
const cells = COLS.map((col, i) =>
|
|
81
|
+
pad(display[`${col.key}Colored`], display[`${col.key}Plain`], widths[i], col.align),
|
|
82
|
+
);
|
|
83
|
+
lines.push(cells.join(' '));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return lines.join('\n');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function extraValue(row, key) {
|
|
90
|
+
switch (key) {
|
|
91
|
+
case 'week':
|
|
92
|
+
return row.week == null ? '0' : String(row.week);
|
|
93
|
+
case 'month':
|
|
94
|
+
return row.month == null ? '0' : String(row.month);
|
|
95
|
+
case 'maintainers':
|
|
96
|
+
return (row.maintainers ?? []).join(', ');
|
|
97
|
+
case 'description':
|
|
98
|
+
return row.description ?? '';
|
|
99
|
+
case 'keywords':
|
|
100
|
+
return (row.keywords ?? []).join(', ');
|
|
101
|
+
case 'url':
|
|
102
|
+
return `https://npm.im/${row.name}`;
|
|
103
|
+
default:
|
|
104
|
+
return '';
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function renderMarkdown(rows, extraFlags) {
|
|
109
|
+
const activeExtra = EXTRA_COLS.filter((col) => extraFlags.includes(col.key));
|
|
110
|
+
const headers = [...COLS.map((col) => col.header), ...activeExtra.map((col) => col.header)];
|
|
111
|
+
const line = (cells) => `| ${cells.join(' | ')} |`;
|
|
112
|
+
|
|
113
|
+
const out = [];
|
|
114
|
+
out.push(line(headers));
|
|
115
|
+
out.push(line(headers.map(() => '---')));
|
|
116
|
+
|
|
117
|
+
for (const row of rows) {
|
|
118
|
+
const baseCells = [
|
|
119
|
+
sanitizeCell(row.name),
|
|
120
|
+
sanitizeCell(row.version),
|
|
121
|
+
sanitizeCell(formatDate(row.published)),
|
|
122
|
+
sanitizeCell(row.publisher),
|
|
123
|
+
sanitizeCell(row.developer),
|
|
124
|
+
sanitizeCell(String(row.total)),
|
|
125
|
+
];
|
|
126
|
+
const extraCells = activeExtra.map((col) => sanitizeCell(extraValue(row, col.key)));
|
|
127
|
+
out.push(line([...baseCells, ...extraCells]));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
return out.join('\n');
|
|
131
|
+
}
|