promptlike 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +270 -28
  3. package/dist/commands/config.js +13 -0
  4. package/dist/commands/copy.js +22 -7
  5. package/dist/commands/get.js +17 -3
  6. package/dist/commands/import.js +30 -128
  7. package/dist/commands/importCheck.js +304 -0
  8. package/dist/commands/importGithub.js +171 -0
  9. package/dist/commands/list.js +83 -17
  10. package/dist/commands/local.js +35 -12
  11. package/dist/commands/login.js +6 -5
  12. package/dist/commands/search.js +73 -7
  13. package/dist/commands/show.js +11 -3
  14. package/dist/commands/sync.js +57 -13
  15. package/dist/commands/tag.js +86 -0
  16. package/dist/help.js +1 -1
  17. package/dist/index.js +7 -0
  18. package/dist/lib/api-client.js +39 -0
  19. package/dist/lib/errors.js +4 -0
  20. package/dist/lib/format.js +28 -0
  21. package/dist/lib/frontmatter.js +86 -4
  22. package/dist/lib/github.js +208 -0
  23. package/dist/lib/githubCache.js +118 -0
  24. package/dist/lib/githubHttp.js +197 -0
  25. package/dist/lib/githubImport.js +238 -0
  26. package/dist/lib/githubSelect.js +148 -0
  27. package/dist/lib/githubSnapshot.js +67 -0
  28. package/dist/lib/githubSpec.js +78 -0
  29. package/dist/lib/importOrigins.js +36 -0
  30. package/dist/lib/importShared.js +179 -0
  31. package/dist/lib/licenses.js +243 -0
  32. package/dist/lib/localStore.js +52 -10
  33. package/dist/lib/loopApi.js +63 -11
  34. package/dist/lib/promptResolver.js +22 -9
  35. package/dist/lib/promptSource.js +123 -0
  36. package/dist/lib/promptTemplate.js +189 -0
  37. package/dist/lib/promptVariables.js +7 -40
  38. package/dist/lib/rank.js +30 -13
  39. package/dist/lib/settings.js +24 -3
  40. package/dist/lib/tagFilter.js +40 -0
  41. package/dist/lib/updateCheck.js +296 -0
  42. package/dist/lib/upstreamCheck.js +71 -0
  43. package/dist/program.js +41 -10
  44. package/package.json +1 -1
