import { CreateCustomerRequest, CreateCustomerResponse, CUSTOMER_PATH, } from '../server/api-types.js'; import {assertObject, assertString} from './asserts.js'; import type {SimpleFetch} from './simple-fetch.js'; // TODO when our license is finalized add a link to it. export const TEST_LICENSE_KEY = 'This key only good for automated testing'; export const PROD_LICENSE_SERVER_URL = new URL( 'https://replicache-license.herokuapp.com/', ); // createCustomer takes customer info and returns a license key. This function // is invoked by the command line and throws instead of logging errors so they // can be caught and printed nicely to stdout. export async function createCustomer( mustFetch: SimpleFetch, serverURL: URL, name: string, project: string | undefined, email: string, commercial: boolean, acceptedTOS: boolean, ): Promise { const url: URL = new URL(CUSTOMER_PATH, serverURL); const clr: CreateCustomerRequest = { name, email, commercial, acceptedTOS, }; if (project !== undefined) { clr.project = project; } try { // TODO use a sensible timeout const response = await mustFetch( 'post', url.toString(), JSON.stringify(clr), { // eslint-disable-next-line @typescript-eslint/naming-convention 'Content-Type': 'application/json', // eslint-disable-next-line @typescript-eslint/naming-convention 'Accept': 'application/json', }, ); const responseBody = await response.text(); const res: CreateCustomerResponse = JSON.parse(responseBody); assertCreateCustomerResponse(res); return res.licenseKey; } catch (e) { if (e instanceof Error) { throw new Error(`Failed to create customer: ${e.message}`); } else if (isToString(e)) { throw new Error(`Failed to create customer: ${e.toString()}`); } else { throw new Error('Failed to create customer'); } } } type ToString = { toString(): string; }; // eslint-disable-next-line @typescript-eslint/no-explicit-any function isToString(o: any): o is ToString { return typeof o['toString'] === 'function'; } function assertCreateCustomerResponse( // eslint-disable-next-line @typescript-eslint/no-explicit-any v: any, ): asserts v is CreateCustomerResponse { assertObject(v); assertString(v.licenseKey); }