npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

shardcloud-sdk

v0.1.0

Published

SDK TypeScript (Node 18+) para consumir a API da ShardCloud

Readme

shardcloud-sdk

SDK TypeScript (Node 18+) para consumir a API da ShardCloud via fetch, com autenticação Bearer e mapeamento dos endpoints documentados.

  • Base URL padrão: https://shardcloud.app/api
  • Auth header: Authorization: Bearer <token>

Instalação

Opção A) Usar localmente (do jeito que o projeto está aqui)

  1. Entre na pasta do SDK
  2. Instale dependências
  3. Build
npm install
npm run build

Se você quiser importar esse SDK em outro projeto local, você pode:

  • apontar no package.json do outro projeto com "shardcloud-sdk": "file:../caminho/para/shardcloud-sdk"
  • ou publicar no npm depois (não está configurado aqui).

Uso rápido

Autenticação (API mais fácil)

Você pode criar um cliente autenticado assim:

import { ShardCloud } from 'shardcloud-sdk';

const client = ShardCloud.auth({
  token: process.env.SHARDCLOUD_API_TOKEN!,
});

Aliases disponíveis:

  • ShardCloud.auth({ token })
  • ShardCloud.autenticar({ token })

Configuração opcional

import { ShardCloud } from 'shardcloud-sdk';

const client = ShardCloud.auth({
  token: process.env.SHARDCLOUD_API_TOKEN!,
  baseUrl: 'https://shardcloud.app/api',
  timeoutMs: 30_000,
});

Tratamento de erros

O SDK lança exceções em falhas de rede/timeout e quando a API responde com HTTP != 2xx.

Erros principais:

  • ShardCloudHttpError: quando response.ok === false
    • contém status, url e bodyText (quando disponível)
  • ShardCloudAbortError: quando estoura o timeout (timeoutMs)

Exemplo:

import { ShardCloud, ShardCloudHttpError } from 'shardcloud-sdk';

const client = ShardCloud.auth({ token: process.env.SHARDCLOUD_API_TOKEN! });

try {
  const apps = await client.apps.list();
  console.log(apps);
} catch (err) {
  if (err instanceof ShardCloudHttpError) {
    console.error('HTTP error', err.status, err.url);
    console.error('Body:', err.bodyText);
  } else {
    console.error('Unknown error', err);
  }
}

Referência completa (métodos do SDK)

Abaixo está o mapeamento direto entre os métodos do SDK e os endpoints presentes na documentação:

Databases

  • client.databases.list()
    • GET /databases
  • client.databases.create(req)
    • POST /databases
    • body JSON:
      • type: 'postgres' | 'mongo' | 'redis'
      • ram: number (docs indicam >= 512)
      • password: string
      • name: string
      • visualizer?: boolean
  • client.databases.get(databaseId)
    • GET /databases/{database_id}
  • client.databases.delete(databaseId)
    • DELETE /databases/{database_id}
  • client.databases.updateResources(databaseId, req)
    • PUT /databases/{database_id}/resources
    • body JSON: { ram?: number; vcpu?: number }
  • client.databases.changePassword(databaseId, req)
    • PUT /databases/{database_id}/password
    • body JSON: { password: string }
  • client.databases.replicaStatus(databaseId)
    • GET /databases/{database_id}/status
  • client.databases.retrySetup(databaseId)
    • POST /databases/{database_id}/retry-setup
  • client.databases.initialize(databaseId)
    • POST /databases/{database_id}/initialize
  • client.databases.stop(databaseId)
    • POST /databases/{database_id}/stop
  • client.databases.metrics(databaseId, { minutes? })
    • GET /databases/{database_id}/metrics?minutes=<n>
    • Obs.: a docs só descreve “Number of minutes for metrics data”; o SDK expõe minutes?: number.
  • client.databases.connectionUrl(databaseId)
    • GET /databases/{database_id}/connection-url

Exemplos (Databases)

Listar databases:

import { ShardCloud } from 'shardcloud-sdk';

const client = ShardCloud.auth({ token: process.env.SHARDCLOUD_API_TOKEN! });
const dbs = await client.databases.list();
console.log(dbs);

Criar um Postgres:

import { ShardCloud } from 'shardcloud-sdk';

const client = ShardCloud.auth({ token: process.env.SHARDCLOUD_API_TOKEN! });

await client.databases.create({
  type: 'postgres',
  ram: 512,
  password: 'sua_senha_forte',
  name: 'meu-db',
  visualizer: true,
});

Pegar connection URL:

const info = await client.databases.connectionUrl(databaseId);
console.log(info.connection_url);
console.log(info.visualizer_url);

