@operaris/license-sdk
v1.0.14
Published
SDK para validação de licenças do ERP Operaris
Downloads
2,238
Readme
@operaris/license-sdk
SDK para validação de licenças do Operaris no ERP/PDV.
Instalação
npm install @operaris/license-sdkUso rápido
import { LicenseClient } from '@operaris/license-sdk'
const client = new LicenseClient({
apiUrl: 'https://api.operaris.com.br',
apiKey: process.env.OPERARIS_API_KEY!,
licenseKey: process.env.OPERARIS_LICENSE_KEY!,
})
// Na inicialização do ERP — lança erro se licença inválida
const license = await client.validateOrThrow({
fingerprint: getMachineFingerprint(),
hostname: os.hostname(),
os: process.platform,
})
console.log('Licença válida até:', license.validUntil)
console.log('Máx. dispositivos:', license.maxDevices)Configuração
| Opção | Tipo | Padrão | Descrição |
|---------------|----------|----------|--------------------------------------------------------|
| apiUrl | string | — | URL base da API Operaris (obrigatório) |
| apiKey | string | — | Chave de API fornecida pela Operaris (obrigatório) |
| licenseKey | string | — | Chave da licença do estabelecimento (obrigatório) |
| cacheTtlMs | number | 300000 | TTL do cache em ms (padrão: 5 minutos) |
| timeoutMs | number | 10000 | Timeout da requisição em ms (padrão: 10 segundos) |
| retries | number | 2 | Tentativas em falha de rede (não retenta em 4xx/5xx) |
Métodos
validate(input): Promise<ValidateResult>
Valida a licença. Retorna o resultado do cache se ainda válido (dentro do TTL). Em falha de rede, retorna o último cache como fallback offline (mesmo que expirado).
const result = await client.validate({ fingerprint: '...', hostname: '...', os: '...' })
if (result.valid) {
// result.status — 'ACTIVE' | 'GRACE'
// result.validUntil — Date
// result.graceDaysRemaining — number | undefined
// result.maxDevices — number
// result.features — Record<string, unknown>
// result.establishment — { id, name, city, state }
// result.fromCache — boolean
// result.offlineFallback — boolean (true = API inacessível, usando cache antigo)
} else {
// result.reason — motivo da rejeição
}Valores possíveis de reason:
| Valor | Descrição |
|--------------------------|----------------------------------------------------|
| LICENSE_NOT_FOUND | Licença não existe |
| LICENSE_EXPIRED | Licença expirada (além do período de carência) |
| LICENSE_CANCELLED | Licença cancelada |
| LICENSE_REVOKED | Licença revogada |
| DEVICE_NOT_REGISTERED | Fingerprint não registrado nesta licença |
| MAX_DEVICES_REACHED | Limite de dispositivos atingido |
| DEVICE_INACTIVE | Dispositivo desativado manualmente |
| API_UNREACHABLE | API inacessível e sem cache disponível |
validateOrThrow(input): Promise<ValidateSuccess>
Igual ao validate, mas lança erro se a licença for inválida.
Ideal para bloquear a inicialização do ERP.
try {
const license = await client.validateOrThrow({ fingerprint, hostname, os })
// prossegue normalmente
} catch (err) {
if (err instanceof LicenseValidationError) {
console.error('Licença inválida:', err.reason)
process.exit(1)
}
if (err instanceof LicenseApiUnreachableError) {
console.error('API inacessível e sem cache — verifique a conexão')
process.exit(1)
}
}clearCache(): void
Invalida o cache local, forçando nova consulta na próxima chamada.
Comportamento offline
O SDK mantém um cache em memória do último resultado válido. Em caso de falha de rede:
- Se houver cache (mesmo expirado) → retorna o cache com
offlineFallback: true - Se não houver cache → retorna
{ valid: false, reason: 'API_UNREACHABLE' }
Isso garante que o ERP continue funcionando por um período durante instabilidades de rede.
Erros
import { LicenseValidationError, LicenseApiUnreachableError } from '@operaris/license-sdk'
// LicenseValidationError
err.reason // string — motivo da rejeição
err.message // string — mensagem legível
// LicenseApiUnreachableError
err.message // 'License API is unreachable and no cache is available'Build
npm run build # compila para dist/
npm run dev # watch modeRequisitos
- Node.js >= 20
fetchnativo (disponível a partir do Node 18)
