Registry / http-networking / pear-api

pear-api

JSON →
library1.30.0jsnpmunverified

The `pear-api` package provides the foundational base class for interacting with the Pear API, which is part of the Holepunch peer-to-peer (P2P) runtime and development platform. Currently at version 1.30.0, this library enables developers to build P2P applications, particularly focusing on User Interface integrations by abstracting complex underlying P2P mechanisms. The Pear ecosystem is actively maintained, with regular updates to its 1.x branch and a significant transition underway to a version 2, which introduces notable breaking changes and a shift towards modern JavaScript module standards. Key differentiators include its focus on enabling local-first, offline-first P2P applications and its design for extensibility within UI environments like Electron.

npm install pear-api
INSTALL
IMPORT
SIG · PEAR-API
P
pear-api
http-networkingjavascriptv1.30.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

PearAPI
import { PearAPI } from 'pear-api';
const PearAPI = require('pear-api');
The primary API base class is typically imported as a named export. While v1 supports CommonJS, future major versions (v2+) are moving towards ESM-only.
Config
import { Config } from 'pear-api';
import Config from 'pear-api/config';
Configuration utilities are often named exports from the main package or a subpath. Avoid direct subpath imports unless explicitly documented.
PearError
import { PearError } from 'pear-api';
const { PearError } = require('pear-api');
Custom error classes or types related to the API are usually named exports. Ensure you're using ESM syntax for modern applications.

This quickstart demonstrates how to extend the `PearAPI` base class to create a custom P2P application API, handle connection, and publish data, including error handling and simulated asynchronous operations.

import { PearAPI } from 'pear-api'; interface MyApiOptions { authToken: string; appId: string; } interface MyP2PData { id: string; message: string; timestamp: number; } class MyPearAppAPI extends PearAPI { private token: string; private appId: string; constructor(options: MyApiOptions) { super(); // Initialize the base PearAPI class this.token = options.authToken; this.appId = options.appId; console.log(`MyPearAppAPI initialized for app: ${this.appId}`); } async connect(): Promise<boolean> { console.log('Attempting to connect to Pear network...'); // Simulate P2P network connection logic await new Promise(resolve => setTimeout(resolve, 1000)); if (!this.token) { console.error('Authentication token is missing.'); return false; } console.log('Successfully connected to Pear network.'); return true; } async publishData(data: MyP2PData): Promise<void> { if (!(await this.connect())) { throw new Error('Failed to connect, cannot publish data.'); } console.log(`Publishing data [${data.id}]: ${data.message} at ${new Date(data.timestamp).toISOString()}`); // Simulate data publishing to the P2P network await new Promise(resolve => setTimeout(resolve, 500)); console.log('Data published.'); } static async createAndRun(token: string): Promise<MyPearAppAPI> { const api = new MyPearAppAPI({ authToken: token, appId: 'my-p2p-app' }); const connected = await api.connect(); if (connected) { await api.publishData({ id: 'msg-1', message: 'Hello P2P world!', timestamp: Date.now() }); } return api; } } // Example usage with a dummy token MyPearAppAPI.createAndRun(process.env.PEAR_AUTH_TOKEN ?? 'dummy_auth_token_123') .then(() => console.log('Pear application flow completed.')) .catch(error => console.error('Pear application error:', error.message));
Debug
Known issues
breakingMigrating from Pear v1 to v2 involves significant breaking changes. Specifically, many UI-related methods have been moved or renamed, and the application entrypoint has changed from supporting HTML in v1 to only JavaScript in v2.
fix
Refer to the official Pear v2 Migration Guide (https://docs.pears.com/api/migration) for detailed steps, including updating your `package.json` entrypoint and adapting to new module structures like `pear-electron` and `pear-bridge`.
affects: >=2.0.0
deprecatedThe `pear run` CLI command has been deprecated in favor of using the `pear-runtime` module for embeddable runtimes with P2P Over-The-Air (OTA) updates.
fix
Transition to using the `pear-runtime` module in your application code for starting and managing the Pear runtime, or consult documentation for the appropriate CLI alternatives for development and deployment.
affects: >=1.10.0
gotchaFuture major versions of Pear modules, including `pear-api`, are increasingly adopting an ESM-only (ECMAScript Modules) export strategy. Projects using CommonJS (`require()`) might encounter `ERR_REQUIRE_ESM`.
fix
Ensure your project is configured for ESM. This often means setting `"type": "module"` in your `package.json`, using `.mjs` file extensions, and updating all `require()` statements to `import` statements. For TypeScript, configure `"module": "NodeNext"` or `"moduleResolution": "NodeNext"` in `tsconfig.json`.
affects: >=2.0.0
gotchaThe `pear-api` package, as a base class for P2P applications, requires careful handling of resource cleanup (e.g., network connections, database instances) during application teardown to prevent hanging processes or resource locks.
fix
Implement proper teardown logic using `Pear.teardown(cb)` and ensure all long-lived resources like Hyperswarm instances (`swarm.destroy()`) or worker pipes (`pipe.end()`) are gracefully closed to prevent resource leaks or application hangs. Refer to Pear troubleshooting documentation for common patterns.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: Class constructor PearAPI cannot be invoked without 'new'
Attempting to call `PearAPI()` directly instead of instantiating it with the `new` keyword.
fix
Always instantiate the `PearAPI` class (or its subclasses) using `new`, e.g., `const api = new PearAPI();` or `class MyAPI extends PearAPI { ... }` then `new MyAPI();`.
ReferenceError: PearAPI is not defined
This typically occurs in a CommonJS environment when an ESM-only version of `pear-api` is used, or the `PearAPI` class was not correctly imported.
fix
Verify that your module import statement is correct (`import { PearAPI } from 'pear-api';`). If you are in a CommonJS context and need an ESM-only module, consider migrating your project to ESM or using dynamic `import()` within an `async` function.
Error: Authentication failed: Invalid API key or token
The base `PearAPI` or its derived classes often require an authentication token or key, which was either missing, expired, or invalid during initialization or an API call.
fix
Ensure that your API key or token is correctly provided during the `PearAPI` constructor or connection method. Double-check its validity, expiration, and required permissions according to your Pear API provider's documentation. Use environment variables for sensitive credentials.
Upgrade
Version history
1.30.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
6 hits · last 30 days
node
6
Resources