Apps

  • client.apps.list()
    • GET /apps
  • client.apps.create(zipFile)
    • POST /apps
    • multipart/form-data com campo project (ZIP, max 100MB)
  • client.apps.get(appId)
    • GET /apps/{app_id}
  • client.apps.delete(appId)
    • DELETE /apps/{app_id}
  • client.apps.updateResources(appId, req)
    • PUT /apps/{app_id}/resources
    • body JSON:
      • name?, description?, subdomain?, ram?, vcpu?, custom_command?, entrypoint?
  • client.apps.updateCode(appId, zipFile)
    • PUT /apps/{app_id}/file
    • multipart/form-data com campo project (ZIP, max 100MB)
  • client.apps.deployments(appId)
    • GET /apps/{app_id}/deploys
  • client.apps.status(appId)
    • GET /apps/{app_id}/status
  • client.apps.updateStatus(appId, { status })
    • POST /apps/{app_id}/status
    • body JSON: { status: 'run' | 'stop' | 'restart' }
  • client.apps.logs(appId)
    • GET /apps/{app_id}/logs
    • retorna string
    • Obs.: a docs menciona SSE, mas este método retorna o text() completo. Para streaming real, precisaria consumir ReadableStream.
  • client.apps.metrics(appId, { minutes? })
    • GET /apps/{app_id}/metrics?minutes=<n>
  • client.apps.fileContent(appId, path)
    • GET /apps/{app_id}/file/content?path=<path>
  • client.apps.files(appId, dir?)
    • GET /apps/{app_id}/files?dir=<dir>
  • client.apps.createFile(appId, { path, content })
    • POST /apps/{app_id}/files
  • client.apps.deletePath(appId, path)
    • DELETE /apps/{app_id}/files?path=<path>
  • client.apps.moveFile(appId, { path, new_path })
    • PATCH /apps/{app_id}/files
  • client.apps.getCustomDomain(appId)
    • GET /apps/{app_id}/domain
  • client.apps.updateCustomDomain(appId, { custom_domain })
    • POST /apps/{app_id}/domain
  • client.apps.deleteCustomDomain(appId)
    • DELETE /apps/{app_id}/domain
  • client.apps.clearCustomDomainCache(appId)
    • DELETE /apps/{app_id}/domain/cache
  • client.apps.getDeployToken(appId)
    • GET /apps/{app_id}/deploy-token
  • client.apps.deployTokenFlow(appId, token)
    • POST /apps/{app_id}/deploy-token?token=<token>
    • Obs.: a docs indica query param “Deploy token”; o SDK usa token.
  • client.apps.deleteDeployToken(appId)
    • DELETE /apps/{app_id}/deploy-token

Exemplos (Apps)

Criar um app a partir de ZIP:

import { readFile } from 'node:fs/promises';
import { ShardCloud } from 'shardcloud-sdk';

const client = ShardCloud.auth({ token: process.env.SHARDCLOUD_API_TOKEN! });

const zipBytes = await readFile('./meu-projeto.zip');
const zipFile = new Blob([zipBytes], { type: 'application/zip' });

const created = await client.apps.create(zipFile);
console.log('App ID:', created.id);

Atualizar código (deploy) com ZIP:

const zipBytes = await readFile('./meu-projeto.zip');
const zipFile = new Blob([zipBytes], { type: 'application/zip' });

await client.apps.updateCode(appId, zipFile);

Rodar / parar / restart:

await client.apps.updateStatus(appId, { status: 'restart' });

Listar arquivos:

const entries = await client.apps.files(appId, '/');
console.log(entries);

Criar arquivo:

await client.apps.createFile(appId, {
  path: '/README.txt',
  content: 'hello',
});

Mover arquivo:

await client.apps.moveFile(appId, {
  path: '/README.txt',
  new_path: '/docs/README.txt',
});

Deletar path:

await client.apps.deletePath(appId, '/docs/README.txt');

Custom domain:

await client.apps.updateCustomDomain(appId, { custom_domain: 'app.seudominio.com' });
const domainInfo = await client.apps.getCustomDomain(appId);
console.log(domainInfo);

Deploy token:

const { token } = await client.apps.getDeployToken(appId);
console.log(token);

const updated = await client.apps.deployTokenFlow(appId, token);
console.log(updated);

await client.apps.deleteDeployToken(appId);

Tipos

Os tipos exportados ficam em src/types.ts. Principais:

  • ShardCloudClient
  • Database, DatabaseWithInfo
  • App, AppWithInfo
  • CreateDatabaseRequest, UpdateDatabaseResourcesRequest, etc.

Observações importantes

  • Logs SSE: o endpoint é descrito como SSE na docs, mas este SDK expõe apps.logs() como retorno string. Se você quiser streaming real, eu implemento um método apps.streamLogs() baseado em ReadableStream.
  • Query params (metrics/dir/path): a docs não mostra claramente os nomes em todos os lugares. Eu segui o que aparece no curl e o que é usual:
    • metrics: minutes
    • file content: path
    • list files: dir
    • delete file/dir: path
    • deploy-token-flow: token

Build

npm run build