Add types npm-registry-fetch, libnpmsearch, and pacote (#38376)

* Add types for npm-registry-fetch

* Add types for libnpmsearch

* Add types for pacote

* Use ReadonlyArray in libnpmsearch

* pacote: Reorganize imports/exports
This commit is contained in:
Joel Spadin
2019-09-25 11:37:07 -05:00
committed by Ben Lichtman
parent d0591744c0
commit 25fe77861d
17 changed files with 1028 additions and 0 deletions

82
types/libnpmsearch/index.d.ts vendored Normal file
View File

@@ -0,0 +1,82 @@
// Type definitions for libnpmsearch 2.0
// Project: https://npmjs.com/package/libnpmsearch
// Definitions by: Joel Spadin <https://github.com/ChaosinaCan>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.0
/// <reference types="node" />
import npmFetch = require('npm-registry-fetch');
declare function search(query: string | ReadonlyArray<string>, opts: search.Options & { detailed: true }): Promise<search.DetailedResult[]>;
declare function search(query: string | ReadonlyArray<string>, opts?: search.Options): Promise<search.Result[]>;
declare namespace search {
function stream(query: string | ReadonlyArray<string>, opts?: Options): NodeJS.ReadWriteStream;
interface Maintainer {
username: string;
email: string;
}
interface Result {
name: string;
version: string;
description?: string;
maintainers?: Maintainer[];
keywords?: string[];
date?: Date;
}
interface DetailedResult {
package: Result;
score: number;
searchScore: number;
}
type Options = SearchOptions & npmFetch.Options;
interface SearchOptions {
/**
* Number of results to limit the query to. Default: `20`
*/
limit?: number;
/**
* Offset number for results. Used with `opts.limit` for pagination.
* Default: `0`
*/
from?: number;
/**
* If true, returns an object with `package`, `score`, and `searchScore`
* fields, with `package` being what would usually be returned, and the
* other two containing details about how that package scored. Useful
* for UIs. Default: `false`
*/
detailed?: boolean;
/**
* Used as a shorthand to set `opts.quality`, `opts.maintenance`, and
* `opts.popularity` with values that prioritize each one.
*/
sortBy?: 'optimal' | 'quality' | 'maintenance' | 'popularity';
/**
* Decimal number between `0` and `1` that defines the weight of
* `maintenance` metrics when scoring and sorting packages.
* Default: `0.65` (same as `opts.sortBy: 'optimal'`)
*/
maintenance?: number;
/**
* Decimal number between `0` and `1` that defines the weight of
* `popularity` metrics when scoring and sorting packages.
* Default: `0.98` (same as `opts.sortBy: 'optimal'`)
*/
popularity?: number;
/**
* Decimal number between `0` and `1` that defines the weight of
* `quality` metrics when scoring and sorting packages.
* Default: `0.5` (same as `opts.sortBy: 'optimal'`)
*/
quality?: number;
}
}
export = search;

View File

@@ -0,0 +1,17 @@
import search = require('libnpmsearch');
const opts: search.Options = {
limit: 20,
from: 0,
detailed: false,
sortBy: 'optimal',
registry: 'https://registry.npmjs.org',
token: 'token',
};
search('libnpm'); // $ExpectType Promise<Result[]>
search('libnpm', opts); // $ExpectType Promise<Result[]>
search('libnpm', { detailed: true }); // $ExpectType Promise<DetailedResult[]>
search.stream('libnpm'); // $ExpectType ReadWriteStream
search.stream('libnpm', opts); // $ExpectType ReadWriteStream

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictFunctionTypes": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"libnpmsearch-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

477
types/npm-registry-fetch/index.d.ts vendored Normal file
View File

@@ -0,0 +1,477 @@
// Type definitions for npm-registry-fetch 4.0
// Project: https://github.com/npm/registry-fetch#readme
// Definitions by: Joel Spadin <https://github.com/ChaosinaCan>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.0
/// <reference types="node" />
import { Response } from 'node-fetch';
import { Readable, Stream } from 'stream';
import { Agent } from 'http';
import { Integrity } from 'ssri';
import { Logger } from 'npmlog';
import * as npa from 'npm-package-arg';
/**
* Performs a request to a given URL.
*
* The URL can be either a full URL, or a path to one. The appropriate registry
* will be automatically picked if only a URL path is given.
*/
declare function fetch(url: string, opts?: fetch.Options): Promise<Response>;
declare namespace fetch {
function pickRegistry(spec: string, opts?: Options): string;
/**
* Performs a request to a given registry URL, parses the body of the
* response as JSON, and returns it as its final value. This is a utility
* shorthand for `fetch(url).then(res => res.json())`.
*/
function json(url: string, opts?: Options): Record<string, unknown>;
namespace json {
/**
* Performs a request to a given registry URL and parses the body of the
* response as JSON, with each entry being emitted through the stream.
*
* The jsonPath argument is a `JSONStream.parse()` path, and the returned
* stream (unlike default `JSONStreams`), has a valid `Symbol.asyncIterator`
* implementation.
*/
function stream(url: string, jsonPath: string, opts?: Options): NodeJS.ReadWriteStream;
}
type Options = FetchOptions & FetchRetryOptions & AuthOptions;
interface AuthOptions {
'always-auth'?: boolean;
alwaysAuth?: boolean;
email?: string;
/**
* Password used for basic authentication. For the more modern
* authentication method, please use the (more secure) `opts.token`
*
* Can optionally be scoped to a registry by using a "nerf dart" for
* that registry. That is:
*
* ```typescript
* {
* '//registry.npmjs.org/:password': 't0k3nH34r'
* }
* ```
*
* See also `opts.username`
*/
password?: string;
/**
* Alias for `password`
*/
_password?: string;
/**
* This is a one-time password from a two-factor authenticator. It is
* required for certain registry interactions when two-factor auth is
* enabled for a user account.
*/
otp?: number | string;
/**
* Authentication token string.
*
* Can be scoped to a registry by using a "nerf dart" for that registry.
* That is:
*
* ```typescript
* {
* '//registry.npmjs.org/:token': 't0k3nH34r'
* }
* ```
*/
token?: string;
/**
* Alias for `token`.
*/
_authToken?: string;
/**
* Username used for basic authentication. For the more modern
* authentication method, please use the (more secure) `opts.token`
*
* Can optionally be scoped to a registry by using a "nerf dart" for
* that registry. That is:
*
* ```typescript
* {
* '//registry.npmjs.org/:username': 't0k3nH34r'
* }
* ```
*
* See also `opts.password`
*/
username?: string;
/**
* @deprecated
* This is a legacy authentication token supported only for
* compatibility. Please use `opts.token` instead.
*/
_auth?: string;
}
interface FetchRetryOptions {
/**
* The "retries" config for `retry` to use when fetching packages from
* the registry.
*
* See also `opts.retry` to provide all retry options as a single object.
*/
'fetch-retries'?: number;
/**
* The "factor" config for `retry` to use when fetching packages.
*
* See also `opts.retry` to provide all retry options as a single
* object.
*/
'fetch-retry-factor'?: number;
/**
* The "minTimeout" config for `retry` to use when fetching packages.
*
* See also `opts.retry` to provide all retry options as a single
* object.
*/
'fetch-retry-mintimeout'?: number;
/**
* The "maxTimeout" config for `retry` to use when fetching packages.
*
* See also `opts.retry` to provide all retry options as a single
* object.
*/
'fetch-retry-maxtimeout'?: number;
}
/**
* Extra options:
*
* **<scope>:registry**
*
* This option type can be used to configure the registry used for requests
* involving a particular scope. For example,
* `opts['@myscope:registry'] = 'https://scope-specific.registry/'` will
* make it so requests go out to this registry instead of `opts.registry`
* when `opts.scope` is used, or when `opts.spec` is a scoped package spec.
*
* The `@` before the scope name is optional, but recommended.
*
* **<registry>:password**
* @see password
*
* **<registry>:token**
* @see token
*
* **<registry>:username**
* @see username
*/
interface FetchOptions {
/**
* An `Agent` instance to be shared across requests. This allows
* multiple concurrent fetch requests to happen on the same socket.
*
* You do not need to provide this option unless you want something
* particularly specialized, since proxy configurations and http/https
* agents are already automatically managed internally when this option
* is not passed through.
*/
agent?: Agent;
/**
* Request body to send through the outgoing request. Buffers and
* Streams will be passed through as-is, with a default `content-type`
* of `application/octet-stream`. Plain JavaScript objects will be
* `JSON.stringify`ed and the `content-type` will default to
* `application/json`.
*
* Use `opts.headers` to set the content-type to something else.
*/
body?: Buffer | Stream | object | string;
/**
* The Certificate Authority signing certificate that is trusted for SSL
* connections to the registry. Values should be in PEM format (Windows
* calls it "Base-64 encoded X.509 (.CER)") with newlines replaced by
* the string `'\n'`. For example:
*
* ```typescript
* {
* ca: '-----BEGIN CERTIFICATE-----\nXXXX\nXXXX\n-----END CERTIFICATE-----'
* }
* ```
*
* Set to `null` to only allow "known" registrars, or to a specific CA
* cert to trust only that specific signing authority.
*
* Multiple CAs can be trusted by specifying an array of certificates
* instead of a single string.
*
* See also `opts.strict-ssl`, `opts.ca` and `opts.key`
*/
ca?: string | Buffer | Array<string | Buffer> | null;
/**
* The location of the http cache directory. If provided, certain
* cachable requests will be cached according to
* [IETF RFC 7234](https://tools.ietf.org/html/rfc7234) rules. This will
* speed up future requests, as well as make the cached data available
* offline if necessary/requested.
*
* See also `offline`, `prefer-offline`, and `prefer-online`.
*/
cache?: string;
/**
* A client certificate to pass when accessing the registry. Values
* should be in PEM format (Windows calls it "Base-64 encoded X.509
* (.CER)") with newlines replaced by the string `'\n'`. For example:
*
* ```typescript
* {
* cert: '-----BEGIN CERTIFICATE-----\nXXXX\nXXXX\n-----END CERTIFICATE-----'
* }
* ```
*
* It is *not* the path to a certificate file (and there is no "certfile"
* option).
*
* See also: `opts.ca` and `opts.key`
*/
cert?: string;
/**
* If present, other auth-related values in `opts` will be completely
* ignored, including `alwaysAuth`, `email`, and `otp`, when calculating
* auth for a request, and the auth details in `opts.forceAuth` will be
* used instead.
*/
'force-auth'?: Partial<AuthOptions>;
/**
* Alias for `force-auth`
*/
forceAuth?: Partial<AuthOptions>;
/**
* If true, `npm-registry-fetch` will set the `Content-Encoding` header
* to `gzip` and use `zlib.gzip()` or `zlib.createGzip()` to gzip-encode
* `opts.body`.
*/
gzip?: boolean;
/**
* Additional headers for the outgoing request. This option can also be
* used to override headers automatically generated by
* `npm-registry-fetch`, such as `Content-Type`.
*/
headers?: Record<string, string>;
/**
* If true, the response body will be thrown away and `res.body` set to
* `null`. This will prevent dangling response sockets for requests
* where you don't usually care what the response body is.
*/
'ignore-body'?: boolean;
/**
* Alias for `ignore-body`.
*/
ignoreBody?: boolean;
/**
* If provided, the response body's will be verified against this
* integrity string, using [`ssri`](https://npm.im/ssri). If
* verification succeeds, the response will complete as normal. If
* verification fails, the response body will error with an `EINTEGRITY`
* error.
*
* Body integrity is only verified if the body is actually consumed to
* completion -- that is, if you use `res.json()`/`res.buffer()`, or if
* you consume the default `res` stream data to its end.
*
* Cached data will have its integrity automatically verified using the
* previously-generated integrity hash for the saved request
* information, so `EINTEGRITY` errors can happen if `opts.cache` is
* used, even if `opts.integrity` is not passed in.
*/
integrity?: string | Integrity;
/**
* This is used to populate the `npm-in-ci` request header sent to the
* registry.
*/
'is-from-ci'?: boolean;
/**
* Alias for `is-from-ci`
*/
isFromCI?: boolean;
/**
* A client key to pass when accessing the registry. Values should be in
* PEM format with newlines replaced by the string `'\n'`. For example:
*
* ```typescript
* {
* key: '-----BEGIN PRIVATE KEY-----\nXXXX\nXXXX\n-----END PRIVATE KEY-----'
* }
* ```
*
* It is *not* the path to a key file (and there is no "keyfile"
* option).
*
* See also: `opts.ca` and `opts.cert`
*/
key?: string;
/**
* The IP address of the local interface to use when making connections
* to the registry.
*
* See also `opts.proxy`
*/
'local-address'?: string;
/**
* Logger object to use for logging operation details.
*/
log?: Logger;
/**
* When using `fetch.json.stream()` (NOT `fetch.json()`), this will be
* passed down to `JSONStream` as the second argument to
* `JSONStream.parse`, and can be used to transform stream data before
* output.
*/
'map-json'?: (v: any) => any;
/**
* Alias for `map-json`
*/
mapJson?: (v: any) => any;
/**
* Alias for `map-json`
*/
mapJSON?: (v: any) => any;
/**
* Maximum number of sockets to keep open during requests. Has no effect
* if `opts.agent` is used.
*/
maxsockets?: number;
/**
* Alias for `maxsockets`
*/
'max-sockets'?: number;
/**
* HTTP method to use for the outgoing request. Case-insensitive.
*/
method?: string;
/**
* If true, proxying will be disabled even if `opts.proxy` is used.
*/
noproxy?: boolean;
/**
* If provided, will be sent in the `npm-session` header. This header is
* used by the npm registry to identify individual user sessions
* (usually individual invocations of the CLI).
*/
'npm-session'?: string;
/**
* Alias for `npm-session`
*/
npmSession?: string;
/**
* Force offline mode: no network requests will be done during install.
* To allow `npm-registry-fetch` to fill in missing cache data, see
* `opts.prefer-offline`.
*
* This option is only really useful if you're also using `opts.cache`.
*/
offline?: boolean;
/**
* If true, staleness checks for cached data will be bypassed, but
* missing data will be requested from the server. To force full offline
* mode, use `opts.offline`.
*
* This option is generally only useful if you're also using `opts.cache`.
*/
'prefer-offline'?: boolean;
/**
* If true, staleness checks for cached data will be forced, making the
* CLI look for updates immediately even for fresh package data.
*
* This option is generally only useful if you're also using `opts.cache`.
*/
'prefer-online'?: boolean;
/**
* If provided, will be sent in the npm-scope header. This header is
* used by the npm registry to identify the toplevel package scope that
* a particular project installation is using.
*/
'project-scope'?: string;
/**
* Alias for `project-scope`.
*/
projectScope?: string;
/**
* A proxy to use for outgoing http requests. If not passed in, the
* `HTTP(S)_PROXY` environment variable will be used.
*/
proxy?: string;
/**
* If provided, the request URI will have a query string appended to it
* using this query. If `opts.query` is an object, it will be converted
* to a query string using [`querystring.stringify()`](https://nodejs.org/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options).
*
* If the request URI already has a query string, it will be merged with
* `opts.query`, preferring `opts.query` values.
*/
query?: string | object;
/**
* Value to use for the `Referer` header. The npm CLI itself uses this
* to serialize the npm command line using the given request.
*/
refer?: string;
/**
* Alias for `refer`.
*/
referer?: string;
/**
* Registry configuration for a request. If a request URL only includes
* the URL path, this registry setting will be prepended. This
* configuration is also used to determine authentication details, so
* even if the request URL references a completely different host,
* `opts.registry` will be used to find the auth details for that
* request.
*
* See also `opts.scope`, `opts.spec`, and `opts.<scope>:registry` which
* can all affect the actual registry URL used by the outgoing request.
*/
registry?: string;
/**
* Single-object configuration for request retry settings. If passed in,
* will override individually-passed `fetch-retry-*` settings.
*/
retry?: Partial<FetchRetryOptions>;
/**
* Associate an operation with a scope for a scoped registry. This
* option can force lookup of scope-specific registries and
* authentication.
*
* See also `opts.<scope>:registry` and `opts.spec` for interactions
* with this option.
*/
scope?: string;
/**
* If provided, can be used to automatically configure `opts.scope`
* based on a specific package name. Non-registry package specs will
* throw an error.
*/
spec?: string | npa.Result;
/**
* Whether or not to do SSL key validation when making requests to the
* registry via https.
*
* See also `opts.ca`.
*/
'strict-ssl'?: boolean;
/**
* Time before a hanging request times out.
*/
timeout?: number;
/**
* User agent string to send in the `User-Agent` header.
*/
'user-agent'?: string;
[key: string]: any;
}
}
export = fetch;

View File

@@ -0,0 +1,81 @@
import fetch = require('npm-registry-fetch');
import { Agent } from 'http';
import { Integrity } from 'ssri';
import npmlog = require('npmlog');
const auth: fetch.AuthOptions = {
'always-auth': true,
email: 'nobody@mail.com',
otp: 123456,
password: 'password',
username: 'nobody',
token: 'token',
};
const retry: fetch.FetchRetryOptions = {
'fetch-retries': 42,
'fetch-retry-factor': 10,
'fetch-retry-maxtimeout': 10000,
'fetch-retry-mintimeout': 60000,
};
const opts: fetch.Options = {
'always-auth': false,
'fetch-retries': 42,
'fetch-retry-factor': 10,
'fetch-retry-maxtimeout': 10000,
'fetch-retry-mintimeout': 60000,
'force-auth': auth,
'ignore-body': true,
'is-from-ci': false,
'local-address': 'address.local',
'map-json': obj => obj.toString(),
'max-sockets': 42,
'npm-session': 'session',
'prefer-offline': false,
'prefer-online': true,
'project-scope': 'scope',
'strict-ssl': true,
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3891.0 Safari/537.36 Edg/78.0.268.3',
agent: new Agent(),
body: 'sometext',
ca: new Buffer(1000),
cache: './my/cache/dir',
cert: 'XXXX',
email: 'nobody@mail.com',
gzip: true,
headers: {
'Content-Type': 'text/plain'
},
integrity: new Integrity(),
key: 'XXXX',
log: npmlog,
method: 'GET',
noproxy: false,
offline: false,
otp: 123456,
password: 'password',
proxy: 'https://my.proxy',
query: { foo: 'bar' },
refer: 'https://registry.npmjs.org',
registry: 'https://registry.npmjs.org',
retry,
scope: 'scope',
spec: '@scope/package',
timeout: 60000,
token: 'token',
username: 'nobody',
'@myscope:registry': 'https://scope-specific.registry/',
'//registry.npmjs.org/:password': 'password',
'//registry.npmjs.org/:token': 'token',
'//registry.npmjs.org/:username': 'nobody',
};
fetch('/'); // $ExpectType Promise<Response>
fetch('/', opts); // $ExpectType Promise<Response>
fetch.json('/'); // $ExpectType Record<string, unknown>
fetch.json('/', opts); // $ExpectType Record<string, unknown>
fetch.json.stream('/-/user/zkat/package', '$*'); // $ExpectType ReadWriteStream
fetch.json.stream('/-/user/zkat/package', '$*', opts); // $ExpectType ReadWriteStream
fetch.pickRegistry('npm-registry-fetch@latest'); // $ExpectType string
fetch.pickRegistry('npm-registry-fetch@latest', opts); // $ExpectType string

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictFunctionTypes": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"npm-registry-fetch-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

12
types/pacote/extract.d.ts vendored Normal file
View File

@@ -0,0 +1,12 @@
import { Options } from './index';
/**
* Extracts package data identified by `spec` into a directory named
* `destination`, which will be created if it does not already exist.
*
* If `opts.digest` is provided and the data it identifies is present in the
* cache, `extract` will bypass most of its operations and go straight to
* extracting the tarball.
*/
declare function extract(spec: string, destination?: string, opts?: Options): Promise<void>;
export = extract;

164
types/pacote/index.d.ts vendored Normal file
View File

@@ -0,0 +1,164 @@
// Type definitions for pacote 9.5
// Project: https://github.com/npm/pacote#readme
// Definitions by: Joel Spadin <https://github.com/ChaosinaCan>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.0
/// <reference types="node" />
import { Readable } from 'stream';
import npmFetch = require('npm-registry-fetch');
import extract = require('./extract');
import manifest = require('./manifest');
import packument = require('./packument');
import prefetch = require('./prefetch');
import tarball = require('./tarball');
export { extract, manifest, packument, prefetch, tarball };
/**
* This utility function can be used to force pacote to release its references
* to any memoized data in its various internal caches. It might help free some
* memory.
*/
export function clearMemoized(): void;
export interface Manifest {
name: string;
version: string;
dependencies: Record<string, string>;
optionalDependencies: Record<string, string>;
devDependencies: Record<string, string>;
peerDependencies: Record<string, string>;
bundleDependencies: false | string[];
bin: Record<string, string> | null;
_resolved: string;
_integrity: string;
_shrinkwrap: Record<string, unknown> | null;
engines?: Record<string, string>;
cpu?: string[];
os?: string[];
_id?: string;
[key: string]: unknown;
}
export interface PackageDist {
shasum: string;
tarball: string;
integrity?: string;
fileCount?: number;
unpackedSize?: number;
}
export interface Human {
name: string;
email?: string;
url?: string;
}
export interface PackageVersion {
name: string;
version: string;
dependencies?: Record<string, string>;
optionalDependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
peerDependencies?: Record<string, string>;
directories: {};
dist: PackageDist;
_hasShrinkwrap: boolean;
// Extra metadata which may be added by the registry:
description?: string;
main?: string;
scripts?: Record<string, string>;
repository?: {
type: string;
url: string;
directory?: string;
};
engines?: Record<string, string>;
keywords?: string[];
author?: Human;
contributors?: Human[];
maintainers?: Human[];
license?: string;
homepage?: string;
bugs?: { url: string };
_id?: string;
_nodeVersion?: string;
_npmVersion?: string;
_npmUser?: Human;
[key: string]: unknown;
}
export interface Packument {
name: string;
'dist-tags': { latest: string; } & Record<string, string>;
versions: Record<string, PackageVersion>;
[key: string]: unknown;
}
export interface PacoteOptions {
/**
* Expects a function that takes a single argument, `dir`, and returns a
* `ReadableStream` that outputs packaged tarball data. Used when creating
* tarballs for package specs that are not already packaged, such as git and
* directory dependencies. The default `opts.dirPacker` does not execute
* `prepare` scripts, even though npm itself does.
*/
dirPacker?: (dir: string) => Readable;
/**
* If passed in, will be used while resolving to filter the versions for
* **registry dependencies** such that versions published **after**
* `opts.enjoy-by` are not considered -- as if they'd never been published.
*/
'enjoy-by'?: Date | string | number;
/** Alias for `enjoy-by` */
enjoyBy?: Date | string | number;
/** Alias for `enjoy-by` */
before?: Date | string | number;
/**
* If false, deprecated versions will be skipped when selecting from
* registry range specifiers. If true, deprecations do not affect version
* selection.
*/
'include-deprecated'?: boolean;
/** Alias for 'include-deprecated' */
includeDeprecated?: boolean;
/**
* If `true`, the full packument will be fetched when doing metadata
* requests. By default, pacote only fetches the summarized packuments, also
* called "corgis".
*/
'full-metadata'?: boolean;
/**
* Package version resolution tag. When processing registry spec ranges,
* this option is used to determine what dist-tag to treat as "latest". For
* more details about how `pacote` selects versions and how `tag` is
* involved, see [the documentation for `npm-pick-manifest`](https://npm.im/npm-pick-manifest).
*/
tag?: string;
/** Alias for `tag` */
defaultTag?: string;
/**
* When fetching tarballs, this option can be passed in to skip registry
* metadata lookups when downloading tarballs. If the string is a `file:`
* URL, pacote will try to read the referenced local file before attempting
* to do any further lookups. This option does not bypass integrity checks
* when `opts.integrity` is passed in.
*/
resolved?: string;
/**
* Passed as an argument to [`npm-package-arg`](https://npm.im/npm-package-arg)
* when resolving `spec` arguments. Used to determine what path to resolve
* local path specs relatively from.
*/
where?: string;
}
export type Options = PacoteOptions & npmFetch.Options;

13
types/pacote/manifest.d.ts vendored Normal file
View File

@@ -0,0 +1,13 @@
import { Options, Manifest } from './index';
/**
* Fetches the manifest for a package. Manifest objects are similar and based on
* the `package.json` for that package, but with pre-processed and limited
* fields.
*
* Note that depending on the spec type, some additional fields might be
* present. For example, packages from `registry.npmjs.org` have additional
* metadata appended by the registry.
*/
declare function manifest(spec: string, opts?: Options): Promise<Manifest>;
export = manifest;

15
types/pacote/packument.d.ts vendored Normal file
View File

@@ -0,0 +1,15 @@
import { Options, Packument } from './index';
/**
* Fetches the packument for a package. Packument objects are general metadata
* about a project corresponding to registry metadata, and include version and
* `dist-tag` information about a package's available versions, rather than a
* specific version. It may include additional metadata not usually available
* through the individual package metadata objects.
*
* Note that depending on the spec type, some additional fields might be
* present. For example, packages from `registry.npmjs.org` have additional
* metadata appended by the registry.
*/
declare function packument(spec: string, opts?: Options): Promise<Packument>;
export = packument;

View File

@@ -0,0 +1,57 @@
import { Readable } from 'stream';
import pacote = require('pacote');
import extract = require('pacote/extract');
import manifest = require('pacote/manifest');
import packument = require('pacote/packument');
import prefetch = require('pacote/prefetch');
import tarball = require('pacote/tarball');
const opts: pacote.Options = {
dirPacker: _dir => new Readable(),
'enjoy-by': new Date(1970, 1),
'include-deprecated': false,
'full-metadata': false,
tag: 'latest',
resolved: 'file://local/path',
where: './',
registry: 'https://registry.npmjs.org',
cache: './cache',
};
pacote.manifest('pacote'); // $ExpectType Promise<Manifest>
pacote.manifest('pacote', opts); // $ExpectType Promise<Manifest>
manifest('pacote'); // $ExpectType Promise<Manifest>
manifest('pacote', opts); // $ExpectType Promise<Manifest>
pacote.packument('pacote'); // $ExpectType Promise<Packument>
pacote.packument('pacote', opts); // $ExpectType Promise<Packument>
packument('pacote'); // $ExpectType Promise<Packument>
packument('pacote', opts); // $ExpectType Promise<Packument>
pacote.extract('pacote', './'); // $ExpectType Promise<void>
pacote.extract('pacote', './', opts); // $ExpectType Promise<void>
extract('pacote', './'); // $ExpectType Promise<void>
extract('pacote', './', opts); // $ExpectType Promise<void>
pacote.tarball('pacote'); // $ExpectType Promise<Buffer>
pacote.tarball('pacote', opts); // $ExpectType Promise<Buffer>
pacote.tarball.stream('pacote'); // $ExpectType PassThrough
pacote.tarball.stream('pacote', opts); // $ExpectType PassThrough
pacote.tarball.toFile('pacote', './pacote.tgz'); // $ExpectType Promise<void>
pacote.tarball.toFile('pacote', './pacote.tgz', opts); // $ExpectType Promise<void>
tarball('pacote'); // $ExpectType Promise<Buffer>
tarball('pacote', opts); // $ExpectType Promise<Buffer>
tarball.stream('pacote'); // $ExpectType PassThrough
tarball.stream('pacote', opts); // $ExpectType PassThrough
tarball.toFile('pacote', './pacote.tgz'); // $ExpectType Promise<void>
tarball.toFile('pacote', './pacote.tgz', opts); // $ExpectType Promise<void>
pacote.prefetch('pacote'); // $ExpectType Promise<void>
pacote.prefetch('pacote', opts); // $ExpectType Promise<void>
prefetch('pacote'); // $ExpectType Promise<void>
prefetch('pacote', opts); // $ExpectType Promise<void>
pacote.clearMemoized(); // $ExpectType void

10
types/pacote/prefetch.d.ts vendored Normal file
View File

@@ -0,0 +1,10 @@
import { Options } from './index';
/**
* @deprecated * **THIS API IS DEPRECATED. USE pacote.tarball() INSTEAD**
*
* Fetches package data identified by `spec`, usually for the purpose of warming
* up the local package cache (with `opts.cache`). It does not return anything.
*/
declare function prefetch(spec: string, opts?: Options): Promise<void>;
export = prefetch;

23
types/pacote/tarball.d.ts vendored Normal file
View File

@@ -0,0 +1,23 @@
import { Options } from './index';
import { PassThrough } from 'stream';
/**
* Fetches package data identified by `spec` and returns the data as a buffer.
*/
declare function tarball(spec: string, opts?: Options): Promise<Buffer>;
declare namespace tarball {
/**
* Same as `pacote.tarball`, except it returns a stream instead of a Promise.
*/
function stream(spec: string, opts?: Options): PassThrough;
/**
* Like `pacote.tarball`, but instead of returning data directly, data will
* be written directly to `dest`, and create any required directories along
* the way.
*/
function toFile(spec: string, dest: string, opts?: Options): Promise<void>;
}
export = tarball;

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictFunctionTypes": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"extract.d.ts",
"index.d.ts",
"manifest.d.ts",
"packument.d.ts",
"pacote-tests.ts",
"prefetch.d.ts",
"tarball.d.ts"
]
}

1
types/pacote/tslint.json Normal file
View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }