"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/index.ts require('whatwg-fetch'); // src/api-token.ts var ApiTokenClient = class { constructor(config) { this.config = config; } async list() { const response = await TursoClient.request( "auth/api-tokens", this.config ); return _nullishCoalesce(response.tokens, () => ( [])); } async create(name) { const response = await TursoClient.request( `auth/api-tokens/${name}`, this.config, { method: "POST", headers: { "content-type": "application/json" } } ); return response; } async revoke(name) { const response = await TursoClient.request( `auth/api-tokens/${name}`, this.config, { method: "DELETE" } ); return response; } async validate(token) { const response = await TursoClient.request( "auth/api-tokens/validate", this.config, { headers: { Authorization: `Bearer ${token}` } } ); const currentTime = Math.floor(Date.now() / 1e3); return { valid: response.exp !== -1 && response.exp > currentTime, expiry: response.exp }; } }; // src/organization.ts var OrganizationClient = class { constructor(config) { this.config = config; } async list() { const response = await TursoClient.request("organizations", this.config); return _nullishCoalesce(response.organizations, () => ( [])); } async update(options) { const response = await TursoClient.request(`organizations/${this.config.org}`, this.config, { method: "PATCH", body: JSON.stringify(options) }); return _nullishCoalesce(response.organization, () => ( null)); } async delete() { return TursoClient.request( `organizations/${this.config.org}`, this.config, { method: "DELETE" } ); } async members() { const response = await TursoClient.request(`organizations/${this.config.org}/members`, this.config); return _nullishCoalesce(response.members, () => ( [])); } async addMember(username, role) { return TursoClient.request( `organizations/${this.config.org}/members/${username}`, this.config, { method: "POST", body: JSON.stringify({ member: username, role: role ? role : "member" }) } ); } async removeMember(username) { return TursoClient.request( `organizations/${this.config.org}/members/${username}`, this.config, { method: "DELETE" } ); } async inviteUser(email, role) { const response = await TursoClient.request( `organizations/${this.config.org}/invites`, this.config, { method: "POST", body: JSON.stringify({ email, role: role ? role : "member" }) } ); return response.invited; } async deleteInvite(email) { return TursoClient.request( `organizations/${this.config.org}/invites/${email}`, this.config, { method: "DELETE" } ); } async invoices() { const response = await TursoClient.request(`organizations/${this.config.org}/invoices`, this.config); return _nullishCoalesce(response.invoices, () => ( [])); } }; // src/location.ts var LocationClient = class { constructor(config) { this.config = config; } async list() { const response = await TursoClient.request("locations", this.config); if (!response.locations) { return []; } return Object.entries(response.locations).map(([code, description]) => ({ code, description })); } async closest() { return fetch("https://region.turso.io/").then((res) => res.json()); } }; // src/group.ts var GroupClient = class { constructor(config) { this.config = config; } async list() { const response = await TursoClient.request( `organizations/${this.config.org}/groups`, this.config ); return _nullishCoalesce(response.groups, () => ( [])); } async get(name) { const response = await TursoClient.request( `organizations/${this.config.org}/groups/${name}`, this.config ); return response.group; } async create(name, location, options) { const response = await TursoClient.request( `organizations/${this.config.org}/groups`, this.config, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name, location, ...options }) } ); return response.group; } async delete(name) { const response = await TursoClient.request( `organizations/${this.config.org}/groups/${name}`, this.config, { method: "DELETE" } ); return response.group; } async addLocation(groupName, location) { const response = await TursoClient.request( `organizations/${this.config.org}/groups/${groupName}/locations/${location}`, this.config, { method: "POST" } ); return response.group; } async removeLocation(groupName, location) { const response = await TursoClient.request( `organizations/${this.config.org}/groups/${groupName}/locations/${location}`, this.config, { method: "DELETE" } ); return response.group; } async createToken(groupName, options) { const queryParams = new URLSearchParams(); if (_optionalChain([options, 'optionalAccess', _2 => _2.expiration])) { queryParams.set("expiration", options.expiration); } if (_optionalChain([options, 'optionalAccess', _3 => _3.authorization])) { queryParams.set("authorization", options.authorization); } const response = await TursoClient.request( `organizations/${this.config.org}/groups/${groupName}/auth/tokens?${queryParams}`, this.config, { method: "POST", body: JSON.stringify({ permissions: { read_attach: { databases: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _4 => _4.permissions, 'optionalAccess', _5 => _5.read_attach, 'optionalAccess', _6 => _6.databases]), () => ( [])) } } }) } ); return response; } async rotateTokens(groupName) { return await TursoClient.request( `organizations/${this.config.org}/groups/${groupName}/auth/rotate`, this.config, { method: "POST" } ); } }; // src/database.ts function hasIsSchemaOption(options) { return options !== void 0 && options.is_schema !== void 0; } function hasSchemaOption(options) { return options !== void 0 && options.schema !== void 0; } var DatabaseClient = class { constructor(config) { this.config = config; } async list(options) { const queryParams = new URLSearchParams( Object.entries({ schema: _optionalChain([options, 'optionalAccess', _7 => _7.schema]), group: _optionalChain([options, 'optionalAccess', _8 => _8.group]), type: _optionalChain([options, 'optionalAccess', _9 => _9.type]) }).filter(([_, value]) => value !== void 0) ); const url = `organizations/${this.config.org}/databases${queryParams.toString() ? `?${queryParams.toString()}` : ""}`; const response = await TursoClient.request(url, this.config); return (_nullishCoalesce(response.databases, () => ( []))).map((db) => this.formatResponse(db)); } async get(dbName) { const response = await TursoClient.request(`organizations/${this.config.org}/databases/${dbName}`, this.config); return this.formatResponse(response.database); } async create(dbName, options) { if (hasIsSchemaOption(options) && hasSchemaOption(options)) { throw new Error("'is_schema' and 'schema' cannot both be provided"); } if (_optionalChain([options, 'optionalAccess', _10 => _10.seed])) { if (options.seed.type === "database" && !options.seed.name) { throw new Error("Seed name is required when type is 'database'"); } if (options.seed.type === "dump" && !options.seed.url) { throw new Error("Seed URL is required when type is 'dump'"); } } if (_optionalChain([options, 'optionalAccess', _11 => _11.seed, 'optionalAccess', _12 => _12.timestamp])) { options.seed.timestamp = this.formatDateParameter(options.seed.timestamp); } const response = await TursoClient.request(`organizations/${this.config.org}/databases`, this.config, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: dbName, ...options }) }); return this.formatCreateResponse(response.database); } async updateVersion(dbName) { return await TursoClient.request( `organizations/${this.config.org}/databases/${dbName}/update`, this.config, { method: "POST" } ); } async delete(dbName) { const response = await TursoClient.request( `organizations/${this.config.org}/databases/${dbName}`, this.config, { method: "DELETE" } ); return response; } async listInstances(dbName) { const response = await TursoClient.request( `organizations/${this.config.org}/databases/${dbName}/instances`, this.config ); return _nullishCoalesce(response.instances, () => ( [])); } async getInstance(dbName, instanceName) { const response = await TursoClient.request( `organizations/${this.config.org}/databases/${dbName}/instances/${instanceName}`, this.config ); return _nullishCoalesce(response.instance, () => ( null)); } async createToken(dbName, options) { const queryParams = new URLSearchParams(); if (_optionalChain([options, 'optionalAccess', _13 => _13.expiration])) { queryParams.set("expiration", options.expiration); } if (_optionalChain([options, 'optionalAccess', _14 => _14.authorization])) { queryParams.set("authorization", options.authorization); } const response = await TursoClient.request( `organizations/${this.config.org}/databases/${dbName}/auth/tokens?${queryParams}`, this.config, { method: "POST", body: JSON.stringify({ permissions: { read_attach: { databases: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _15 => _15.permissions, 'optionalAccess', _16 => _16.read_attach, 'optionalAccess', _17 => _17.databases]), () => ( [])) } } }) } ); return response; } async rotateTokens(dbName) { return await TursoClient.request( `organizations/${this.config.org}/databases/${dbName}/auth/rotate`, this.config, { method: "POST" } ); } async usage(dbName, options) { const queryParams = new URLSearchParams(); if (_optionalChain([options, 'optionalAccess', _18 => _18.from])) { queryParams.set("from", this.formatDateParameter(options.from)); } if (_optionalChain([options, 'optionalAccess', _19 => _19.to])) { queryParams.set("to", this.formatDateParameter(options.to)); } const response = await TursoClient.request( `organizations/${this.config.org}/databases/${dbName}/usage?${queryParams}`, this.config ); return response.database; } formatDateParameter(date) { return date instanceof Date ? date.toISOString() : date; } formatResponse(db) { return { name: db.Name, id: db.DbId, hostname: db.Hostname, regions: db.regions, primaryRegion: db.primaryRegion, type: db.type, version: db.version, group: db.group, sleeping: db.sleeping, archived: db.archived, allow_attach: db.allow_attach, block_reads: db.block_reads, block_writes: db.block_writes, schema: db.schema, is_schema: db.is_schema }; } formatCreateResponse(db) { return { id: db.DbId, hostname: db.Hostname, name: db.Name }; } }; // src/client.ts var TursoClientError = class extends Error { constructor(message, additionalInfo) { super(message); this.name = "TursoClientError"; this.status = _optionalChain([additionalInfo, 'optionalAccess', _20 => _20.status]); } }; var TursoClient = class { constructor(config) { if (!config.token) { throw new Error("You must provide an API token"); } this.config = { baseUrl: "https://api.turso.tech/v1/", ...config }; this.apiTokens = new ApiTokenClient(this.config); this.organizations = new OrganizationClient(this.config); this.locations = new LocationClient(this.config); this.groups = new GroupClient(this.config); this.databases = new DatabaseClient(this.config); } static async request(url, config, options = {}) { const response = await fetch(new URL(url, config.baseUrl), { ...options, headers: { ...options.headers, Authorization: `Bearer ${config.token}`, "User-Agent": "@tursodatabase/api" } }); if (!response.ok) { const errorResponse = await response.json().catch(() => { throw new Error(`Something went wrong! Status ${response.status}`); }); throw new TursoClientError(errorResponse.error, { status: response.status }); } return response.json(); } }; function createClient(config) { return new TursoClient(config); } exports.createClient = createClient; //# sourceMappingURL=index.cjs.map