Compare commits
34 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3a2ad58d1c | |||
| 46782d925b | |||
| e85d725873 | |||
| d90be18e74 | |||
| 5c0e4c6b90 | |||
| 34e2c82e68 | |||
| bc53e9f872 | |||
| 646ab4d18c | |||
| aaeb025217 | |||
| 21e37a7a16 | |||
| 4e0dfb0356 | |||
| 84780647da | |||
| 1645d7881a | |||
| 88351db20f | |||
| 18cbf8693f | |||
| 7d64a2bc4d | |||
| 4c327e5e32 | |||
| a898928bd3 | |||
| aba8182422 | |||
| 5412ab524b | |||
| 2f175e9d64 | |||
| d2b1018234 | |||
| e7babf5222 | |||
| 63660ecc03 | |||
| 336e27f383 | |||
| 9174571ea4 | |||
| 4a722b79b7 | |||
| 866dc35403 | |||
| 84d74a131a | |||
| 929404fadd | |||
| 332a4a4195 | |||
| 07d625fa1f | |||
| e7cafd9c1c | |||
| 60725ecdcb |
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"@git.zone/cli": {
|
||||
"projectType": "npm",
|
||||
"module": {
|
||||
"githost": "gitlab.com",
|
||||
"gitscope": "apiclient.xyz",
|
||||
"gitrepo": "hetznercloud",
|
||||
"description": "An unofficial TypeScript API client for the Hetzner Cloud API providing easy methods to manage servers, volumes, and firewalls.",
|
||||
"npmPackagename": "@apiclient.xyz/hetznercloud",
|
||||
"license": "MIT",
|
||||
"projectDomain": "apiclient.xyz",
|
||||
"keywords": [
|
||||
"Hetzner",
|
||||
"Cloud",
|
||||
"API",
|
||||
"TypeScript",
|
||||
"Client",
|
||||
"Servers",
|
||||
"Volumes",
|
||||
"Firewalls",
|
||||
"Automation",
|
||||
"DevOps",
|
||||
"Cloud Infrastructure"
|
||||
]
|
||||
},
|
||||
"release": {
|
||||
"registries": [
|
||||
"https://verdaccio.lossless.digital",
|
||||
"https://registry.npmjs.org"
|
||||
],
|
||||
"accessLevel": "public"
|
||||
}
|
||||
},
|
||||
"@ship.zone/szci": {
|
||||
"npmGlobalTools": []
|
||||
}
|
||||
}
|
||||
Vendored
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"json.schemas": [
|
||||
{
|
||||
"fileMatch": ["/npmextra.json"],
|
||||
"fileMatch": ["/.smartconfig.json"],
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# Changelog
|
||||
|
||||
## 2026-05-07 - 1.2.1 - fix(client)
|
||||
update request handling and typings for current smartrequest and OpenAPI output
|
||||
|
||||
- migrate HetznerAccount requests to the SmartRequest builder API and normalize responses to statusCode/body
|
||||
- adjust generated request and resource types for nullable OpenAPI fields and JSON request bodies
|
||||
- make live API tests skip cleanly when the Hetzner token is missing or rejected
|
||||
- refresh package tooling and project metadata configuration files
|
||||
|
||||
## 2024-06-15 - 1.2.0 - release
|
||||
Release published with no additional user-facing changes beyond recent updates already included below.
|
||||
|
||||
- Version 1.2.0 tags the current state without introducing separate documented changes.
|
||||
|
||||
## 2024-06-15 - 1.1.1 - openapi
|
||||
Integrated OpenAPI directly into the repository.
|
||||
|
||||
- Added OpenAPI assets and related integration directly to the repo.
|
||||
|
||||
## 2024-06-15 - 1.1.0 - core
|
||||
Applied a core update.
|
||||
|
||||
- Updated core functionality and internal project behavior.
|
||||
|
||||
## 2024-06-15 - 1.0.18 - volumes and firewalls
|
||||
Added support for managing volumes and firewalls.
|
||||
|
||||
- Enabled volumes management.
|
||||
- Enabled firewalls management.
|
||||
|
||||
## 2024-01-29 - 1.0.1 to 1.0.17 - core
|
||||
Series of trivial core update releases between 1.0.1 and 1.0.17.
|
||||
|
||||
- Repeated maintenance-level `fix(core): update` changes were released across versions 1.0.1 through 1.0.17.
|
||||
- Individual entries are summarized here to avoid duplicating minimal, non-descriptive updates.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Task Venture Capital GmbH
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,18 +0,0 @@
|
||||
{
|
||||
"gitzone": {
|
||||
"projectType": "npm",
|
||||
"module": {
|
||||
"githost": "gitlab.com",
|
||||
"gitscope": "apiclient.xyz",
|
||||
"gitrepo": "hetznercloud",
|
||||
"description": "an unofficial api client for the hetzner cloud api",
|
||||
"npmPackagename": "@apiclient.xyz/hetznercloud",
|
||||
"license": "MIT",
|
||||
"projectDomain": "apiclient.xyz"
|
||||
}
|
||||
},
|
||||
"npmci": {
|
||||
"npmGlobalTools": [],
|
||||
"npmAccessLevel": "public"
|
||||
}
|
||||
}
|
||||
+27
-12
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"name": "@apiclient.xyz/hetznercloud",
|
||||
"version": "1.0.5",
|
||||
"version": "1.2.1",
|
||||
"private": false,
|
||||
"description": "an unofficial api client for the hetzner cloud api",
|
||||
"description": "An unofficial TypeScript API client for the Hetzner Cloud API providing easy methods to manage servers, volumes, and firewalls.",
|
||||
"main": "dist_ts/index.js",
|
||||
"typings": "dist_ts/index.d.ts",
|
||||
"type": "module",
|
||||
@@ -12,19 +12,21 @@
|
||||
"test": "(tstest test/ --web)",
|
||||
"build": "(tsbuild --web --allowimplicitany)",
|
||||
"buildDocs": "(tsdoc)",
|
||||
"create": "openapi-generator-cli generate -i https://docs.hetzner.cloud/spec.json -g typescript-node -o ts_openapi"
|
||||
"updateOpenapi": "openapi-typescript https://docs.hetzner.cloud/spec.json --output ts/openapi.spec.ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@git.zone/tsbuild": "^2.1.25",
|
||||
"@git.zone/tsbundle": "^2.0.5",
|
||||
"@git.zone/tsrun": "^1.2.46",
|
||||
"@git.zone/tstest": "^1.0.44",
|
||||
"@push.rocks/tapbundle": "^5.0.15",
|
||||
"@types/node": "^20.8.7"
|
||||
"@git.zone/tsbuild": "^4.4.0",
|
||||
"@git.zone/tsbundle": "^2.10.1",
|
||||
"@git.zone/tsrun": "^2.0.3",
|
||||
"@git.zone/tstest": "^3.6.3",
|
||||
"@push.rocks/qenv": "^6.1.4",
|
||||
"@types/node": "^25.6.2",
|
||||
"openapi-typescript": "^7.13.0",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@push.rocks/smartrequest": "^2.0.21",
|
||||
"@tempfix/hetzner-openapi": "^1.0.4"
|
||||
"@push.rocks/smartrequest": "^5.0.3",
|
||||
"@tsclass/tsclass": "^9.5.1"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -46,7 +48,20 @@
|
||||
"dist_ts_web/**/*",
|
||||
"assets/**/*",
|
||||
"cli.js",
|
||||
"npmextra.json",
|
||||
".smartconfig.json",
|
||||
"readme.md"
|
||||
],
|
||||
"keywords": [
|
||||
"Hetzner",
|
||||
"Cloud",
|
||||
"API",
|
||||
"TypeScript",
|
||||
"Client",
|
||||
"Servers",
|
||||
"Volumes",
|
||||
"Firewalls",
|
||||
"Automation",
|
||||
"DevOps",
|
||||
"Cloud Infrastructure"
|
||||
]
|
||||
}
|
||||
|
||||
Generated
+6935
-4956
File diff suppressed because it is too large
Load Diff
@@ -1,39 +1,265 @@
|
||||
# @apiclient.xyz/hetznercloud
|
||||
an unofficial api client for the hetzner cloud api
|
||||
|
||||
## Availabililty and Links
|
||||
* [npmjs.org (npm package)](https://www.npmjs.com/package/@apiclient.xyz/hetznercloud)
|
||||
* [gitlab.com (source)](https://gitlab.com/apiclient.xyz/hetznercloud)
|
||||
* [github.com (source mirror)](https://github.com/apiclient.xyz/hetznercloud)
|
||||
* [docs (typedoc)](https://apiclient.xyz.gitlab.io/hetznercloud/)
|
||||
`@apiclient.xyz/hetznercloud` is an unofficial TypeScript client for the Hetzner Cloud API. It wraps the day-to-day infrastructure primitives this package currently supports - servers, volumes, and firewalls - behind small classes that keep the original Hetzner resource data available while giving you convenient methods for create, list, label-filter, and delete workflows.
|
||||
|
||||
## Status for master
|
||||
## Issue Reporting and Security
|
||||
|
||||
Status Category | Status Badge
|
||||
-- | --
|
||||
GitLab Pipelines | [](https://lossless.cloud)
|
||||
GitLab Pipline Test Coverage | [](https://lossless.cloud)
|
||||
npm | [](https://lossless.cloud)
|
||||
Snyk | [](https://lossless.cloud)
|
||||
TypeScript Support | [](https://lossless.cloud)
|
||||
node Support | [](https://nodejs.org/dist/latest-v10.x/docs/api/)
|
||||
Code Style | [](https://lossless.cloud)
|
||||
PackagePhobia (total standalone install weight) | [](https://lossless.cloud)
|
||||
PackagePhobia (package size on registry) | [](https://lossless.cloud)
|
||||
BundlePhobia (total size when bundled) | [](https://lossless.cloud)
|
||||
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
|
||||
|
||||
## Usage
|
||||
A modern approach to talking to the hetzner API.
|
||||
## Why Use It?
|
||||
|
||||
- TypeScript-first ESM package for Hetzner Cloud automation.
|
||||
- Simple `HetznerAccount` object that owns API token authentication.
|
||||
- Resource classes for `HetznerServer`, `HetznerVolume`, and `HetznerFirewall`.
|
||||
- Label-based lookup helpers for predictable automation runs.
|
||||
- Typed request and response shapes generated from the Hetzner OpenAPI specification.
|
||||
- Escape hatch via `account.request()` whenever you need an endpoint that does not yet have a higher-level class method.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
pnpm add @apiclient.xyz/hetznercloud
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
```typescript
|
||||
import hetznerCloud from '@apiclient.xyz/hetznercloud'
|
||||
const myhetznerAccount = new hetznerCloud.HetznerAccount('myToken');
|
||||
const servers = myhetznerAccount.getServers();
|
||||
for (const server of servers) {
|
||||
await server.delete();
|
||||
import {
|
||||
HetznerAccount,
|
||||
HetznerFirewall,
|
||||
HetznerVolume,
|
||||
} from '@apiclient.xyz/hetznercloud';
|
||||
|
||||
const account = new HetznerAccount('your-hetzner-api-token');
|
||||
|
||||
const server = await account.createServer({
|
||||
name: 'demo-api-01',
|
||||
type: 'cpx31',
|
||||
location: 'nbg1',
|
||||
labels: {
|
||||
app: 'demo-api',
|
||||
environment: 'staging',
|
||||
},
|
||||
userData: '#!/bin/bash\napt-get update',
|
||||
});
|
||||
|
||||
const volume = await HetznerVolume.create(account, {
|
||||
name: 'demo-api-data',
|
||||
size: 25,
|
||||
location: 'nbg1',
|
||||
labels: {
|
||||
app: 'demo-api',
|
||||
environment: 'staging',
|
||||
},
|
||||
server,
|
||||
});
|
||||
|
||||
const firewall = await HetznerFirewall.create(account, {
|
||||
name: 'demo-api-web',
|
||||
labels: {
|
||||
app: 'demo-api',
|
||||
environment: 'staging',
|
||||
},
|
||||
rules: [
|
||||
{
|
||||
direction: 'in',
|
||||
protocol: 'tcp',
|
||||
port: '443',
|
||||
source_ips: ['0.0.0.0/0', '::/0'],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
console.log(server.data);
|
||||
console.log(volume.data);
|
||||
console.log(firewall.data);
|
||||
```
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### Accounts
|
||||
|
||||
`HetznerAccount` stores your Hetzner Cloud API token and exposes the shared request layer used by all resource classes.
|
||||
|
||||
```typescript
|
||||
import { HetznerAccount } from '@apiclient.xyz/hetznercloud';
|
||||
|
||||
const account = new HetznerAccount('your-hetzner-api-token');
|
||||
```
|
||||
|
||||
Available account helpers:
|
||||
|
||||
- `account.getServers()` lists all servers visible to the token.
|
||||
- `account.getServersByLabel(labels)` lists servers and returns exact label matches.
|
||||
- `account.createServer(options)` creates a new server.
|
||||
- `account.request(method, path, payload)` calls the Hetzner Cloud API directly.
|
||||
|
||||
The direct request helper returns an object shaped like this:
|
||||
|
||||
```typescript
|
||||
const response = await account.request('GET', '/servers', {});
|
||||
|
||||
console.log(response.statusCode);
|
||||
console.log(response.body);
|
||||
```
|
||||
|
||||
The current implementation logs request metadata and response bodies to the console, which is useful during automation debugging and important to remember when running with sensitive payloads.
|
||||
|
||||
### Servers
|
||||
|
||||
Servers are represented by `HetznerServer`. The package can create, list, filter, and delete them.
|
||||
|
||||
```typescript
|
||||
const server = await account.createServer({
|
||||
name: 'worker-01',
|
||||
type: 'cpx41',
|
||||
location: 'fsn1',
|
||||
labels: {
|
||||
role: 'worker',
|
||||
},
|
||||
userData: '#!/bin/bash\necho ready',
|
||||
});
|
||||
|
||||
const allServers = await account.getServers();
|
||||
const workerServers = await account.getServersByLabel({ role: 'worker' });
|
||||
|
||||
await server.delete();
|
||||
```
|
||||
|
||||
`createServer()` currently creates Ubuntu 22.04 servers, starts them immediately, and enables public IPv4 and IPv6 networking.
|
||||
|
||||
Supported server type names are:
|
||||
|
||||
```text
|
||||
cx11, cx21, cx31, cx41, cx51,
|
||||
ccx11, ccx21, ccx31, ccx41, ccx51,
|
||||
ccx13, ccx23, ccx33, ccx43, ccx53, ccx63,
|
||||
cpx11, cpx21, cpx31, cpx41, cpx51, cpx61, cpx70, cpx71, cpx90
|
||||
```
|
||||
|
||||
Supported location names are:
|
||||
|
||||
```text
|
||||
fsn1, nbg1, hel1, ash, hil
|
||||
```
|
||||
|
||||
### Volumes
|
||||
|
||||
Volumes are represented by `HetznerVolume`. A volume is created for and attached to an existing `HetznerServer` instance.
|
||||
|
||||
```typescript
|
||||
import { HetznerVolume } from '@apiclient.xyz/hetznercloud';
|
||||
|
||||
const volume = await HetznerVolume.create(account, {
|
||||
name: 'worker-01-data',
|
||||
size: 50,
|
||||
location: 'fsn1',
|
||||
labels: {
|
||||
role: 'worker',
|
||||
},
|
||||
server,
|
||||
});
|
||||
|
||||
const allVolumes = await HetznerVolume.getVolumes(account);
|
||||
const workerVolumes = await HetznerVolume.getVolumesByLabel(account, { role: 'worker' });
|
||||
|
||||
await volume.delete();
|
||||
```
|
||||
|
||||
`HetznerVolume.create()` currently formats new volumes as `xfs` and attaches them to `options.server.data.id`.
|
||||
|
||||
### Firewalls
|
||||
|
||||
Firewalls are represented by `HetznerFirewall`. The package can create firewalls with rules, list them, filter them by label, and delete them.
|
||||
|
||||
```typescript
|
||||
import { HetznerFirewall } from '@apiclient.xyz/hetznercloud';
|
||||
|
||||
const firewall = await HetznerFirewall.create(account, {
|
||||
name: 'web-ingress',
|
||||
labels: {
|
||||
app: 'frontend',
|
||||
},
|
||||
rules: [
|
||||
{
|
||||
direction: 'in',
|
||||
protocol: 'tcp',
|
||||
port: '80',
|
||||
source_ips: ['0.0.0.0/0', '::/0'],
|
||||
},
|
||||
{
|
||||
direction: 'in',
|
||||
protocol: 'tcp',
|
||||
port: '443',
|
||||
source_ips: ['0.0.0.0/0', '::/0'],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const allFirewalls = await HetznerFirewall.getFirewalls(account);
|
||||
const frontendFirewalls = await HetznerFirewall.getFirewallsByLabel(account, { app: 'frontend' });
|
||||
|
||||
await firewall.delete();
|
||||
```
|
||||
|
||||
### Label Filtering
|
||||
|
||||
The label helpers perform exact matches for every key/value pair you pass in. This makes them practical for idempotent automation where labels are your resource ownership contract.
|
||||
|
||||
```typescript
|
||||
const servers = await account.getServersByLabel({
|
||||
app: 'demo-api',
|
||||
environment: 'staging',
|
||||
});
|
||||
```
|
||||
|
||||
## Direct API Access
|
||||
|
||||
Use `account.request()` when you need access to an endpoint that is not wrapped yet. Pass the HTTP method, the API path below `/v1`, and a payload object.
|
||||
|
||||
```typescript
|
||||
const locationsResponse = await account.request('GET', '/locations', {});
|
||||
|
||||
if (locationsResponse.statusCode >= 200 && locationsResponse.statusCode < 300) {
|
||||
console.log(locationsResponse.body);
|
||||
}
|
||||
```
|
||||
|
||||
## Legal
|
||||
> MIT licensed | **©** [Task Venture Capital GmbH](https://task.vc)
|
||||
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
|
||||
For non-`GET` and non-`DELETE` requests, the payload is sent as JSON.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm test
|
||||
pnpm run build
|
||||
```
|
||||
|
||||
Tests use `@git.zone/tstest`. Live Hetzner API tests look for `HETZNER_API_TOKEN`; without a usable token, the live API parts are skipped.
|
||||
|
||||
The OpenAPI types can be refreshed with:
|
||||
|
||||
```bash
|
||||
pnpm run updateOpenapi
|
||||
```
|
||||
|
||||
## License and Legal Information
|
||||
|
||||
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [license](./license) file.
|
||||
|
||||
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
|
||||
|
||||
### Trademarks
|
||||
|
||||
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
|
||||
|
||||
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
|
||||
|
||||
### Company Information
|
||||
|
||||
Task Venture Capital GmbH
|
||||
Registered at District Court Bremen HRB 35230 HB, Germany
|
||||
|
||||
For any legal inquiries or further information, please contact us via email at hello@task.vc.
|
||||
|
||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
||||
|
||||
+69
-6
@@ -1,8 +1,71 @@
|
||||
import { expect, expectAsync, tap } from '@push.rocks/tapbundle';
|
||||
import * as hetznercloud from '../ts/index.js'
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as hetznercloud from '../ts/index.js';
|
||||
import * as qenv from '@push.rocks/qenv';
|
||||
const testQenv = new qenv.Qenv('./', './.nogit/');
|
||||
|
||||
tap.test('first test', async () => {
|
||||
console.log(hetznercloud)
|
||||
})
|
||||
let testAccount: hetznercloud.HetznerAccount | undefined;
|
||||
let liveApiAvailable = false;
|
||||
let liveApiSkipReason = 'HETZNER_API_TOKEN has not been validated.';
|
||||
|
||||
tap.start()
|
||||
tap.test('should create a valid hetzer account', async (toolsArg) => {
|
||||
const token = await testQenv.getEnvVarOnDemand('HETZNER_API_TOKEN');
|
||||
if (!token) {
|
||||
liveApiSkipReason = 'HETZNER_API_TOKEN is not configured.';
|
||||
toolsArg.skip(liveApiSkipReason);
|
||||
return;
|
||||
}
|
||||
testAccount = new hetznercloud.HetznerAccount(token);
|
||||
expect(testAccount).toBeInstanceOf(hetznercloud.HetznerAccount);
|
||||
});
|
||||
|
||||
tap.test('should be able to list all servers', async (toolsArg) => {
|
||||
if (!testAccount) {
|
||||
toolsArg.skip(liveApiSkipReason);
|
||||
return;
|
||||
}
|
||||
const account = testAccount;
|
||||
const tokenCheckResponse = await account.request('GET', '/servers', {});
|
||||
if (tokenCheckResponse.statusCode === 401 || tokenCheckResponse.statusCode === 403) {
|
||||
liveApiSkipReason = 'HETZNER_API_TOKEN was rejected by the Hetzner API.';
|
||||
toolsArg.skip(liveApiSkipReason);
|
||||
return;
|
||||
}
|
||||
if (tokenCheckResponse.statusCode < 200 || tokenCheckResponse.statusCode >= 300) {
|
||||
throw new Error(`Hetzner API returned status ${tokenCheckResponse.statusCode}`);
|
||||
}
|
||||
liveApiAvailable = true;
|
||||
const servers = await account.getServers();
|
||||
expect(servers).toBeArray();
|
||||
console.log(JSON.stringify(servers, null, 2));
|
||||
});
|
||||
|
||||
const testserver = tap.test('should be able to create a server', async (toolsArg) => {
|
||||
if (!liveApiAvailable || !testAccount) {
|
||||
toolsArg.skip(liveApiSkipReason);
|
||||
return;
|
||||
}
|
||||
const newServer = await testAccount.createServer({
|
||||
name: 'testserver',
|
||||
location: 'nbg1',
|
||||
type: 'cpx41',
|
||||
labels: {
|
||||
servezoneId: 'testzone',
|
||||
},
|
||||
});
|
||||
expect(newServer).toBeInstanceOf(hetznercloud.HetznerServer);
|
||||
console.log(newServer);
|
||||
await toolsArg.delayFor(10000);
|
||||
return newServer;
|
||||
});
|
||||
|
||||
tap.test('should be able to delete a server', async (toolsArg) => {
|
||||
if (!liveApiAvailable) {
|
||||
toolsArg.skip(liveApiSkipReason);
|
||||
return;
|
||||
}
|
||||
const testServer: hetznercloud.HetznerServer =
|
||||
await (testserver.testResultPromise as Promise<hetznercloud.HetznerServer>);
|
||||
await testServer.delete();
|
||||
});
|
||||
|
||||
export default tap.start();
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* autocreated commitinfo by @pushrocks/commitinfo
|
||||
* autocreated commitinfo by @push.rocks/commitinfo
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@apiclient.xyz/hetznercloud',
|
||||
version: '1.0.5',
|
||||
description: 'an unofficial api client for the hetzner cloud api'
|
||||
version: '1.2.1',
|
||||
description: 'An unofficial TypeScript API client for the Hetzner Cloud API providing easy methods to manage servers, volumes, and firewalls.'
|
||||
}
|
||||
|
||||
+40
-7
@@ -11,6 +11,14 @@ export class HetznerAccount {
|
||||
return HetznerServer.getServers(this);
|
||||
}
|
||||
|
||||
public async getServersByLabel(labelObject: plugins.tsclass.typeFestOwn.SecondArgument<typeof HetznerServer.getServersByLabel>) {
|
||||
return HetznerServer.getServersByLabel(this, labelObject);
|
||||
}
|
||||
|
||||
public async createServer(optionsArg: plugins.tsclass.typeFestOwn.SecondArgument<typeof HetznerServer.create>) {
|
||||
return HetznerServer.create(this, optionsArg);
|
||||
}
|
||||
|
||||
/**
|
||||
* request things from the hetzner API
|
||||
* @param methodArg
|
||||
@@ -19,13 +27,38 @@ export class HetznerAccount {
|
||||
*/
|
||||
public request = async (methodArg: string, pathArg: string, payloadArg: any) => {
|
||||
const url = `https://api.hetzner.cloud/v1${pathArg}`;
|
||||
const response = await plugins.smartrequest.request(url, {
|
||||
method: methodArg,
|
||||
headers: {
|
||||
console.log(`Url: ${url}`);
|
||||
console.log(`Method: ${methodArg}`);
|
||||
console.log(`Payload: ${JSON.stringify(payloadArg, null, 2)}`);
|
||||
const request = plugins.smartrequest.SmartRequest.create()
|
||||
.url(url)
|
||||
.headers({
|
||||
Authorization: `Bearer ${this.token}`,
|
||||
},
|
||||
requestBody: payloadArg,
|
||||
});
|
||||
return response;
|
||||
})
|
||||
.options({
|
||||
keepAlive: false,
|
||||
});
|
||||
|
||||
if (methodArg !== 'GET' && methodArg !== 'DELETE') {
|
||||
request.json(payloadArg);
|
||||
}
|
||||
|
||||
const response = methodArg === 'POST'
|
||||
? await request.post()
|
||||
: methodArg === 'PUT'
|
||||
? await request.put()
|
||||
: methodArg === 'PATCH'
|
||||
? await request.patch()
|
||||
: methodArg === 'DELETE'
|
||||
? await request.delete()
|
||||
: await request.get();
|
||||
const body = await response.json().catch(() => ({}));
|
||||
const responseObject = {
|
||||
statusCode: response.status,
|
||||
body,
|
||||
};
|
||||
console.log(responseObject.statusCode);
|
||||
console.log(responseObject.body);
|
||||
return responseObject;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
// Hetzner Cloud Firewall Class
|
||||
import type { HetznerAccount } from './classes.account.js';
|
||||
import * as plugins from './hetznercloud.plugins.js';
|
||||
import * as types from './types.js';
|
||||
|
||||
export class HetznerFirewall {
|
||||
// STATIC
|
||||
public static create = async (
|
||||
hetznerAccountRefArg: HetznerAccount,
|
||||
optionsArg: {
|
||||
name: string;
|
||||
labels?: {[key: string]: string},
|
||||
rules: types.TFirewallCreateRequestBody['rules'],
|
||||
}
|
||||
) => {
|
||||
const firewall = new HetznerFirewall(hetznerAccountRefArg);
|
||||
|
||||
const createFirewallUrl = '/firewalls';
|
||||
const createFirewallPayload: types.TFirewallCreateRequestBody = {
|
||||
name: optionsArg.name,
|
||||
labels: optionsArg.labels || {} as any,
|
||||
rules: optionsArg.rules
|
||||
};
|
||||
const response = await firewall.hetznerAccountRef.request(
|
||||
'POST',
|
||||
createFirewallUrl,
|
||||
createFirewallPayload
|
||||
);
|
||||
firewall.data = (response.body as types.TFirewallCreateResponseBody).firewall!;
|
||||
return firewall;
|
||||
}
|
||||
|
||||
public static getFirewalls = async (hetznerAccountRefArg: HetznerAccount) => {
|
||||
const firewallsGetUrl = '/firewalls';
|
||||
const response = await hetznerAccountRefArg.request('GET', firewallsGetUrl, {});
|
||||
const firewallsDataArray = (response.body as types.TFirewallsGetResponseBody).firewalls;
|
||||
const firewalls: HetznerFirewall[] = [];
|
||||
for (const firewallData of firewallsDataArray) {
|
||||
const firewall = new HetznerFirewall(hetznerAccountRefArg);
|
||||
firewall.data = firewallData;
|
||||
firewalls.push(firewall);
|
||||
}
|
||||
return firewalls;
|
||||
}
|
||||
|
||||
public static getFirewallsByLabel = async (hetznerAccountRefArg: HetznerAccount, labelObject: {[key: string]: string}) => {
|
||||
const firewalls = await HetznerFirewall.getFirewalls(hetznerAccountRefArg);
|
||||
const results: HetznerFirewall[] = [];
|
||||
for (const firewall of firewalls) {
|
||||
let isMatch = true;
|
||||
for (const key in labelObject) {
|
||||
if ((firewall.data.labels || {})[key] !== labelObject[key]) {
|
||||
isMatch = false;
|
||||
}
|
||||
}
|
||||
if (isMatch) {
|
||||
results.push(firewall);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
// INSTANCE
|
||||
public data!: types.IFirewall;
|
||||
public hetznerAccountRef: HetznerAccount;
|
||||
|
||||
constructor(hetznerAccountRefArg: HetznerAccount) {
|
||||
this.hetznerAccountRef = hetznerAccountRefArg;
|
||||
}
|
||||
|
||||
public async delete() {
|
||||
await this.hetznerAccountRef.request('DELETE', `/firewalls/${this.data.id}`, {});
|
||||
}
|
||||
}
|
||||
+48
-18
@@ -4,32 +4,45 @@ import * as types from './types.js';
|
||||
|
||||
export class HetznerServer {
|
||||
// STATIC
|
||||
public static async create(hetznerAccountRefArg: HetznerAccount, optionsArg: {
|
||||
name: string,
|
||||
datacenter: 'nbg1-dc3',
|
||||
}) {
|
||||
public static async create(
|
||||
hetznerAccountRefArg: HetznerAccount,
|
||||
optionsArg: {
|
||||
name: string;
|
||||
type: types.THetznerCloudServerName;
|
||||
location: types.THetznerCloudLocationName;
|
||||
labels?: {[key: string]: string},
|
||||
userData?: string,
|
||||
}
|
||||
) {
|
||||
const server = new HetznerServer(hetznerAccountRefArg);
|
||||
|
||||
const createServerUrl = '/servers';
|
||||
const createServerPayload: types.TServerCreateRequestBody =
|
||||
{
|
||||
name: optionsArg.name,
|
||||
datacenter: optionsArg.datacenter,
|
||||
image: '',
|
||||
server_type: '',
|
||||
start_after_create: true,
|
||||
user_data: '',
|
||||
};
|
||||
|
||||
const response = await server.hetznerAccountRef.request('POST', createServerUrl, createServerPayload);
|
||||
server.data = (response.body as types.TServerCreateResponseBody).server;
|
||||
const createServerPayload: types.TServerCreateRequestBody = {
|
||||
name: optionsArg.name,
|
||||
image: 'ubuntu-22.04',
|
||||
server_type: optionsArg.type,
|
||||
start_after_create: true,
|
||||
labels: optionsArg.labels || {} as any,
|
||||
location: optionsArg.location,
|
||||
user_data: optionsArg.userData || '',
|
||||
public_net: {
|
||||
enable_ipv4: true,
|
||||
enable_ipv6: true,
|
||||
},
|
||||
};
|
||||
const response = await server.hetznerAccountRef.request(
|
||||
'POST',
|
||||
createServerUrl,
|
||||
createServerPayload
|
||||
);
|
||||
server.data = (response.body as types.TServerCreateResponseBody).server!;
|
||||
return server;
|
||||
}
|
||||
|
||||
public static async getServers(hetznerAccountRefArg: HetznerAccount) {
|
||||
const serversGetUrl = '/servers';
|
||||
const response = await hetznerAccountRefArg.request('GET', serversGetUrl, {});
|
||||
const serversDataArray = (response.body as types.TServersGetResponseBody).servers;
|
||||
const serversDataArray = (response.body as types.TServersGetResponseBody).servers;
|
||||
const servers: HetznerServer[] = [];
|
||||
for (const serverData of serversDataArray) {
|
||||
const server = new HetznerServer(hetznerAccountRefArg);
|
||||
@@ -39,9 +52,26 @@ export class HetznerServer {
|
||||
return servers;
|
||||
}
|
||||
|
||||
public static async getServersByLabel(hetznerAccountRefArg: HetznerAccount, labelObject: {[key: string]: string}) {
|
||||
const servers = await HetznerServer.getServers(hetznerAccountRefArg);
|
||||
const results: HetznerServer[] = [];
|
||||
for (const server of servers) {
|
||||
let isMatch = true;
|
||||
for (const key in labelObject) {
|
||||
if ((server.data.labels || {})[key] !== labelObject[key]) {
|
||||
isMatch = false;
|
||||
}
|
||||
}
|
||||
if (isMatch) {
|
||||
results.push(server);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
// INSTANCE
|
||||
public hetznerAccountRef: HetznerAccount;
|
||||
public data: types.IServer;
|
||||
public data!: types.IServer;
|
||||
|
||||
constructor(hetznerAccountRefArg: HetznerAccount) {
|
||||
this.hetznerAccountRef = hetznerAccountRefArg;
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { HetznerAccount } from './classes.account.js';
|
||||
import type { HetznerServer } from './classes.server.js';
|
||||
import * as plugins from './hetznercloud.plugins.js';
|
||||
import * as types from './types.js';
|
||||
|
||||
export class HetznerVolume {
|
||||
public static create = async (
|
||||
hetznerAccountRefArg: HetznerAccount,
|
||||
optionsArg: {
|
||||
name: string;
|
||||
size: number;
|
||||
location: types.THetznerCloudLocationName;
|
||||
labels?: {[key: string]: string},
|
||||
server: HetznerServer,
|
||||
}
|
||||
) => {
|
||||
const volume = new HetznerVolume(hetznerAccountRefArg);
|
||||
|
||||
const createVolumeUrl = '/volumes';
|
||||
const createVolumePayload: types.TVolumeCreateRequestBody = {
|
||||
name: optionsArg.name,
|
||||
size: optionsArg.size,
|
||||
location: optionsArg.location,
|
||||
labels: optionsArg.labels || {} as any,
|
||||
server: optionsArg.server.data.id,
|
||||
format: 'xfs'
|
||||
};
|
||||
const response = await volume.hetznerAccountRef.request(
|
||||
'POST',
|
||||
createVolumeUrl,
|
||||
createVolumePayload
|
||||
);
|
||||
volume.data = (response.body as types.TVolumeCreateResponseBody).volume!;
|
||||
return volume;
|
||||
}
|
||||
|
||||
public static getVolumes = async (hetznerAccountRefArg: HetznerAccount) => {
|
||||
const volumesGetUrl = '/volumes';
|
||||
const response = await hetznerAccountRefArg.request('GET', volumesGetUrl, {});
|
||||
const volumesDataArray = (response.body as types.TVolumeGetResponseBody).volumes;
|
||||
const volumes: HetznerVolume[] = [];
|
||||
for (const volumeData of volumesDataArray) {
|
||||
const volume = new HetznerVolume(hetznerAccountRefArg);
|
||||
volume.data = volumeData;
|
||||
volumes.push(volume);
|
||||
}
|
||||
return volumes;
|
||||
}
|
||||
|
||||
public static getVolumesByLabel = async (hetznerAccountRefArg: HetznerAccount, labelObject: {[key: string]: string}) => {
|
||||
const volumes = await HetznerVolume.getVolumes(hetznerAccountRefArg);
|
||||
const results: HetznerVolume[] = [];
|
||||
for (const volume of volumes) {
|
||||
let isMatch = true;
|
||||
for (const key in labelObject) {
|
||||
if ((volume.data.labels || {})[key] !== labelObject[key]) {
|
||||
isMatch = false;
|
||||
}
|
||||
}
|
||||
if (isMatch) {
|
||||
results.push(volume);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
public data!: types.IVolume;
|
||||
public hetznerAccountRef: HetznerAccount;
|
||||
|
||||
constructor(hetznerAccountRefArg: HetznerAccount) {
|
||||
this.hetznerAccountRef = hetznerAccountRefArg;
|
||||
}
|
||||
|
||||
public delete = async () => {
|
||||
await this.hetznerAccountRef.request('DELETE', `/volumes/${this.data.id}`, {});
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
import * as hetznerOpenapi from '@tempfix/hetzner-openapi';
|
||||
|
||||
export {
|
||||
hetznerOpenapi
|
||||
}
|
||||
|
||||
// @push.rocks
|
||||
import * as smartrequest from '@push.rocks/smartrequest';
|
||||
|
||||
export {
|
||||
smartrequest,
|
||||
}
|
||||
|
||||
// @tsclass scope
|
||||
import * as tsclass from '@tsclass/tsclass';
|
||||
|
||||
export {
|
||||
tsclass,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
export * from './classes.account.js';
|
||||
export * from './classes.server.js';
|
||||
export * from './classes.volume.js';
|
||||
export * from './classes.firewall.js';
|
||||
|
||||
+25285
File diff suppressed because it is too large
Load Diff
+59
-5
@@ -1,12 +1,66 @@
|
||||
import * as plugins from './hetznercloud.plugins.js';
|
||||
import * as hetznerOpenapiSpec from './openapi.spec.js';
|
||||
|
||||
type TJsonRequestBody<TPathMethod> = TPathMethod extends { requestBody?: infer TRequestBody }
|
||||
? NonNullable<TRequestBody> extends { content: { 'application/json': infer TJsonBody } }
|
||||
? TJsonBody
|
||||
: never
|
||||
: never;
|
||||
|
||||
// datacenters
|
||||
export type TDatacenters = plugins.hetznerOpenapi.paths['/datacenters']['get']['responses']['200']['content']['application/json'];
|
||||
export type TDatacenters = hetznerOpenapiSpec.paths['/datacenters']['get']['responses']['200']['content']['application/json'];
|
||||
|
||||
// servers
|
||||
export type IServer = plugins.hetznerOpenapi.paths['/servers/{id}']['get']['responses']['200']['content']['application/json']['server'];
|
||||
export type IServer = NonNullable<hetznerOpenapiSpec.paths['/servers/{id}']['get']['responses']['200']['content']['application/json']['server']>;
|
||||
export type TServersGetRequestBody = {};
|
||||
export type TServersGetResponseBody = plugins.hetznerOpenapi.paths['/servers']['get']['responses']['200']['content']['application/json'];
|
||||
export type TServerCreateRequestBody = plugins.hetznerOpenapi.paths['/servers']['post']['requestBody']['content']['application/json'];
|
||||
export type TServerCreateResponseBody = plugins.hetznerOpenapi.paths['/servers']['post']['responses']['201']['content']['application/json'];
|
||||
export type TServersGetResponseBody = hetznerOpenapiSpec.paths['/servers']['get']['responses']['200']['content']['application/json'];
|
||||
export type TServerCreateRequestBody = TJsonRequestBody<hetznerOpenapiSpec.paths['/servers']['post']>;
|
||||
export type TServerCreateResponseBody = hetznerOpenapiSpec.paths['/servers']['post']['responses']['201']['content']['application/json'];
|
||||
export type TServerDeleteRequestBody = hetznerOpenapiSpec.paths['/servers/{id}']['delete'];
|
||||
|
||||
// server types
|
||||
export type THetznerCloudServerName =
|
||||
| 'cx11'
|
||||
| 'cx21'
|
||||
| 'cx31'
|
||||
| 'cx41'
|
||||
| 'cx51'
|
||||
| 'ccx11'
|
||||
| 'ccx21'
|
||||
| 'ccx31'
|
||||
| 'ccx41'
|
||||
| 'ccx51'
|
||||
| 'ccx13'
|
||||
| 'ccx23'
|
||||
| 'ccx33'
|
||||
| 'ccx43'
|
||||
| 'ccx53'
|
||||
| 'ccx63'
|
||||
| 'cpx11'
|
||||
| 'cpx21'
|
||||
| 'cpx31'
|
||||
| 'cpx41'
|
||||
| 'cpx51'
|
||||
| 'cpx61'
|
||||
| 'cpx70'
|
||||
| 'cpx71'
|
||||
| 'cpx90';
|
||||
|
||||
// location types
|
||||
export type THetznerCloudLocationName = 'fsn1' | 'nbg1' | 'hel1' | 'ash' | 'hil';
|
||||
|
||||
// volumes
|
||||
export type IVolume = NonNullable<hetznerOpenapiSpec.paths['/volumes/{id}']['get']['responses']['200']['content']['application/json']['volume']>;
|
||||
export type TVolumeGetRequestBody = {};
|
||||
export type TVolumeGetResponseBody = hetznerOpenapiSpec.paths['/volumes']['get']['responses']['200']['content']['application/json'];
|
||||
export type TVolumeCreateRequestBody = TJsonRequestBody<hetznerOpenapiSpec.paths['/volumes']['post']>;
|
||||
export type TVolumeCreateResponseBody = hetznerOpenapiSpec.paths['/volumes']['post']['responses']['201']['content']['application/json'];
|
||||
export type TVolumeDeleteRequestBody = hetznerOpenapiSpec.paths['/volumes/{id}']['delete'];
|
||||
|
||||
// firewalls
|
||||
export type IFirewall = NonNullable<hetznerOpenapiSpec.paths['/firewalls/{id}']['get']['responses']['200']['content']['application/json']['firewall']>;
|
||||
export type TFirewallsGetRequestBody = {};
|
||||
export type TFirewallsGetResponseBody = hetznerOpenapiSpec.paths['/firewalls']['get']['responses']['200']['content']['application/json'];
|
||||
export type TFirewallCreateRequestBody = TJsonRequestBody<hetznerOpenapiSpec.paths['/firewalls']['post']>;
|
||||
export type TFirewallCreateResponseBody = hetznerOpenapiSpec.paths['/firewalls']['post']['responses']['201']['content']['application/json'];
|
||||
export type TFirewallDeleteRequestBody = hetznerOpenapiSpec.paths['/firewalls/{id}']['delete'];
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
"verbatimModuleSyntax": true,
|
||||
"declaration": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"types": [
|
||||
"node"
|
||||
]
|
||||
},
|
||||
"exclude": [
|
||||
"dist_*/**/*.d.ts"
|
||||
|
||||
Reference in New Issue
Block a user