# jg-package-check

> Inspect npm tarballs without extraction, then check an installed package’s public exports in disposable npm or pnpm consumers.

- **Version:** `1.0.0`
- **Runtimes:** Node.js
- **Install:** `npm install jg-package-check`
- **On npm:** [jg-package-check](https://www.npmjs.com/package/jg-package-check)
- **Source:** [packages/jg-package-check](https://github.com/jesusgraterol/jg-packages/tree/main/packages/jg-package-check)
- **Recipes:** [jg-package-check recipes](https://jg-packages.jesusgraterol.dev/packages/jg-package-check/recipes/index.md)

## Usage

- `inspectNpmTarball` reads a bounded gzip archive and returns a map of package-relative names to their raw file bytes. It checks the npm root, portable paths, unique files and clean termination. The input must be a regular-file npm tarball. Directory and link entries and extended tar metadata are rejected.
- `withPackedConsumer` installs local tarballs in a temporary ESM project with npm or pnpm and disables lifecycle scripts. It removes the project when the checks finish or fail. The optional `prepare` callback can write fixture configuration inside the project.
- `checkPackedExports` looks for unpublished `workspace:` and `catalog:` ranges, imports the named public subpaths and verifies that Node.js refuses the named private subpaths.

Use tarball inspection before installation. Export checks run the installed package's code. Use artifacts from a source you trust and avoid changing them during qualification. The caller defines the allowed archive files and owns CLI, type, application and release checks.

## Errors

| Code                             | Message                                |
| -------------------------------- | -------------------------------------- |
| `INVALID_NPM_TARBALL`            | The npm tarball is invalid.            |
| `PACKED_CONSUMER_SETUP_FAILED`   | Unable to prepare the packed consumer. |
| `PACKED_CONSUMER_CLEANUP_FAILED` | Unable to remove the packed consumer.  |

A cleanup error includes the temporary path in `data.directory`. Its cause preserves an earlier callback or setup failure if both operations failed. A callback error propagates after successful cleanup.

## <a id="api-reference"></a>jg-package-check API reference

Every export of `jg-package-check@1.0.0`, 9 in all, with its signature, its errors, and an example. It's generated from the package's TSDoc.

- Functions: [`checkPackedExports`](#api-checkPackedExports), [`inspectNpmTarball`](#api-inspectNpmTarball), [`withPackedConsumer`](#api-withPackedConsumer)
- Constants: [`ERRORS`](#api-ERRORS)
- Types: [`INpmTarballLimits`](#api-INpmTarballLimits), [`IPackedConsumer`](#api-IPackedConsumer), [`IPackedConsumerManager`](#api-IPackedConsumerManager), [`IPackedConsumerOptions`](#api-IPackedConsumerOptions), [`IPackedExportCheck`](#api-IPackedExportCheck)

### <a id="api-functions"></a>Functions

#### <a id="api-checkPackedExports"></a>`checkPackedExports`

*Function*

Checks unpublished workspace/catalog ranges, imports the requested public subpaths through Node, and requires the package export map to reject each private subpath. Import checks execute the installed package, so use a trusted artifact. CLI, type and browser checks are caller-owned.

```ts
checkPackedExports(
  consumer: IPackedConsumer,
  options: IPackedExportCheck,
): Promise<string[]>
```

**Parameters**

- `consumer` `IPackedConsumer`: An installed temporary consumer.
- `options` `IPackedExportCheck`: The name and paths to check. A root export is specified as `.`. The caller's signal reason propagates if it interrupts an import check.

**Returns** `Promise<string[]>`: Diagnostics, or an empty array when all requested checks pass.

**Example**

```ts
import { resolve } from 'node:path';
import { checkPackedExports, withPackedConsumer } from 'jg-package-check';

await withPackedConsumer(
  { packageManager: 'npm', tarballs: [resolve('jg-example-1.0.0.tgz')] },
  (consumer) => checkPackedExports(consumer, {
    packageName: 'jg-example',
    importSubpaths: ['.', './format'],
    privateSubpaths: ['./dist/internal.js'],
  }),
);
```

#### <a id="api-inspectNpmTarball"></a>`inspectNpmTarball`

*Function*

Parses a bounded npm tarball in memory without extracting it. Requires a gzip archive containing regular files below `package/`, including `package/package.json`. Returned file names omit `package/` and the file bytes are views into the bounded decompressed buffer.

```ts
inspectNpmTarball(
  compressed: Uint8Array,
  limits?: Partial<INpmTarballLimits>,
): Promise<Map<string, Buffer<ArrayBufferLike>>>
```

**Parameters**

- `compressed` `Uint8Array`: The complete gzip tarball bytes.
- `limits?` `Partial<INpmTarballLimits>`: Limits in bytes and entries. Defaults to 16 MiB compressed, 32 MiB expanded, 8 MiB per file and 4096 files. Expanded size is capped at 256 MiB. Defaults to `{}`.

**Returns** `Promise<Map<string, Buffer<ArrayBufferLike>>>`: A map of relative file names to their contents in archive order.

**Throws**

- `INVALID_NPM_TARBALL`: The npm tarball is invalid.

**Example**

```ts
import { inspectNpmTarball } from 'jg-package-check';
import { readBoundedFile } from 'jg-fs';

const bytes = await readBoundedFile('jg-example-1.0.0.tgz', 16 * 1024 * 1024);
const files = await inspectNpmTarball(bytes);
files.get('package.json'); // the manifest bytes
```

#### <a id="api-withPackedConsumer"></a>`withPackedConsumer`

*Function*

Installs absolute local tarball paths using npm or pnpm with lifecycle scripts disabled. Creates a fresh ESM project, optionally lets the caller configure it, and removes it after the callback settles. Use committed, trusted package artifacts. The callback owns its verification commands.

```ts
withPackedConsumer<T>(
  options: IPackedConsumerOptions,
  check: (consumer: IPackedConsumer) => Promise<T>,
): Promise<T>
```

**Parameters**

- `options` `IPackedConsumerOptions`: Installation, optional fixture preparation, and process settings.
- `check` `(consumer: IPackedConsumer) => Promise<T>`: The checks to run inside the installed consumer.

**Returns** `Promise<T>`: The callback's result after the consumer has been removed.

**Throws**

- `PACKED_CONSUMER_SETUP_FAILED`: Unable to prepare the packed consumer.
- `PACKED_CONSUMER_CLEANUP_FAILED`: Unable to remove the packed consumer.

**Example**

```ts
import { resolve } from 'node:path';
import { checkPackedExports, withPackedConsumer } from 'jg-package-check';

const tarball = resolve('jg-example-1.0.0.tgz');
await withPackedConsumer({ packageManager: 'npm', tarballs: [tarball] }, (consumer) =>
  checkPackedExports(consumer, { packageName: 'jg-example', importSubpaths: ['.'] }),
);
```

### <a id="api-constants"></a>Constants

#### <a id="api-ERRORS"></a>`ERRORS`

*Constant*

the stable codes for the package's own failures

```ts
const ERRORS: { INVALID_NPM_TARBALL: "INVALID_NPM_TARBALL"; PACKED_CONSUMER_SETUP_FAILED: "PACKED_CONSUMER_SETUP_FAILED"; PACKED_CONSUMER_CLEANUP_FAILED: "PACKED_CONSUMER_CLEANUP_FAILED" }
```

### <a id="api-types"></a>Types

#### <a id="api-INpmTarballLimits"></a>`INpmTarballLimits`

*Type*

limits for one npm tarball; numbers are positive safe integers

```ts
type INpmTarballLimits = {
    compressedBytes: number;
    expandedBytes: number;
    entryBytes: number;
    entries: number;
};
```

**Members**

- `compressedBytes: number` (property)
- `expandedBytes: number` (property)
- `entryBytes: number` (property)
- `entries: number` (property)

#### <a id="api-IPackedConsumer"></a>`IPackedConsumer`

*Type*

the temporary ESM project and the environment for commands run in it

```ts
type IPackedConsumer = {
    directory: string;
    env: NodeJS.ProcessEnv;
    signal?: AbortSignal;
};
```

**Members**

- `directory: string` (property)
- `env: NodeJS.ProcessEnv` (property)
- `signal: AbortSignal` (property)

#### <a id="api-IPackedConsumerManager"></a>`IPackedConsumerManager`

*Type*

npm and pnpm have tested, shell-free install commands and script refusal

```ts
type IPackedConsumerManager = 'npm' | 'pnpm';
```

#### <a id="api-IPackedConsumerOptions"></a>`IPackedConsumerOptions`

*Type*

setup options for one temporary consumer

```ts
type IPackedConsumerOptions = {
    packageManager: IPackedConsumerManager;
    tarballs: string[];
    additionalPackages?: string[];
    env?: NodeJS.ProcessEnv;
    signal?: AbortSignal;
    installTimeoutSeconds?: number;
    offline?: boolean;
    prepare?: (consumer: IPackedConsumer) => Promise<void>;
};
```

**Members**

- `packageManager: IPackedConsumerManager` (property)
- `tarballs: string[]` (property)
- `additionalPackages: string[]` (property)
- `env: NodeJS.ProcessEnv` (property)
- `signal: AbortSignal` (property)
- `installTimeoutSeconds: number` (property)
- `offline: boolean` (property)
- `prepare: (consumer: IPackedConsumer) => Promise<void>` (property)

#### <a id="api-IPackedExportCheck"></a>`IPackedExportCheck`

*Type*

the package name and the root (.) or subpaths (./name) to exercise in Node.js

```ts
type IPackedExportCheck = {
    packageName: string;
    importSubpaths?: string[];
    privateSubpaths?: string[];
    timeoutSeconds?: number;
};
```

**Members**

- `packageName: string` (property)
- `importSubpaths: string[]` (property)
- `privateSubpaths: string[]` (property)
- `timeoutSeconds: number` (property)
