@vltpkg/registry-client 1.0.8 → 1.0.10

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/dist/index.d.ts CHANGED
@@ -11,6 +11,13 @@ import type { WebAuthChallenge } from './web-auth-challenge.ts';
11
11
  import { oidc } from './oidc.ts';
12
12
  import type { OidcOptions } from './oidc.ts';
13
13
  export { CacheEntry, clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, oidc, registryBase, runtimeTokens, setRuntimeToken, setToken, type JSONObj, type OidcOptions, type Token, type TokenResponse, type WebAuthChallenge, };
14
+ /** A response body read straight out of the cache file. */
15
+ export type CachedBody = {
16
+ /** the cache file it came from */
17
+ path: string;
18
+ /** the body, a view into the file's bytes */
19
+ body: Buffer;
20
+ };
14
21
  export type CacheableMethod = 'GET' | 'HEAD';
15
22
  export declare const isCacheableMethod: (m: unknown) => m is CacheableMethod;
16
23
  export declare const cacheKey: (method: string, url: URL | string) => string;
@@ -108,6 +115,12 @@ export type RegistryClientRequestOptions = Omit<Dispatcher.RequestOptions, 'meth
108
115
  * @internal
109
116
  */
110
117
  staleWhileRevalidate?: false;
118
+ /**
119
+ * Revalidate a cached response even when it is still within max-age.
120
+ * Conditional request headers are still sent when available.
121
+ * @internal
122
+ */
123
+ forceRevalidate?: boolean;
111
124
  };
112
125
  export declare const userAgent: string;
113
126
  export declare class RegistryClient {
@@ -148,5 +161,23 @@ export declare class RegistryClient {
148
161
  * hang on the `doneUrl` until it returns a {@link TokenResponse} object.
149
162
  */
150
163
  webAuthOpener({ doneUrl, authUrl }: WebAuthChallenge): Promise<TokenResponse>;
164
+ /**
165
+ * Read a valid cached non-JSON body straight off disk, bypassing the
166
+ * in-memory cache LRU so that a tarball is never held in it.
167
+ *
168
+ * One read: the head is decoded from the same bytes the body comes
169
+ * from, so `cache-unzip` rewriting the head cannot land between the
170
+ * two and hand back a body at a stale offset.
171
+ *
172
+ * Does not log a cache hit -- the caller may still reject the body
173
+ * and fall back to {@link request}, which logs its own.
174
+ *
175
+ * Returns undefined on anything unexpected; callers fall back to
176
+ * {@link request}.
177
+ */
178
+ cachedBody(url: URL | string, options?: {
179
+ integrity?: Integrity;
180
+ method?: CacheableMethod;
181
+ }): CachedBody | undefined;
151
182
  request(url: URL | string, options?: RegistryClientRequestOptions): Promise<CacheEntry>;
152
183
  }
package/dist/index.js CHANGED
@@ -6,6 +6,8 @@ import { logRequest } from '@vltpkg/output';
6
6
  import { urlOpen } from '@vltpkg/url-open';
7
7
  import { XDG } from '@vltpkg/xdg';
8
8
  import { randomUUID } from 'node:crypto';
9
+ import { readFileSync } from 'node:fs';
10
+ import { STATUS_CODES } from 'node:http';
9
11
  import { availableParallelism } from 'node:os';
10
12
  import { dirname, resolve } from 'node:path';
11
13
  import { setTimeout } from 'node:timers/promises';
@@ -201,11 +203,16 @@ export class RegistryClient {
201
203
  return;
202
204
  }
203
205
  }
204
- /* c8 ignore start */
205
206
  // TODO: fall back to username/password login, and/or couchdb PUT login
206
- throw error('Failed to perform web login', { response });
207
+ const { statusCode } = response;
208
+ const status = STATUS_CODES[statusCode];
209
+ throw error(`Failed to perform web login: ${statusCode}${status ? ` ${status}` : ''}`, {
210
+ code: 'EREQUEST',
211
+ url: webLoginURL,
212
+ status: statusCode,
213
+ response,
214
+ });
207
215
  }
208
- /* c8 ignore stop */
209
216
  /**
210
217
  * Given a {@link WebAuthChallenge}, open the `authUrl` in a browser and
211
218
  * hang on the `doneUrl` until it returns a {@link TokenResponse} object.
@@ -280,9 +287,70 @@ export class RegistryClient {
280
287
  response,
281
288
  });
282
289
  }
290
+ /**
291
+ * Read a valid cached non-JSON body straight off disk, bypassing the
292
+ * in-memory cache LRU so that a tarball is never held in it.
293
+ *
294
+ * One read: the head is decoded from the same bytes the body comes
295
+ * from, so `cache-unzip` rewriting the head cannot land between the
296
+ * two and hand back a body at a stale offset.
297
+ *
298
+ * Does not log a cache hit -- the caller may still reject the body
299
+ * and fall back to {@link request}, which logs its own.
300
+ *
301
+ * Returns undefined on anything unexpected; callers fall back to
302
+ * {@link request}.
303
+ */
304
+ cachedBody(url, options = {}) {
305
+ const { integrity, method = 'GET' } = options;
306
+ try {
307
+ // normalize like request() does, or a url that is not already in
308
+ // canonical form (an explicit :443, say) keys a different file
309
+ // and the fast path silently never hits.
310
+ const key = cacheKey(method, typeof url === 'string' ? new URL(url) : url);
311
+ // an in-memory value can be newer than disk, since cache.set
312
+ // writes to disk asynchronously. let request() serve those.
313
+ // (an in-flight fetch() peeks as undefined, so the probe reads
314
+ // disk underneath it -- benign, tarball urls are immutable.)
315
+ if (this.cache.peek(key))
316
+ return undefined;
317
+ // same order as the cache's own disk read
318
+ const paths = new Set();
319
+ try {
320
+ const i = this.cache.integrityPath(integrity);
321
+ if (i)
322
+ paths.add(i);
323
+ }
324
+ catch { }
325
+ paths.add(this.cache.path(key));
326
+ for (const path of paths) {
327
+ let buf;
328
+ try {
329
+ buf = readFileSync(path);
330
+ }
331
+ catch {
332
+ continue;
333
+ }
334
+ const entry = CacheEntry.decode(buf);
335
+ // statusCode must stay first: an unparseable buffer decodes to
336
+ // the module-level emptyCacheEntry singleton, and valid/isJSON
337
+ // memoize onto `this`, so reading them off it would poison the
338
+ // singleton process-wide.
339
+ if (entry.statusCode !== 200 ||
340
+ !entry.valid ||
341
+ entry.isJSON) {
342
+ continue;
343
+ }
344
+ return { path, body: entry.buffer() };
345
+ }
346
+ /* c8 ignore next */
347
+ }
348
+ catch { }
349
+ return undefined;
350
+ }
283
351
  async request(url, options = {}) {
284
352
  const u = typeof url === 'string' ? new URL(url) : url;
285
- const { method = 'GET', integrity, redirections = new Set(), signal, otp = (process.env.VLT_OTP ?? '').trim(), staleWhileRevalidate = true, } = options;
353
+ const { method = 'GET', integrity, redirections = new Set(), signal, otp = (process.env.VLT_OTP ?? '').trim(), staleWhileRevalidate = true, forceRevalidate = false, } = options;
286
354
  let { trustIntegrity } = options;
287
355
  const m = isCacheableMethod(method) ? method : undefined;
288
356
  const { useCache = !!m } = options;
@@ -295,11 +363,21 @@ export class RegistryClient {
295
363
  await this.cache.fetch(key, { context: { integrity } })
296
364
  : undefined;
297
365
  const entry = buffer ? this.#decodeCached(buffer) : undefined;
298
- if (entry?.valid) {
366
+ if (entry?.valid && !forceRevalidate) {
299
367
  logRequest(url, 'cache', { method });
300
368
  return entry;
301
369
  }
302
- if (staleWhileRevalidate && entry?.staleWhileRevalidate && m) {
370
+ // what the two early returns below would have served had
371
+ // forceRevalidate not skipped them. read once: staleWhileRevalidate
372
+ // memoizes a deadline, not an answer, so an entry can expire during
373
+ // a slow failure and the fallback would silently miss.
374
+ const forcedFallback = forceRevalidate && entry?.staleWhileRevalidate ?
375
+ entry
376
+ : undefined;
377
+ if (!forceRevalidate &&
378
+ staleWhileRevalidate &&
379
+ entry?.staleWhileRevalidate &&
380
+ m) {
303
381
  // revalidate while returning the stale entry
304
382
  register(dirname(this.cache.path()), m, url);
305
383
  logRequest(url, 'stale', { method });
@@ -329,6 +407,17 @@ export class RegistryClient {
329
407
  /* c8 ignore start */
330
408
  }
331
409
  catch (er) {
410
+ // a forced revalidation that can't reach the registry must be no
411
+ // worse than the entry it skipped past. also covers 5xx/429, which
412
+ // land here once RetryAgent gives up. an abort is the caller's own
413
+ // doing, so it still rejects.
414
+ if (forcedFallback &&
415
+ !signal?.aborted) {
416
+ // 'stale', not 'cache': a 'start' was already logged, and unlike
417
+ // the swr path above nothing revalidates in the background.
418
+ logRequest(url, 'stale', { method });
419
+ return forcedFallback;
420
+ }
332
421
  // Rethrow so we get a better stack trace
333
422
  throw error('Request failed', {
334
423
  code: 'EREQUEST',
@@ -350,7 +439,16 @@ export class RegistryClient {
350
439
  if (result.isGzip && !trustIntegrity) {
351
440
  result.checkIntegrity({ url });
352
441
  }
353
- if (useCache) {
442
+ // a forced revalidation must never replace a cached entry with an
443
+ // error response -- the flat 200-only rule revalidate-entry.ts has.
444
+ // keyed on entry existing at all, not on validity: staleWhileRevalidate
445
+ // is true forever for an entry with no date header, which would make
446
+ // one permanently unreplaceable.
447
+ // safe on the 304 path: handleCacheHitResponse returns the cached
448
+ // entry, whose statusCode is the original 200, so the date refresh
449
+ // still gets written back.
450
+ const clobbersCachedEntry = forceRevalidate && !!entry && result.statusCode !== 200;
451
+ if (useCache && !clobbersCachedEntry) {
354
452
  // Get the encoded buffer from the cache entry
355
453
  const buffer = result.encode();
356
454
  this.cache.set(key, Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength), {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@vltpkg/registry-client",
3
3
  "description": "Fetch package artifacts and metadata from registries",
4
- "version": "1.0.8",
4
+ "version": "1.0.10",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/vltpkg/vltpkg.git",
@@ -13,14 +13,14 @@
13
13
  "url": "http://vlt.sh"
14
14
  },
15
15
  "dependencies": {
16
- "@vltpkg/cache": "1.0.8",
17
- "@vltpkg/cache-unzip": "1.0.8",
18
- "@vltpkg/error-cause": "1.0.8",
19
- "@vltpkg/keychain": "1.0.8",
20
- "@vltpkg/output": "1.0.8",
21
- "@vltpkg/types": "1.0.8",
22
- "@vltpkg/url-open": "1.0.8",
23
- "@vltpkg/xdg": "1.0.8",
16
+ "@vltpkg/cache": "1.0.10",
17
+ "@vltpkg/cache-unzip": "1.0.10",
18
+ "@vltpkg/error-cause": "1.0.10",
19
+ "@vltpkg/keychain": "1.0.10",
20
+ "@vltpkg/output": "1.0.10",
21
+ "@vltpkg/types": "1.0.10",
22
+ "@vltpkg/url-open": "1.0.10",
23
+ "@vltpkg/xdg": "1.0.10",
24
24
  "cache-control-parser": "^2.0.6",
25
25
  "package-json-from-dist": "^1.0.1",
26
26
  "undici": "^7.16.0"