@@ -0,0 +1,208 @@
1
+ "use strict";
2
+ /**
3
+ * Read-only GitHub client for `ple import github:…` — PUBLIC repositories only,
4
+ * no token. Four calls, an import costs at most three of the counted ones
5
+ * (repo, commit, tree) plus raw downloads; the Contents API is never used:
6
+ *
7
+ * getRepo repo → {fullName, defaultBranch, license}
8
+ * resolveCommit ref → 40-hex commit
9
+ * getTree commit → every file (refuses a truncated list)
10
+ * fetchRaw file at a commit → text (≤ 64 KB, no binary)
11
+ *
12
+ * Every URL is built from validated parts with each path segment encoded. The
13
+ * HTTP rules (hosts, headers, redirects, errors) live in ./githubHttp.ts, the
14
+ * on-disk cache in ./githubCache.ts.
15
+ */
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.TOO_LARGE_REPO = exports.REPO_RE = exports.OWNER_RE = exports.GithubError = exports.GITHUB_RAW = exports.GITHUB_API = exports.CACHE_TTL_MS = void 0;
18
+ exports.blobUrl = blobUrl;
19
+ exports.resetGithubRunState = resetGithubRunState;
20
+ exports.getRepo = getRepo;
21
+ exports.resolveCommit = resolveCommit;
22
+ exports.getTree = getTree;
23
+ exports.fetchRaw = fetchRaw;
24
+ exports.rememberRaw = rememberRaw;
25
+ const githubCache_1 = require("./githubCache");
26
+ Object.defineProperty(exports, "CACHE_TTL_MS", { enumerable: true, get: function () { return githubCache_1.CACHE_TTL_MS; } });
27
+ const githubHttp_1 = require("./githubHttp");
28
+ Object.defineProperty(exports, "GITHUB_API", { enumerable: true, get: function () { return githubHttp_1.GITHUB_API; } });
29
+ Object.defineProperty(exports, "GITHUB_RAW", { enumerable: true, get: function () { return githubHttp_1.GITHUB_RAW; } });
30
+ Object.defineProperty(exports, "GithubError", { enumerable: true, get: function () { return githubHttp_1.GithubError; } });
31
+ const format_1 = require("./format");
32
+ const secretGuard_1 = require("./secretGuard");
33
+ const MAX_TREE_BYTES = 8 * 1024 * 1024;
34
+ const MAX_JSON_BYTES = 1024 * 1024;
35
+ exports.OWNER_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
36
+ exports.REPO_RE = /^[A-Za-z0-9._-]{1,100}$/;
37
+ const SHA_RE = /^[0-9a-f]{40}$/;
38
+ exports.TOO_LARGE_REPO = 'This repository is too large to list in one request; try a smaller repository or open an issue.';
39
+ const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
40
+ function assertRepo(owner, repo) {
41
+ if (!exports.OWNER_RE.test(owner) || !exports.REPO_RE.test(repo) || repo === '.' || repo === '..') {
42
+ throw new githubHttp_1.GithubError('Use github:<owner>/<repo>[/path][@ref], e.g. github:anthropics/skills/skills/pdf');
43
+ }
44
+ }
45
+ const encodePath = (p) => p.split('/').map(encodeURIComponent).join('/');
46
+ /** Permalink to a file at a commit on github.com (every path segment encoded). */
47
+ function blobUrl(repo, commit, filePath) {
48
+ return `https://github.com/${repo}/blob/${commit}/${encodePath(filePath)}`;
49
+ }
50
+ /** A path from a tree: no empty, `.` or `..` segment (it is only ever placed into a URL). */
51
+ function assertSafePath(p) {
52
+ if (!p || p.split('/').some((s) => s === '' || s === '.' || s === '..')) {
53
+ throw new githubHttp_1.GithubError(`Not a file path GitHub can serve: ${(0, format_1.safeText)(p)}`);
54
+ }
55
+ }
56
+ /** Tests only: forget the once-per-run state (rate-limit warning, cache pruning). */
57
+ function resetGithubRunState() {
58
+ (0, githubHttp_1.resetHttpState)();
59
+ (0, githubCache_1.resetCacheState)();
60
+ }
61
+ const repoKey = (owner, repo) => `${owner}/${repo}`.toLowerCase();
62
+ // ---------------------------------------------------------------------------
63
+ // Public calls
64
+ // ---------------------------------------------------------------------------
65
+ const isRepoInfo = (d) => isObject(d) &&
66
+ typeof d.fullName === 'string' &&
67
+ typeof d.defaultBranch === 'string' &&
68
+ (d.licenseSpdx === null || typeof d.licenseSpdx === 'string');
69
+ /** GET /repos/{owner}/{repo} */
70
+ async function getRepo(owner, repo) {
71
+ assertRepo(owner, repo);
72
+ const key = `repo:${repoKey(owner, repo)}`;
73
+ const hit = (0, githubCache_1.cacheGet)(key, githubCache_1.CACHE_TTL_MS, isRepoInfo);
74
+ if (hit)
75
+ return hit;
76
+ const label = `github.com/${owner}/${repo}`;
77
+ const body = (0, githubHttp_1.parseJson)(await (0, githubHttp_1.request)({
78
+ url: `${githubHttp_1.GITHUB_API}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`,
79
+ accept: 'application/vnd.github+json',
80
+ api: true,
81
+ maxBytes: MAX_JSON_BYTES,
82
+ what: `repo info for ${label}`,
83
+ missing: { statuses: [404], message: `Not found: ${label}. Only public repositories can be imported.` },
84
+ tooLarge: new githubHttp_1.GithubError(`GitHub sent too much data for ${label}.`),
85
+ }), `repo info for ${label}`);
86
+ if (!isObject(body) || typeof body.full_name !== 'string' || typeof body.default_branch !== 'string' || !body.default_branch) {
87
+ throw new githubHttp_1.GithubError(`GitHub sent an unexpected answer for repo info for ${label}.`);
88
+ }
89
+ // The canonical name is used to build every later URL: it must look like owner/repo, nothing else.
90
+ const [fullOwner, fullRepo, ...extra] = body.full_name.split('/');
91
+ if (extra.length > 0 || !exports.OWNER_RE.test(fullOwner) || !exports.REPO_RE.test(fullRepo ?? '')) {
92
+ throw new githubHttp_1.GithubError(`GitHub sent an unexpected answer for repo info for ${label}.`);
93
+ }
94
+ const license = isObject(body.license) && typeof body.license.spdx_id === 'string' ? body.license.spdx_id : null;
95
+ const info = { fullName: body.full_name, defaultBranch: body.default_branch, licenseSpdx: license };
96
+ (0, githubCache_1.cachePut)(key, info);
97
+ return info;
98
+ }
99
+ const isRefAnswer = (d) => typeof d === 'string' && SHA_RE.test(d);
100
+ /** GET /repos/{owner}/{repo}/commits/{ref} with the `sha` media type → the 40-hex commit id. */
101
+ async function resolveCommit(owner, repo, ref) {
102
+ assertRepo(owner, repo);
103
+ const key = `ref:${repoKey(owner, repo)}@${ref}`;
104
+ const hit = (0, githubCache_1.cacheGet)(key, githubCache_1.CACHE_TTL_MS, isRefAnswer);
105
+ if (hit)
106
+ return hit;
107
+ const label = `github.com/${owner}/${repo}`;
108
+ const text = (await (0, githubHttp_1.request)({
109
+ url: `${githubHttp_1.GITHUB_API}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/commits/${encodeURIComponent(ref)}`,
110
+ accept: 'application/vnd.github.sha',
111
+ api: true,
112
+ maxBytes: 1024,
113
+ what: `the commit for '${ref}' in ${label}`,
114
+ // GitHub answers 422 for a ref it cannot resolve, 404 for some spellings of the same.
115
+ missing: { statuses: [404, 422], message: `Cannot find '${(0, format_1.safeText)(ref)}' in ${label} (branch, tag or commit).` },
116
+ tooLarge: new githubHttp_1.GithubError(`GitHub sent an unexpected answer for the commit of '${(0, format_1.safeText)(ref)}'.`),
117
+ }))
118
+ .toString('utf8')
119
+ .trim();
120
+ if (!SHA_RE.test(text)) {
121
+ throw new githubHttp_1.GithubError(`GitHub sent an unexpected answer for the commit of '${(0, format_1.safeText)(ref)}'.`);
122
+ }
123
+ (0, githubCache_1.cachePut)(key, text);
124
+ return text;
125
+ }
126
+ const isTree = (d) => isObject(d) &&
127
+ Array.isArray(d.entries) &&
128
+ d.entries.every((e) => isObject(e) && typeof e.path === 'string' && typeof e.sha === 'string');
129
+ /** GET /repos/{owner}/{repo}/git/trees/{sha}?recursive=1 — every file of the commit. */
130
+ async function getTree(owner, repo, sha) {
131
+ assertRepo(owner, repo);
132
+ if (!SHA_RE.test(sha))
133
+ throw new githubHttp_1.GithubError('Not a commit id.');
134
+ const key = `tree:${repoKey(owner, repo)}@${sha}`;
135
+ const hit = (0, githubCache_1.cacheGet)(key, null, isTree);
136
+ if (hit)
137
+ return hit;
138
+ const label = `github.com/${owner}/${repo}`;
139
+ const body = (0, githubHttp_1.parseJson)(await (0, githubHttp_1.request)({
140
+ url: `${githubHttp_1.GITHUB_API}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/git/trees/${sha}?recursive=1`,
141
+ accept: 'application/vnd.github+json',
142
+ api: true,
143
+ maxBytes: MAX_TREE_BYTES,
144
+ what: `the file list of ${label}`,
145
+ missing: { statuses: [404], message: `Not found: ${label}. Only public repositories can be imported.` },
146
+ tooLarge: new githubHttp_1.GithubError(exports.TOO_LARGE_REPO),
147
+ }), `the file list of ${label}`);
148
+ if (!isObject(body) || !Array.isArray(body.tree)) {
149
+ throw new githubHttp_1.GithubError(`GitHub sent an unexpected answer for the file list of ${label}.`);
150
+ }
151
+ // The recursive listing stops at 100,000 entries / 7 MB; a partial list would silently hide files.
152
+ if (body.truncated === true)
153
+ throw new githubHttp_1.GithubError(exports.TOO_LARGE_REPO);
154
+ const entries = [];
155
+ for (const e of body.tree) {
156
+ if (!isObject(e) || e.type !== 'blob' || typeof e.path !== 'string' || typeof e.sha !== 'string')
157
+ continue;
158
+ entries.push({
159
+ path: e.path,
160
+ type: 'blob',
161
+ sha: e.sha,
162
+ ...(typeof e.size === 'number' ? { size: e.size } : {}),
163
+ ...(typeof e.mode === 'string' ? { mode: e.mode } : {}),
164
+ });
165
+ }
166
+ const tree = { entries, truncated: false };
167
+ (0, githubCache_1.cachePut)(key, tree);
168
+ return tree;
169
+ }
170
+ const isText = (d) => typeof d === 'string';
171
+ const rawKey = (owner, repo, sha, filePath) => `raw:${repoKey(owner, repo)}@${sha}:${filePath}`;
172
+ /**
173
+ * One file at a commit, as text. At most MAX_SCAN_FILE_BYTES is ever downloaded
174
+ * (the limit applies while streaming, not only after), and a file with a NUL
175
+ * byte is refused as binary. `cache: false` skips WRITING the cache — callers
176
+ * use it for files they might still refuse (license, secret) and call
177
+ * {@link rememberRaw} once the file is accepted.
178
+ */
179
+ async function fetchRaw(owner, repo, sha, filePath, opts = {}) {
180
+ assertRepo(owner, repo);
181
+ if (!SHA_RE.test(sha))
182
+ throw new githubHttp_1.GithubError('Not a commit id.');
183
+ assertSafePath(filePath);
184
+ const key = rawKey(owner, repo, sha, filePath);
185
+ const hit = (0, githubCache_1.cacheGet)(key, null, isText);
186
+ if (hit !== null)
187
+ return hit;
188
+ const shown = (0, format_1.safeText)(filePath);
189
+ const limit = secretGuard_1.MAX_SCAN_FILE_BYTES / 1024;
190
+ const buf = await (0, githubHttp_1.request)({
191
+ url: `${githubHttp_1.GITHUB_RAW}/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/${sha}/${encodePath(filePath)}`,
192
+ accept: 'text/plain',
193
+ api: false,
194
+ maxBytes: secretGuard_1.MAX_SCAN_FILE_BYTES,
195
+ what: shown,
196
+ tooLarge: new githubHttp_1.GithubError(`${shown} is larger than ${limit} KB`, { kind: 'too_large' }),
197
+ });
198
+ if (buf.includes(0))
199
+ throw new githubHttp_1.GithubError(`${shown} is not a text file`, { kind: 'binary' });
200
+ const text = buf.toString('utf8');
201
+ if (opts.cache !== false)
202
+ (0, githubCache_1.cachePut)(key, text);
203
+ return text;
204
+ }
205
+ /** Keep a file fetched with `cache: false` — call it only for files that were accepted. */
206
+ function rememberRaw(owner, repo, sha, filePath, text) {
207
+ (0, githubCache_1.cachePut)(rawKey(owner, repo, sha, filePath), text);
208
+ }
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ /**
3
+ * Politeness cache for GitHub answers, under `<localRoot>/cache/github/`:
4
+ * what a `--dry-run` fetched must not be fetched again by the real import.
5
+ *
6
+ * Trees and files are keyed by commit SHA — immutable, so kept; repo info and
7
+ * ref → commit lookups go stale and live 10 minutes. File names are the sha256
8
+ * of the key (never user input); reads and writes go through fsSafe (0600/0700,
9
+ * atomic, never through a symlink). A corrupt or foreign file is ignored, a
10
+ * failed write is ignored; the folder keeps the newest {@link MAX_CACHE_FILES}.
11
+ */
12
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ var desc = Object.getOwnPropertyDescriptor(m, k);
15
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
16
+ desc = { enumerable: true, get: function() { return m[k]; } };
17
+ }
18
+ Object.defineProperty(o, k2, desc);
19
+ }) : (function(o, m, k, k2) {
20
+ if (k2 === undefined) k2 = k;
21
+ o[k2] = m[k];
22
+ }));
23
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
24
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
25
+ }) : function(o, v) {
26
+ o["default"] = v;
27
+ });
28
+ var __importStar = (this && this.__importStar) || (function () {
29
+ var ownKeys = function(o) {
30
+ ownKeys = Object.getOwnPropertyNames || function (o) {
31
+ var ar = [];
32
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
33
+ return ar;
34
+ };
35
+ return ownKeys(o);
36
+ };
37
+ return function (mod) {
38
+ if (mod && mod.__esModule) return mod;
39
+ var result = {};
40
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
41
+ __setModuleDefault(result, mod);
42
+ return result;
43
+ };
44
+ })();
45
+ Object.defineProperty(exports, "__esModule", { value: true });
46
+ exports.CACHE_TTL_MS = void 0;
47
+ exports.cacheGet = cacheGet;
48
+ exports.resetCacheState = resetCacheState;
49
+ exports.cachePut = cachePut;
50
+ const crypto = __importStar(require("crypto"));
51
+ const fs = __importStar(require("fs"));
52
+ const path = __importStar(require("path"));
53
+ const fsSafe_1 = require("./fsSafe");
54
+ const localStore_1 = require("./localStore");
55
+ /** Repo info and ref → commit answers go stale; trees and files by SHA do not. */
56
+ exports.CACHE_TTL_MS = 10 * 60 * 1000;
57
+ const MAX_CACHE_FILES = 400;
58
+ const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
59
+ function cacheDir() {
60
+ return path.join((0, localStore_1.localRoot)(), 'cache', 'github');
61
+ }
62
+ /** File names are a hash of the key — never user input. */
63
+ function cacheFile(key) {
64
+ return path.join(cacheDir(), `${crypto.createHash('sha256').update(key).digest('hex')}.json`);
65
+ }
66
+ /** Cached value, or null when missing, corrupt, of another shape, or older than `maxAgeMs` (null = keep forever). */
67
+ function cacheGet(key, maxAgeMs, valid) {
68
+ const raw = (0, fsSafe_1.readPrivateFile)(cacheFile(key));
69
+ if (raw === null)
70
+ return null;
71
+ try {
72
+ const entry = JSON.parse(raw);
73
+ if (!isObject(entry) || entry.v !== 1 || entry.key !== key || typeof entry.savedAt !== 'number')
74
+ return null;
75
+ const age = Date.now() - entry.savedAt;
76
+ if (maxAgeMs !== null && (age < 0 || age > maxAgeMs))
77
+ return null;
78
+ return valid(entry.data) ? entry.data : null;
79
+ }
80
+ catch {
81
+ return null;
82
+ }
83
+ }
84
+ let pruned = false;
85
+ /** Tests only: forget the once-per-run state. */
86
+ function resetCacheState() {
87
+ pruned = false;
88
+ }
89
+ /** Once per run: keep the newest MAX_CACHE_FILES files, drop the rest. */
90
+ function pruneCache() {
91
+ if (pruned)
92
+ return;
93
+ pruned = true;
94
+ try {
95
+ const dir = cacheDir();
96
+ const files = fs
97
+ .readdirSync(dir)
98
+ .filter((f) => /^[0-9a-f]{64}\.json$/.test(f))
99
+ .map((f) => ({ f, t: fs.statSync(path.join(dir, f)).mtimeMs }))
100
+ .sort((a, b) => b.t - a.t);
101
+ for (const old of files.slice(MAX_CACHE_FILES))
102
+ fs.unlinkSync(path.join(dir, old.f));
103
+ }
104
+ catch {
105
+ /* best effort */
106
+ }
107
+ }
108
+ /** Best effort: a read-only disk just means the next run asks GitHub again. */
109
+ function cachePut(key, data) {
110
+ try {
111
+ const entry = { v: 1, key, savedAt: Date.now(), data };
112
+ (0, fsSafe_1.writePrivateFile)(cacheFile(key), JSON.stringify(entry));
113
+ pruneCache();
114
+ }
115
+ catch {
116
+ /* best effort */
117
+ }
118
+ }
@@ -0,0 +1,197 @@
1
+ "use strict";
2
+ /**
3
+ * One HTTP request to GitHub, and what can go wrong with it. No token, ever:
4
+ * nothing here reads the environment or puts credentials or cookies on a
5
+ * request — what GitHub sees is the URL, the User-Agent below and the IP
6
+ * address it came from.
7
+ *
8
+ * Only two hosts are ever contacted:
9
+ * api.github.com repo info, ref → commit, recursive tree (counted: 60/hour per IP)
10
+ * raw.githubusercontent.com file contents at a commit (not counted)
11
+ *
12
+ * Redirects are not followed blindly: the API may redirect (a renamed repo) at
13
+ * most twice and only to api.github.com; raw downloads never redirect. One
14
+ * `AbortSignal.timeout` per request covers the body read too. A body is capped
15
+ * while it streams, not only after.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.GithubError = exports.GITHUB_RAW = exports.GITHUB_API = void 0;
19
+ exports.resetHttpState = resetHttpState;
20
+ exports.request = request;
21
+ exports.parseJson = parseJson;
22
+ const constants_1 = require("./constants");
23
+ const format_1 = require("./format");
24
+ exports.GITHUB_API = 'https://api.github.com';
25
+ exports.GITHUB_RAW = 'https://raw.githubusercontent.com';
26
+ const API_VERSION = '2022-11-28';
27
+ /** Per request, response body included (one signal covers both). */
28
+ const REQUEST_TIMEOUT_MS = 15000;
29
+ const MAX_REDIRECTS = 2;
30
+ const MAX_RAW_RETRY_WAIT_S = 5;
31
+ /** Warn once per run when this few unauthenticated requests are left. */
32
+ const LOW_LIMIT = 10;
33
+ const REDIRECTS = new Set([301, 302, 307, 308]);
34
+ /** Anything that went wrong talking to GitHub. `retryable` → exit code 2 (see errors.ts). */
35
+ class GithubError extends Error {
36
+ constructor(message, opts = {}) {
37
+ super(message);
38
+ this.name = 'GithubError';
39
+ this.retryable = opts.retryable ?? false;
40
+ this.kind = opts.kind ?? 'other';
41
+ }
42
+ }
43
+ exports.GithubError = GithubError;
44
+ // ---------------------------------------------------------------------------
45
+ // Rate-limit bookkeeping
46
+ // ---------------------------------------------------------------------------
47
+ let warnedLowLimit = false;
48
+ /** Tests only: forget the once-per-run state. */
49
+ function resetHttpState() {
50
+ warnedLowLimit = false;
51
+ }
52
+ function clock(epochSeconds) {
53
+ const d = new Date(epochSeconds * 1000);
54
+ return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
55
+ }
56
+ function resetClock(headers) {
57
+ const reset = Number(headers.get('x-ratelimit-reset'));
58
+ return Number.isFinite(reset) && reset > 0 ? clock(reset) : null;
59
+ }
60
+ function noteRateLimit(headers) {
61
+ const raw = headers.get('x-ratelimit-remaining');
62
+ const remaining = raw === null ? NaN : Number(raw);
63
+ if (!Number.isFinite(remaining) || remaining >= LOW_LIMIT || warnedLowLimit)
64
+ return;
65
+ warnedLowLimit = true;
66
+ const reset = resetClock(headers);
67
+ console.error(format_1.c.muted(`GitHub allows 60 requests an hour without a token; ${remaining} left${reset ? `, resets at ${reset}` : ''}.`));
68
+ }
69
+ function failure(status, headers, spec) {
70
+ if (spec.missing?.statuses.includes(status))
71
+ return new GithubError(spec.missing.message, { kind: 'not_found' });
72
+ if ((status === 403 || status === 429) && headers.get('x-ratelimit-remaining') === '0') {
73
+ const reset = resetClock(headers);
74
+ return new GithubError(`GitHub's limit for requests without a token (60 an hour per IP address) is used up. ${reset ? `Try again after ${reset}.` : 'Try again later.'}`, { retryable: true, kind: 'rate_limit' });
75
+ }
76
+ if (status === 409)
77
+ return new GithubError('This repository is empty.');
78
+ if (status === 451)
79
+ return new GithubError('GitHub blocks this repository for legal reasons.');
80
+ return new GithubError(`GitHub returned ${status} for ${(0, format_1.safeText)(spec.what)}.`, {
81
+ retryable: status >= 500 || status === 429 || headers.has('retry-after'),
82
+ });
83
+ }
84
+ function networkError(err, signal) {
85
+ let detail = err instanceof Error ? err.message : String(err);
86
+ const cause = err instanceof Error ? err.cause : undefined;
87
+ if (cause instanceof Error && cause.message)
88
+ detail += `: ${cause.message}`;
89
+ if (signal.aborted)
90
+ detail = `no answer within ${REQUEST_TIMEOUT_MS / 1000} s`;
91
+ return new GithubError(`Cannot reach GitHub (${(0, format_1.safeText)(detail)}).`, { retryable: true, kind: 'network' });
92
+ }
93
+ /** A redirect target is followed only when it is https://api.github.com/… (relative paths resolve against the request). */
94
+ function apiRedirectTarget(location, from) {
95
+ if (!location)
96
+ return null;
97
+ try {
98
+ const u = new URL(location, from);
99
+ return u.origin === exports.GITHUB_API && !u.username && !u.password ? u.toString() : null;
100
+ }
101
+ catch {
102
+ return null;
103
+ }
104
+ }
105
+ async function discard(res) {
106
+ try {
107
+ await res.body?.cancel();
108
+ }
109
+ catch {
110
+ /* nothing left to free */
111
+ }
112
+ }
113
+ async function readBody(res, spec) {
114
+ const declared = Number(res.headers.get('content-length'));
115
+ if (Number.isFinite(declared) && declared > spec.maxBytes) {
116
+ await discard(res);
117
+ throw spec.tooLarge;
118
+ }
119
+ if (!res.body)
120
+ return Buffer.alloc(0);
121
+ const reader = res.body.getReader();
122
+ const chunks = [];
123
+ let total = 0;
124
+ for (;;) {
125
+ const { done, value } = await reader.read();
126
+ if (done)
127
+ break;
128
+ total += value.byteLength;
129
+ if (total > spec.maxBytes) {
130
+ await reader.cancel().catch(() => undefined);
131
+ throw spec.tooLarge;
132
+ }
133
+ chunks.push(value);
134
+ }
135
+ return Buffer.concat(chunks);
136
+ }
137
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
138
+ function retryAfterMs(headers) {
139
+ const raw = (headers.get('retry-after') ?? '').trim();
140
+ const seconds = /^\d{1,6}$/.test(raw) ? Number(raw) : 1;
141
+ return Math.min(seconds, MAX_RAW_RETRY_WAIT_S) * 1000;
142
+ }
143
+ async function request(spec) {
144
+ let url = spec.url;
145
+ let hops = 0;
146
+ let waited = false;
147
+ for (;;) {
148
+ const signal = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
149
+ try {
150
+ const res = await fetch(url, {
151
+ method: 'GET',
152
+ headers: {
153
+ 'User-Agent': `promptlike-cli/${constants_1.CLI_VERSION}`,
154
+ Accept: spec.accept,
155
+ ...(spec.api ? { 'X-GitHub-Api-Version': API_VERSION } : {}),
156
+ },
157
+ redirect: 'manual',
158
+ signal,
159
+ });
160
+ noteRateLimit(res.headers);
161
+ if (REDIRECTS.has(res.status)) {
162
+ await discard(res);
163
+ const next = spec.api && hops < MAX_REDIRECTS ? apiRedirectTarget(res.headers.get('location'), url) : null;
164
+ if (!next)
165
+ throw failure(res.status, res.headers, spec);
166
+ url = next;
167
+ hops++;
168
+ continue;
169
+ }
170
+ // raw.githubusercontent.com asks for a pause with 429: once, never longer than a few seconds.
171
+ if (res.status === 429 && !spec.api && !waited) {
172
+ await discard(res);
173
+ waited = true;
174
+ await sleep(retryAfterMs(res.headers));
175
+ continue;
176
+ }
177
+ if (!res.ok) {
178
+ await discard(res);
179
+ throw failure(res.status, res.headers, spec);
180
+ }
181
+ return await readBody(res, spec);
182
+ }
183
+ catch (err) {
184
+ if (err instanceof GithubError)
185
+ throw err;
186
+ throw networkError(err, signal);
187
+ }
188
+ }
189
+ }
190
+ function parseJson(buf, what) {
191
+ try {
192
+ return JSON.parse(buf.toString('utf8'));
193
+ }
194
+ catch {
195
+ throw new GithubError(`GitHub sent an unexpected answer for ${(0, format_1.safeText)(what)}.`);
196
+ }
197
+ }