@litebackup/sdk 0.0.0-stage → 0.3.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ /**
2
+ * This file was auto-generated by openapi-typescript.
3
+ * Do not make direct changes to the file.
4
+ */
5
+ export {};
@@ -0,0 +1,38 @@
1
+ import { Backup, type BackupOptions, type BackupSource } from "./backup.js";
2
+ import { Litebackup, type AcquireOptions, type ReleaseOptions, type ReplicateOptions, type RestoreOptions, type VersionsOptions } from "./client.js";
3
+ import type { Failover, FailoverOptions } from "./failover.js";
4
+ import type { AcquireResult, DatabaseStatus, ReleaseResult, RestoreResult, Version, Writer } from "./types.js";
5
+ /** Picks the shared client of the helpers. */
6
+ export interface SharedClientOptions {
7
+ /** Join token; defaults to LITEBACKUP_TOKEN. */
8
+ token?: string;
9
+ /** Session; defaults to LITEBACKUP_SESSION, then "default". */
10
+ session?: string;
11
+ }
12
+ /**
13
+ * Returns the shared client for a token and session, connecting on first
14
+ * use. A failed connection, or a client closed with close(), is replaced on
15
+ * the next call.
16
+ */
17
+ export declare function sharedClient(options?: SharedClientOptions): Promise<Litebackup>;
18
+ /**
19
+ * Backs up a database, given as a path or a better-sqlite3 handle, and keeps
20
+ * syncing it. Returns a Backup at once; `await backup.wait()` for durability.
21
+ */
22
+ export declare function backup(source: BackupSource, options?: BackupOptions): Backup;
23
+ /** Runs a database on several identical machines; see Litebackup.failover. */
24
+ export declare function failover(path: string, options?: FailoverOptions): Promise<Failover>;
25
+ /** Keeps a live read-only replica of a database; resolves once its first version is local. */
26
+ export declare function replicate(name: string, options?: ReplicateOptions & SharedClientOptions): Promise<DatabaseStatus>;
27
+ /** Writes a version of a database to a new file and checks it. */
28
+ export declare function restore(name: string, options: RestoreOptions & SharedClientOptions): Promise<RestoreResult>;
29
+ /** The versions of a database the server can restore, oldest first. */
30
+ export declare function versions(name: string, options?: VersionsOptions & SharedClientOptions): Promise<Version[]>;
31
+ /** Takes a database's write lock and brings it to this machine; see Litebackup.acquire. */
32
+ export declare function acquire(name: string, options?: AcquireOptions & SharedClientOptions): Promise<AcquireResult>;
33
+ /** Syncs an acquired database a final time and releases its write lock; see Litebackup.release. */
34
+ export declare function release(name: string, options?: ReleaseOptions & SharedClientOptions): Promise<ReleaseResult>;
35
+ /** Removes the local copy of a released database the bucket holds; see Litebackup.offload. */
36
+ export declare function offload(name: string, options?: SharedClientOptions): Promise<DatabaseStatus>;
37
+ /** Which machine writes a database, when its lease runs out, and whether it ran out. */
38
+ export declare function writer(name: string, options?: SharedClientOptions): Promise<Writer>;
@@ -0,0 +1,80 @@
1
+ import { Backup } from "./backup.js";
2
+ import { Litebackup } from "./client.js";
3
+ import { tokenEnvironment } from "./launch.js";
4
+ /** One client per (token, session), connected on first use. */
5
+ const shared = new Map();
6
+ /**
7
+ * Returns the shared client for a token and session, connecting on first
8
+ * use. A failed connection, or a client closed with close(), is replaced on
9
+ * the next call.
10
+ */
11
+ export async function sharedClient(options = {}) {
12
+ const token = options.token ?? process.env[tokenEnvironment] ?? "";
13
+ const session = options.session ?? process.env.LITEBACKUP_SESSION ?? "";
14
+ const key = `${token}\u0000${session}`;
15
+ const existing = shared.get(key);
16
+ if (existing) {
17
+ const client = await existing.catch(() => undefined);
18
+ if (client && !client.closed) {
19
+ return client;
20
+ }
21
+ if (shared.get(key) !== existing) {
22
+ return sharedClient(options);
23
+ }
24
+ }
25
+ const connecting = Litebackup.connect({ token: token || undefined, session: session || undefined });
26
+ shared.set(key, connecting);
27
+ try {
28
+ return await connecting;
29
+ }
30
+ catch (error) {
31
+ if (shared.get(key) === connecting) {
32
+ shared.delete(key);
33
+ }
34
+ throw error;
35
+ }
36
+ }
37
+ /**
38
+ * Backs up a database, given as a path or a better-sqlite3 handle, and keeps
39
+ * syncing it. Returns a Backup at once; `await backup.wait()` for durability.
40
+ */
41
+ export function backup(source, options = {}) {
42
+ return new Backup(sharedClient(options), source, options);
43
+ }
44
+ /** Runs a database on several identical machines; see Litebackup.failover. */
45
+ export async function failover(path, options = {}) {
46
+ return (await sharedClient(options)).failover(path, options);
47
+ }
48
+ /** Keeps a live read-only replica of a database; resolves once its first version is local. */
49
+ export async function replicate(name, options = {}) {
50
+ return (await sharedClient(options)).replicate(name, options);
51
+ }
52
+ /** Writes a version of a database to a new file and checks it. */
53
+ export async function restore(name, options) {
54
+ return (await sharedClient(options)).restore(name, options);
55
+ }
56
+ /** The versions of a database the server can restore, oldest first. */
57
+ export async function versions(name, options = {}) {
58
+ return (await sharedClient(options)).versions(name, options);
59
+ }
60
+ /** Takes a database's write lock and brings it to this machine; see Litebackup.acquire. */
61
+ export async function acquire(name, options = {}) {
62
+ return (await sharedClient(options)).acquire(name, withoutClientOptions(options));
63
+ }
64
+ /** Syncs an acquired database a final time and releases its write lock; see Litebackup.release. */
65
+ export async function release(name, options = {}) {
66
+ return (await sharedClient(options)).release(name, withoutClientOptions(options));
67
+ }
68
+ /** Removes the local copy of a released database the bucket holds; see Litebackup.offload. */
69
+ export async function offload(name, options = {}) {
70
+ return (await sharedClient(options)).offload(name);
71
+ }
72
+ /** Which machine writes a database, when its lease runs out, and whether it ran out. */
73
+ export async function writer(name, options = {}) {
74
+ return (await sharedClient(options)).writer(name);
75
+ }
76
+ /** Drops the shared client's token and session from call options. */
77
+ function withoutClientOptions(options) {
78
+ const { token: _token, session: _session, ...rest } = options;
79
+ return rest;
80
+ }
@@ -0,0 +1,17 @@
1
+ export { acquire, backup, failover, offload, release, replicate, restore, versions, writer, sharedClient } from "./helpers.js";
2
+ export type { SharedClientOptions } from "./helpers.js";
3
+ export { Litebackup } from "./client.js";
4
+ export type { AcquireOptions, ConnectOptions, EventsOptions, ReleaseOptions, ReplicateOptions, RestoreOptions, ShutdownOptions, StopBackupTarget, VersionsOptions, } from "./client.js";
5
+ export { Backup } from "./backup.js";
6
+ export type { BackupOptions, BackupSource, SQLiteHandle } from "./backup.js";
7
+ export { Failover } from "./failover.js";
8
+ export type { FailoverEvents, FailoverOptions } from "./failover.js";
9
+ export { LitebackupError, sdkVersion } from "./types.js";
10
+ export type { AcquireResult, BackupInfo, Conflict, DatabaseStatus, Durability, EventList, FailoverInfo, LitebackupEvent, PrefixReplica, ReleaseResult, ReplicaList, RestoreResult, Role, ShutdownResult, State, Status, SyncedState, Version, WriteProtection, Writer, } from "./types.js";
11
+ export type { Camelize } from "./case.js";
12
+ export type { Duration } from "./duration.js";
13
+ export { binaryPathEnvironment, installCommand, litebackupBinary, tokenEnvironment } from "./launch.js";
14
+ export { sessionSocket, systemConfigurationPath } from "./paths.js";
15
+ export { findRelease, releaseKeys, SignatureError } from "./release.js";
16
+ export type { FindReleaseOptions, Release, ReleaseFile } from "./release.js";
17
+ export type { components, paths } from "./generated/client.js";
@@ -0,0 +1,8 @@
1
+ export { acquire, backup, failover, offload, release, replicate, restore, versions, writer, sharedClient } from "./helpers.js";
2
+ export { Litebackup } from "./client.js";
3
+ export { Backup } from "./backup.js";
4
+ export { Failover } from "./failover.js";
5
+ export { LitebackupError, sdkVersion } from "./types.js";
6
+ export { binaryPathEnvironment, installCommand, litebackupBinary, tokenEnvironment } from "./launch.js";
7
+ export { sessionSocket, systemConfigurationPath } from "./paths.js";
8
+ export { findRelease, releaseKeys, SignatureError } from "./release.js";
@@ -0,0 +1,27 @@
1
+ /** Overrides the litebackup binary the SDK starts. */
2
+ export declare const binaryPathEnvironment = "LITEBACKUP_PATH";
3
+ /** Holds the join token, TOKEN@HOST, a daemon joins with on its first start. */
4
+ export declare const tokenEnvironment = "LITEBACKUP_TOKEN";
5
+ /** The one line that installs the litebackup command on this platform. */
6
+ export declare function installCommand(): string;
7
+ /**
8
+ * Finds the litebackup binary: LITEBACKUP_PATH, then this platform's
9
+ * optional npm package, then litebackup on PATH.
10
+ */
11
+ export declare function litebackupBinary(environment?: NodeJS.ProcessEnv): string;
12
+ /** Reports whether something accepts connections on the socket. */
13
+ export declare function socketListening(socketPath: string): Promise<boolean>;
14
+ /**
15
+ * Starts the session daemon when nothing listens. It runs litebackup's own
16
+ * launch command, which takes the session's launch lock and starts
17
+ * `litebackup daemon --session`, exactly like the CLI does, so concurrent
18
+ * processes start one daemon. The daemon joins with the token on its first
19
+ * start. Where `litebackup install service` ran, systemd owns the daemon,
20
+ * and the launch command explains how to reach or start the service instead.
21
+ */
22
+ export declare function launchDaemon(args: {
23
+ session: string;
24
+ socketPath: string;
25
+ environment: NodeJS.ProcessEnv;
26
+ token?: string;
27
+ }): Promise<void>;
@@ -0,0 +1,98 @@
1
+ import { execFile } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import { createConnection } from "node:net";
5
+ import { delimiter, dirname, join } from "node:path";
6
+ /** Overrides the litebackup binary the SDK starts. */
7
+ export const binaryPathEnvironment = "LITEBACKUP_PATH";
8
+ /** Holds the join token, TOKEN@HOST, a daemon joins with on its first start. */
9
+ export const tokenEnvironment = "LITEBACKUP_TOKEN";
10
+ /** npm platform packages that bundle the litebackup binary. */
11
+ const platformPackages = {
12
+ "darwin-arm64": "@litebackup/bin-darwin-arm64",
13
+ "darwin-x64": "@litebackup/bin-darwin-x64",
14
+ "linux-arm64": "@litebackup/bin-linux-arm64",
15
+ "linux-x64": "@litebackup/bin-linux-x64",
16
+ };
17
+ /** Go names the architectures the website's downloads use. */
18
+ const downloadArchitectures = { x64: "amd64", arm64: "arm64" };
19
+ /** The one line that installs the litebackup command on this platform. */
20
+ export function installCommand() {
21
+ const architecture = downloadArchitectures[process.arch] ?? process.arch;
22
+ return `sudo curl -fsSL -o /usr/local/bin/litebackup https://litebackup.com/packages/cli/channels/stable/litebackup-${process.platform}-${architecture} && sudo chmod +x /usr/local/bin/litebackup`;
23
+ }
24
+ /** Finds litebackup on PATH, or returns undefined. */
25
+ function onPath(environment) {
26
+ for (const directory of (environment.PATH ?? "").split(delimiter)) {
27
+ if (directory && existsSync(join(directory, "litebackup"))) {
28
+ return join(directory, "litebackup");
29
+ }
30
+ }
31
+ return undefined;
32
+ }
33
+ /**
34
+ * Finds the litebackup binary: LITEBACKUP_PATH, then this platform's
35
+ * optional npm package, then litebackup on PATH.
36
+ */
37
+ export function litebackupBinary(environment = process.env) {
38
+ const override = environment[binaryPathEnvironment]?.trim();
39
+ if (override) {
40
+ return override;
41
+ }
42
+ const packageName = platformPackages[`${process.platform}-${process.arch}`];
43
+ if (packageName) {
44
+ try {
45
+ const require = createRequire(import.meta.url);
46
+ const binary = join(dirname(require.resolve(`${packageName}/package.json`)), "bin", "litebackup");
47
+ if (existsSync(binary)) {
48
+ return binary;
49
+ }
50
+ }
51
+ catch {
52
+ // The optional package is not installed for this platform; fall back to PATH.
53
+ }
54
+ }
55
+ const found = onPath(environment);
56
+ if (found) {
57
+ return found;
58
+ }
59
+ throw new Error(`the litebackup command is not installed; set ${binaryPathEnvironment} or install it with: ${installCommand()}`);
60
+ }
61
+ /** Reports whether something accepts connections on the socket. */
62
+ export function socketListening(socketPath) {
63
+ return new Promise((resolve) => {
64
+ const connection = createConnection({ path: socketPath });
65
+ connection.once("connect", () => {
66
+ connection.end();
67
+ resolve(true);
68
+ });
69
+ connection.once("error", () => resolve(false));
70
+ });
71
+ }
72
+ /**
73
+ * Starts the session daemon when nothing listens. It runs litebackup's own
74
+ * launch command, which takes the session's launch lock and starts
75
+ * `litebackup daemon --session`, exactly like the CLI does, so concurrent
76
+ * processes start one daemon. The daemon joins with the token on its first
77
+ * start. Where `litebackup install service` ran, systemd owns the daemon,
78
+ * and the launch command explains how to reach or start the service instead.
79
+ */
80
+ export async function launchDaemon(args) {
81
+ if (await socketListening(args.socketPath)) {
82
+ return;
83
+ }
84
+ const binary = litebackupBinary(args.environment);
85
+ const environment = { ...args.environment, [binaryPathEnvironment]: binary };
86
+ if (args.token) {
87
+ environment[tokenEnvironment] = args.token;
88
+ }
89
+ await new Promise((resolve, reject) => {
90
+ execFile(binary, ["launch", "--session", args.session], { env: environment, timeout: 30_000 }, (error, _stdout, stderr) => {
91
+ if (error) {
92
+ reject(new Error(`starting Litebackup failed: ${stderr.trim() || error.message}`));
93
+ return;
94
+ }
95
+ resolve();
96
+ });
97
+ });
98
+ }
@@ -0,0 +1,15 @@
1
+ /** The session used when neither the caller nor LITEBACKUP_SESSION names one. */
2
+ export declare const defaultSession = "default";
3
+ /** Records a `litebackup install service` install, as litebackup reads it. */
4
+ export declare const systemConfigurationPath = "/etc/litebackup/client.json";
5
+ /**
6
+ * Resolves the session name and its socket exactly as litebackup does. Where
7
+ * `litebackup install service` ran, root and the service's user use the
8
+ * service's socket under its runtime directory. Everyone else uses
9
+ * $XDG_RUNTIME_DIR/litebackup/<session>/client.sock, or a per-user directory
10
+ * under the temporary directory.
11
+ */
12
+ export declare function sessionSocket(session: string | undefined, environment: NodeJS.ProcessEnv, configurationPath?: string): {
13
+ session: string;
14
+ socketPath: string;
15
+ };
@@ -0,0 +1,42 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { tmpdir, userInfo } from "node:os";
3
+ import { join } from "node:path";
4
+ /** The session used when neither the caller nor LITEBACKUP_SESSION names one. */
5
+ export const defaultSession = "default";
6
+ /** Records a `litebackup install service` install, as litebackup reads it. */
7
+ export const systemConfigurationPath = "/etc/litebackup/client.json";
8
+ /** Matches litebackup's session names. */
9
+ const sessionPattern = /^[a-z0-9._-]+$/;
10
+ /** Reads the service install, or undefined when there is none. */
11
+ function systemConfiguration(path) {
12
+ try {
13
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
14
+ if (typeof parsed.uid === "number" && typeof parsed.runtime_directory === "string" && parsed.runtime_directory) {
15
+ return { uid: parsed.uid, runtime_directory: parsed.runtime_directory };
16
+ }
17
+ }
18
+ catch {
19
+ // No service install, or one this SDK cannot read: use the per-user socket.
20
+ }
21
+ return undefined;
22
+ }
23
+ /**
24
+ * Resolves the session name and its socket exactly as litebackup does. Where
25
+ * `litebackup install service` ran, root and the service's user use the
26
+ * service's socket under its runtime directory. Everyone else uses
27
+ * $XDG_RUNTIME_DIR/litebackup/<session>/client.sock, or a per-user directory
28
+ * under the temporary directory.
29
+ */
30
+ export function sessionSocket(session, environment, configurationPath = systemConfigurationPath) {
31
+ const name = session || environment.LITEBACKUP_SESSION || defaultSession;
32
+ if (!sessionPattern.test(name)) {
33
+ throw new Error(`session names use [a-z0-9._-], got ${JSON.stringify(name)}`);
34
+ }
35
+ const uid = userInfo().uid;
36
+ const system = systemConfiguration(configurationPath);
37
+ if (system && (uid === 0 || uid === system.uid)) {
38
+ return { session: name, socketPath: join(system.runtime_directory, name, "client.sock") };
39
+ }
40
+ const runtimeRoot = environment.XDG_RUNTIME_DIR || join(environment.TMPDIR || tmpdir(), `litebackup-${uid}`);
41
+ return { session: name, socketPath: join(runtimeRoot, "litebackup", name, "client.sock") };
42
+ }
@@ -0,0 +1,39 @@
1
+ /** Litebackup's Ed25519 release keys by key ID, base64url without padding, as the litebackup command checks them. */
2
+ export declare const releaseKeys: Readonly<Record<string, string>>;
3
+ /** One published file of a release. */
4
+ export interface ReleaseFile {
5
+ name: string;
6
+ filename: string;
7
+ url: string;
8
+ sha256: string;
9
+ size: number;
10
+ os?: string;
11
+ architecture?: string;
12
+ }
13
+ /** A package release taken from its verified signed document. */
14
+ export interface Release {
15
+ version: string;
16
+ channels: string[];
17
+ files: ReleaseFile[];
18
+ }
19
+ /** Options for findRelease. */
20
+ export interface FindReleaseOptions {
21
+ /** Package slug; "cli" when unset. */
22
+ package?: string;
23
+ /** The release to find; the release on `channel` when unset. */
24
+ version?: string;
25
+ /** Used when `version` is unset; "stable" when unset. */
26
+ channel?: string;
27
+ /** Keys that verify the release; releaseKeys when unset. */
28
+ keys?: Readonly<Record<string, string>>;
29
+ }
30
+ /** A release whose signature does not match Litebackup's release keys. */
31
+ export declare class SignatureError extends Error {
32
+ constructor();
33
+ }
34
+ /**
35
+ * Reads package metadata, as https://litebackup.com/packages/metadata serves
36
+ * it, and returns the selected release taken from its signed document, never
37
+ * the unsigned listing. Throws SignatureError when the signature does not verify.
38
+ */
39
+ export declare function findRelease(metadata: string | unknown, options?: FindReleaseOptions): Release;
@@ -0,0 +1,67 @@
1
+ import { createPublicKey, verify } from "node:crypto";
2
+ /** Litebackup's Ed25519 release keys by key ID, base64url without padding, as the litebackup command checks them. */
3
+ export const releaseKeys = {
4
+ "01a1e021-85f9-7e27-83a3-6773334277e0": "a1Dlc-XT9Z2ZyVs-0p7HreWE6KPwppru7MxvhVdbdBs",
5
+ };
6
+ /** Frames a signed document the way Apps signs releases: context, key ID, separator, document. */
7
+ const signatureContext = "clor-apps-v1\u0000";
8
+ const signatureSeparator = "\u0000";
9
+ /** A release whose signature does not match Litebackup's release keys. */
10
+ export class SignatureError extends Error {
11
+ constructor() {
12
+ super("the release signature does not match Litebackup's release keys");
13
+ this.name = "SignatureError";
14
+ }
15
+ }
16
+ /** Checks a signed release against keys and decodes it. */
17
+ function verifyRelease(signed, keys) {
18
+ const encoded = keys[signed?.key_id];
19
+ if (!encoded) {
20
+ throw new SignatureError();
21
+ }
22
+ let document;
23
+ let verified = false;
24
+ try {
25
+ const key = createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: encoded }, format: "jwk" });
26
+ document = Buffer.from(signed.document, "base64url");
27
+ const message = Buffer.concat([Buffer.from(signatureContext + signed.key_id + signatureSeparator), document]);
28
+ verified = verify(null, message, key, Buffer.from(signed.signature, "base64url"));
29
+ }
30
+ catch {
31
+ throw new SignatureError();
32
+ }
33
+ if (!verified) {
34
+ throw new SignatureError();
35
+ }
36
+ try {
37
+ const decoded = JSON.parse(document.toString("utf8"));
38
+ return { version: decoded.version, files: decoded.artifacts ?? [] };
39
+ }
40
+ catch {
41
+ throw new SignatureError();
42
+ }
43
+ }
44
+ /**
45
+ * Reads package metadata, as https://litebackup.com/packages/metadata serves
46
+ * it, and returns the selected release taken from its signed document, never
47
+ * the unsigned listing. Throws SignatureError when the signature does not verify.
48
+ */
49
+ export function findRelease(metadata, options = {}) {
50
+ const listing = (typeof metadata === "string" ? JSON.parse(metadata) : metadata);
51
+ const slug = options.package ?? "cli";
52
+ const channel = options.channel ?? "stable";
53
+ const keys = options.keys ?? releaseKeys;
54
+ const listed = listing.packages?.find((candidate) => candidate.slug === slug);
55
+ if (!listed) {
56
+ throw new Error(`no package ${slug}`);
57
+ }
58
+ const candidate = listed.releases.find((release) => (options.version ? release.version === options.version : release.channels.includes(channel)));
59
+ if (!candidate) {
60
+ throw new Error(options.version ? `package ${slug} has no release ${options.version}` : `package ${slug} has no release on ${channel}`);
61
+ }
62
+ const release = verifyRelease(candidate.signature, keys);
63
+ if (release.version !== candidate.version) {
64
+ throw new SignatureError();
65
+ }
66
+ return { ...release, channels: candidate.channels };
67
+ }
@@ -0,0 +1,20 @@
1
+ /** A response read whole from the client socket. */
2
+ export interface SocketResponse {
3
+ status: number;
4
+ headers: Record<string, string>;
5
+ body: string;
6
+ }
7
+ /** Options for one request over the client's unix socket. */
8
+ export interface SocketRequest {
9
+ socketPath: string;
10
+ method: "GET" | "POST";
11
+ path: string;
12
+ headers: Record<string, string>;
13
+ body?: string;
14
+ signal?: AbortSignal;
15
+ }
16
+ /**
17
+ * Sends one HTTP request over a unix socket and reads the whole response.
18
+ * The client API answers small JSON documents, so buffering is fine.
19
+ */
20
+ export declare function socketFetch(options: SocketRequest): Promise<SocketResponse>;
@@ -0,0 +1,44 @@
1
+ import { request } from "node:http";
2
+ /**
3
+ * Sends one HTTP request over a unix socket and reads the whole response.
4
+ * The client API answers small JSON documents, so buffering is fine.
5
+ */
6
+ export function socketFetch(options) {
7
+ return new Promise((resolve, reject) => {
8
+ const outgoing = request({
9
+ socketPath: options.socketPath,
10
+ method: options.method,
11
+ path: options.path,
12
+ headers: {
13
+ ...options.headers,
14
+ ...(options.body === undefined ? {} : { "content-type": "application/json", "content-length": Buffer.byteLength(options.body) }),
15
+ },
16
+ signal: options.signal,
17
+ }, (incoming) => {
18
+ const chunks = [];
19
+ incoming.on("data", (chunk) => chunks.push(chunk));
20
+ incoming.on("error", reject);
21
+ incoming.on("end", () => {
22
+ const headers = {};
23
+ for (const [name, value] of Object.entries(incoming.headers)) {
24
+ if (typeof value === "string") {
25
+ headers[name] = value;
26
+ }
27
+ else if (Array.isArray(value)) {
28
+ headers[name] = value.join(", ");
29
+ }
30
+ }
31
+ resolve({
32
+ status: incoming.statusCode ?? 0,
33
+ headers,
34
+ body: Buffer.concat(chunks).toString("utf8"),
35
+ });
36
+ });
37
+ });
38
+ outgoing.on("error", reject);
39
+ if (options.body !== undefined) {
40
+ outgoing.write(options.body);
41
+ }
42
+ outgoing.end();
43
+ });
44
+ }
@@ -0,0 +1,41 @@
1
+ import type { Camelize } from "./case.js";
2
+ import type { components } from "./generated/client.js";
3
+ type Schemas = components["schemas"];
4
+ /** What this machine does with a database. */
5
+ export type Role = "origin" | "replica";
6
+ /** Where a database stands on this machine; waiting means another machine is the origin. */
7
+ export type State = "syncing" | "synced" | "waiting" | "offloaded" | "stopped" | "conflicted" | "error";
8
+ /** How far a version must reach: the server's acknowledgement, or the bucket too. */
9
+ export type Durability = "server" | "cloud";
10
+ /** How a replica keeps app writes out. */
11
+ export type WriteProtection = "lock" | "detect" | "none";
12
+ export type SyncedState = Camelize<Schemas["SyncedState"]>;
13
+ export type DatabaseStatus = Camelize<Schemas["DatabaseStatus"]>;
14
+ export type Status = Camelize<Schemas["Status"]>;
15
+ export type Version = Camelize<Schemas["RestorableVersion"]>;
16
+ export type RestoreResult = Camelize<Schemas["RestoreResult"]>;
17
+ export type Conflict = Camelize<Schemas["Conflict"]>;
18
+ export type AcquireResult = Camelize<Schemas["AcquireResult"]>;
19
+ export type ReleaseResult = Camelize<Schemas["ReleaseResult"]>;
20
+ export type Writer = Camelize<Schemas["Writer"]>;
21
+ /** A backup or failover running on this machine, as backups.list() returns it. */
22
+ export type BackupInfo = Camelize<Schemas["Backup"]>;
23
+ /** A failover as the daemon reports it. */
24
+ export type FailoverInfo = Camelize<Schemas["Failover"]>;
25
+ export type PrefixReplica = Camelize<Schemas["PrefixReplica"]>;
26
+ export type ReplicaList = Camelize<Schemas["ReplicaList"]>;
27
+ export type LitebackupEvent = Camelize<Schemas["Event"]>;
28
+ export type EventList = Camelize<Schemas["EventList"]>;
29
+ export type ShutdownResult = Camelize<Schemas["ShutdownResult"]>;
30
+ /** The SDK version sent with every call. */
31
+ export declare const sdkVersion = "0.3.18";
32
+ /** An error the Litebackup daemon answered with, carrying its code. */
33
+ export declare class LitebackupError extends Error {
34
+ /** Such as name_in_use, exists, in_use, not_found, still_open, timeout, or sdk_unsupported. */
35
+ readonly code: string;
36
+ /** The HTTP status of the answer, or 0 for errors the SDK raised itself. */
37
+ readonly status: number;
38
+ /** Creates an error from a daemon {code, message} answer. */
39
+ constructor(code: string, message: string, status: number);
40
+ }
41
+ export {};
@@ -0,0 +1,16 @@
1
+ /** The SDK version sent with every call. */
2
+ export const sdkVersion = "0.3.18";
3
+ /** An error the Litebackup daemon answered with, carrying its code. */
4
+ export class LitebackupError extends Error {
5
+ /** Such as name_in_use, exists, in_use, not_found, still_open, timeout, or sdk_unsupported. */
6
+ code;
7
+ /** The HTTP status of the answer, or 0 for errors the SDK raised itself. */
8
+ status;
9
+ /** Creates an error from a daemon {code, message} answer. */
10
+ constructor(code, message, status) {
11
+ super(`${code}: ${message}`);
12
+ this.name = "LitebackupError";
13
+ this.code = code;
14
+ this.status = status;
15
+ }
16
+ }
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@litebackup/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.18",
4
+ "description": "Back up, replicate, and restore SQLite databases with Litebackup",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "main": "./dist/src/index.js",
8
+ "types": "./dist/src/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/src/index.d.ts",
12
+ "default": "./dist/src/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist/src"
17
+ ],
18
+ "engines": {
19
+ "node": ">=22"
20
+ },
21
+ "scripts": {
22
+ "generate": "openapi-typescript ../client-openapi.yaml --output src/generated/client.ts",
23
+ "build": "tsc --project tsconfig.json",
24
+ "test": "npm run build && node --test \"dist/test/*.test.js\"",
25
+ "prepack": "npm run build"
26
+ },
27
+ "optionalDependencies": {
28
+ "@litebackup/bin-darwin-arm64": "0.3.18",
29
+ "@litebackup/bin-darwin-x64": "0.3.18",
30
+ "@litebackup/bin-linux-arm64": "0.3.18",
31
+ "@litebackup/bin-linux-x64": "0.3.18"
32
+ },
33
+ "devDependencies": {
34
+ "@types/node": "24.19.2",
35
+ "openapi-typescript": "7.13.0",
36
+ "typescript": "5.9.3"
37
+ }
38
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.