create-db 1.1.1-pr66-version-bump-19346362281.0 → 1.1.1-pr67-overhaul-20068192317.0

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.
package/dist/cli.d.mts ADDED
@@ -0,0 +1 @@
1
+ export { };
package/dist/cli.mjs ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import { n as createDbCli } from "./src-CFVkopQv.mjs";
3
+
4
+ //#region src/cli.ts
5
+ createDbCli().run();
6
+
7
+ //#endregion
8
+ export { };
@@ -0,0 +1,84 @@
1
+ #!/usr/bin/env node
2
+ import * as trpc_cli0 from "trpc-cli";
3
+ import z$1 from "zod";
4
+
5
+ //#region src/types.d.ts
6
+ declare const RegionSchema: z$1.ZodEnum<{
7
+ "ap-southeast-1": "ap-southeast-1";
8
+ "ap-northeast-1": "ap-northeast-1";
9
+ "eu-central-1": "eu-central-1";
10
+ "eu-west-3": "eu-west-3";
11
+ "us-east-1": "us-east-1";
12
+ "us-west-1": "us-west-1";
13
+ }>;
14
+ type RegionId = z$1.infer<typeof RegionSchema>;
15
+ interface Region {
16
+ id: string;
17
+ name?: string;
18
+ status: string;
19
+ }
20
+ interface DatabaseResult {
21
+ success: true;
22
+ connectionString: string | null;
23
+ claimUrl: string;
24
+ deletionDate: string;
25
+ region: string;
26
+ name: string;
27
+ projectId: string;
28
+ userAgent?: string;
29
+ }
30
+ interface DatabaseError {
31
+ success: false;
32
+ error: string;
33
+ message: string;
34
+ raw?: string;
35
+ details?: unknown;
36
+ status?: number;
37
+ }
38
+ type CreateDatabaseResult = DatabaseResult | DatabaseError;
39
+ declare function isDatabaseError(result: CreateDatabaseResult): result is DatabaseError;
40
+ declare function isDatabaseSuccess(result: CreateDatabaseResult): result is DatabaseResult;
41
+ interface ProgrammaticCreateOptions {
42
+ region?: RegionId;
43
+ userAgent?: string;
44
+ }
45
+ //#endregion
46
+ //#region src/index.d.ts
47
+ declare function createDbCli(): trpc_cli0.TrpcCli;
48
+ /**
49
+ * Create a new Prisma Postgres database programmatically.
50
+ *
51
+ * @param options - Options for creating the database
52
+ * @param options.region - The AWS region for the database (optional)
53
+ * @param options.userAgent - Custom user agent string (optional)
54
+ * @returns A promise that resolves to either a {@link DatabaseResult} or {@link DatabaseError}
55
+ *
56
+ * @example
57
+ * ```typescript
58
+ * import { create } from "create-db";
59
+ *
60
+ * const result = await create({ region: "us-east-1" });
61
+ *
62
+ * if (result.success) {
63
+ * console.log(`Connection string: ${result.connectionString}`);
64
+ * console.log(`Claim URL: ${result.claimUrl}`);
65
+ * } else {
66
+ * console.error(`Error: ${result.message}`);
67
+ * }
68
+ * ```
69
+ */
70
+ declare function create(options?: ProgrammaticCreateOptions): Promise<CreateDatabaseResult>;
71
+ /**
72
+ * List available Prisma Postgres regions programmatically.
73
+ *
74
+ * @example
75
+ * ```typescript
76
+ * import { regions } from "create-db";
77
+ *
78
+ * const availableRegions = await regions();
79
+ * console.log(availableRegions);
80
+ * ```
81
+ */
82
+ declare function regions(): Promise<Region[]>;
83
+ //#endregion
84
+ export { type CreateDatabaseResult, type DatabaseError, type DatabaseResult, type ProgrammaticCreateOptions, type Region, type RegionId, RegionSchema, create, createDbCli, isDatabaseError, isDatabaseSuccess, regions };
package/dist/index.mjs ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { a as isDatabaseError, i as RegionSchema, n as createDbCli, o as isDatabaseSuccess, r as regions, t as create } from "./src-CFVkopQv.mjs";
3
+
4
+ export { RegionSchema, create, createDbCli, isDatabaseError, isDatabaseSuccess, regions };
@@ -0,0 +1,528 @@
1
+ #!/usr/bin/env node
2
+ import { cancel, intro, isCancel, log, outro, select, spinner } from "@clack/prompts";
3
+ import { createRouterClient, os } from "@orpc/server";
4
+ import { randomUUID } from "crypto";
5
+ import dotenv from "dotenv";
6
+ import fs from "fs";
7
+ import pc from "picocolors";
8
+ import terminalLink from "terminal-link";
9
+ import { createCli } from "trpc-cli";
10
+ import z$1, { z } from "zod";
11
+ import path from "path";
12
+
13
+ //#region src/types.ts
14
+ const RegionSchema = z$1.enum([
15
+ "ap-southeast-1",
16
+ "ap-northeast-1",
17
+ "eu-central-1",
18
+ "eu-west-3",
19
+ "us-east-1",
20
+ "us-west-1"
21
+ ]);
22
+ function isDatabaseError(result) {
23
+ return !result.success;
24
+ }
25
+ function isDatabaseSuccess(result) {
26
+ return result.success;
27
+ }
28
+
29
+ //#endregion
30
+ //#region src/analytics.ts
31
+ const pendingAnalytics = [];
32
+ async function sendAnalytics(eventName, properties, cliRunId, workerUrl) {
33
+ const controller = new AbortController();
34
+ const timer = setTimeout(() => controller.abort(), 5e3);
35
+ const promise = (async () => {
36
+ try {
37
+ await fetch(`${workerUrl}/analytics`, {
38
+ method: "POST",
39
+ headers: { "Content-Type": "application/json" },
40
+ body: JSON.stringify({
41
+ eventName,
42
+ properties: {
43
+ distinct_id: cliRunId,
44
+ ...properties
45
+ }
46
+ }),
47
+ signal: controller.signal
48
+ });
49
+ } catch {} finally {
50
+ clearTimeout(timer);
51
+ }
52
+ })();
53
+ pendingAnalytics.push(promise);
54
+ }
55
+ async function flushAnalytics(maxWaitMs = 500) {
56
+ if (pendingAnalytics.length === 0) return;
57
+ await Promise.race([Promise.all(pendingAnalytics), new Promise((resolve) => setTimeout(resolve, maxWaitMs))]);
58
+ }
59
+
60
+ //#endregion
61
+ //#region src/database.ts
62
+ function getCommandName() {
63
+ const executable = process.argv[1] || "create-db";
64
+ if (executable.includes("create-pg")) return "create-pg";
65
+ if (executable.includes("create-postgres")) return "create-postgres";
66
+ return "create-db";
67
+ }
68
+ async function createDatabaseCore(region, createDbWorkerUrl, claimDbWorkerUrl, userAgent, cliRunId) {
69
+ const name = (/* @__PURE__ */ new Date()).toISOString();
70
+ const runId = cliRunId ?? randomUUID();
71
+ const resp = await fetch(`${createDbWorkerUrl}/create`, {
72
+ method: "POST",
73
+ headers: { "Content-Type": "application/json" },
74
+ body: JSON.stringify({
75
+ region,
76
+ name,
77
+ utm_source: getCommandName(),
78
+ userAgent
79
+ })
80
+ });
81
+ if (resp.status === 429) {
82
+ sendAnalytics("create_db:database_creation_failed", {
83
+ region,
84
+ "error-type": "rate_limit",
85
+ "status-code": 429
86
+ }, runId, createDbWorkerUrl);
87
+ return {
88
+ success: false,
89
+ error: "rate_limit_exceeded",
90
+ message: "We're experiencing a high volume of requests. Please try again later.",
91
+ status: 429
92
+ };
93
+ }
94
+ let result;
95
+ let raw = "";
96
+ try {
97
+ raw = await resp.text();
98
+ result = JSON.parse(raw);
99
+ } catch {
100
+ sendAnalytics("create_db:database_creation_failed", {
101
+ region,
102
+ "error-type": "invalid_json",
103
+ "status-code": resp.status
104
+ }, runId, createDbWorkerUrl);
105
+ return {
106
+ success: false,
107
+ error: "invalid_json",
108
+ message: "Unexpected response from create service.",
109
+ raw,
110
+ status: resp.status
111
+ };
112
+ }
113
+ if (result.error) {
114
+ sendAnalytics("create_db:database_creation_failed", {
115
+ region,
116
+ "error-type": "api_error",
117
+ "error-message": result.error.message
118
+ }, runId, createDbWorkerUrl);
119
+ return {
120
+ success: false,
121
+ error: "api_error",
122
+ message: result.error.message || "Unknown error",
123
+ details: result.error,
124
+ status: result.error.status ?? resp.status
125
+ };
126
+ }
127
+ const database = result.data?.database ?? result.databases?.[0];
128
+ const projectId = result.data?.id ?? result.id ?? "";
129
+ const apiKeys = database?.apiKeys;
130
+ const directConnDetails = result.data ? apiKeys?.[0]?.directConnection : result.databases?.[0]?.apiKeys?.[0]?.ppgDirectConnection;
131
+ const directUser = directConnDetails?.user ? encodeURIComponent(String(directConnDetails.user)) : "";
132
+ const directPass = directConnDetails?.pass ? encodeURIComponent(String(directConnDetails.pass)) : "";
133
+ const directHost = directConnDetails?.host;
134
+ const directPort = directConnDetails?.port ? `:${directConnDetails.port}` : "";
135
+ const directDbName = directConnDetails?.database || "postgres";
136
+ const connectionString = directConnDetails && directHost ? `postgresql://${directUser}:${directPass}@${directHost}${directPort}/${directDbName}?sslmode=require` : null;
137
+ const claimUrl = `${claimDbWorkerUrl}/claim?projectID=${projectId}&utm_source=${userAgent || getCommandName()}&utm_medium=cli`;
138
+ const expiryDate = new Date(Date.now() + 1440 * 60 * 1e3);
139
+ sendAnalytics("create_db:database_created", {
140
+ region,
141
+ utm_source: getCommandName()
142
+ }, runId, createDbWorkerUrl);
143
+ return {
144
+ success: true,
145
+ connectionString,
146
+ claimUrl,
147
+ deletionDate: expiryDate.toISOString(),
148
+ region: database?.region?.id || region,
149
+ name: database?.name ?? name,
150
+ projectId,
151
+ userAgent
152
+ };
153
+ }
154
+
155
+ //#endregion
156
+ //#region src/env-utils.ts
157
+ function readUserEnvFile() {
158
+ const envPath = path.join(process.cwd(), ".env");
159
+ if (!fs.existsSync(envPath)) return {};
160
+ const envContent = fs.readFileSync(envPath, "utf8");
161
+ const envVars = {};
162
+ for (const line of envContent.split("\n")) {
163
+ const trimmed = line.trim();
164
+ if (trimmed && !trimmed.startsWith("#")) {
165
+ const [key, ...valueParts] = trimmed.split("=");
166
+ if (key && valueParts.length > 0) {
167
+ const value = valueParts.join("=").replace(/^["']|["']$/g, "");
168
+ envVars[key.trim()] = value.trim();
169
+ }
170
+ }
171
+ }
172
+ return envVars;
173
+ }
174
+
175
+ //#endregion
176
+ //#region src/geolocation.ts
177
+ const TEST_LOCATION = null;
178
+ const REGION_COORDINATES = {
179
+ "ap-southeast-1": {
180
+ lat: 1.3521,
181
+ lng: 103.8198
182
+ },
183
+ "ap-northeast-1": {
184
+ lat: 35.6762,
185
+ lng: 139.6503
186
+ },
187
+ "eu-central-1": {
188
+ lat: 50.1109,
189
+ lng: 8.6821
190
+ },
191
+ "eu-west-3": {
192
+ lat: 48.8566,
193
+ lng: 2.3522
194
+ },
195
+ "us-east-1": {
196
+ lat: 38.9072,
197
+ lng: -77.0369
198
+ },
199
+ "us-west-1": {
200
+ lat: 37.7749,
201
+ lng: -122.4194
202
+ }
203
+ };
204
+ /**
205
+ * Calculate the great-circle distance between two points on Earth using the Haversine formula.
206
+ * @param lat1 Latitude of first point in degrees
207
+ * @param lng1 Longitude of first point in degrees
208
+ * @param lat2 Latitude of second point in degrees
209
+ * @param lng2 Longitude of second point in degrees
210
+ * @returns Distance in kilometers
211
+ */
212
+ function calculateHaversineDistance(lat1, lng1, lat2, lng2) {
213
+ const EARTH_RADIUS_KM = 6371;
214
+ const toRadians = (degrees) => degrees * Math.PI / 180;
215
+ const lat1Rad = toRadians(lat1);
216
+ const lat2Rad = toRadians(lat2);
217
+ const deltaLatRad = toRadians(lat2 - lat1);
218
+ const deltaLngRad = toRadians(lng2 - lng1);
219
+ const a = Math.sin(deltaLatRad / 2) ** 2 + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(deltaLngRad / 2) ** 2;
220
+ return EARTH_RADIUS_KM * (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)));
221
+ }
222
+ /**
223
+ * Detect user's location via IP geolocation API or test location override.
224
+ * Returns null if detection fails or times out.
225
+ */
226
+ async function detectUserLocation() {
227
+ if (TEST_LOCATION !== null) return {
228
+ country: "TEST",
229
+ continent: "TEST",
230
+ city: "Test City",
231
+ region: "Test Region",
232
+ latitude: TEST_LOCATION.latitude,
233
+ longitude: TEST_LOCATION.longitude
234
+ };
235
+ const controller = new AbortController();
236
+ const timeout = setTimeout(() => controller.abort(), 3e3);
237
+ try {
238
+ const response = await fetch("https://ipapi.co/json/", {
239
+ method: "GET",
240
+ headers: { "User-Agent": "create-db-cli/1.0" },
241
+ signal: controller.signal
242
+ });
243
+ if (!response.ok) return null;
244
+ const data = await response.json();
245
+ if (typeof data.latitude !== "number" || typeof data.longitude !== "number" || !Number.isFinite(data.latitude) || !Number.isFinite(data.longitude)) return null;
246
+ return {
247
+ country: data.country_code,
248
+ continent: data.continent_code,
249
+ city: data.city,
250
+ region: data.region,
251
+ latitude: data.latitude,
252
+ longitude: data.longitude
253
+ };
254
+ } catch {
255
+ return null;
256
+ } finally {
257
+ clearTimeout(timeout);
258
+ }
259
+ }
260
+ /**
261
+ * Find the closest AWS region to a given location using Haversine distance.
262
+ * Returns null if the location is invalid or missing coordinates.
263
+ */
264
+ function getRegionClosestToLocation(userLocation) {
265
+ if (!userLocation || userLocation.latitude == null || userLocation.longitude == null) return null;
266
+ const userLat = typeof userLocation.latitude === "number" ? userLocation.latitude : parseFloat(String(userLocation.latitude));
267
+ const userLng = typeof userLocation.longitude === "number" ? userLocation.longitude : parseFloat(String(userLocation.longitude));
268
+ if (!Number.isFinite(userLat) || !Number.isFinite(userLng)) return null;
269
+ let closestRegion = null;
270
+ let minDistance = Infinity;
271
+ for (const [regionId, coords] of Object.entries(REGION_COORDINATES)) {
272
+ const distance = calculateHaversineDistance(userLat, userLng, coords.lat, coords.lng);
273
+ if (distance < minDistance) {
274
+ minDistance = distance;
275
+ closestRegion = regionId;
276
+ }
277
+ }
278
+ return closestRegion;
279
+ }
280
+
281
+ //#endregion
282
+ //#region src/regions.ts
283
+ async function checkOnline(workerUrl) {
284
+ try {
285
+ if (!(await fetch(`${workerUrl}/health`)).ok) throw new Error("API not available");
286
+ } catch {
287
+ console.error(pc.bold(pc.red("\n✖ Error: Cannot reach Prisma Postgres API server.\n")));
288
+ console.error(pc.dim(`Check your internet connection or visit ${pc.green("https://www.prisma-status.com/")}\n`));
289
+ throw new Error("Cannot reach API server");
290
+ }
291
+ }
292
+ async function getRegions(workerUrl) {
293
+ const res = await fetch(`${workerUrl}/regions`);
294
+ if (!res.ok) throw new Error(`Failed to fetch regions. Status: ${res.status} ${res.statusText}`);
295
+ const data = await res.json();
296
+ return (Array.isArray(data) ? data : data.data ?? []).filter((region) => region.status === "available");
297
+ }
298
+ async function validateRegion(region, workerUrl) {
299
+ const regionIds = (await getRegions(workerUrl)).map((r) => r.id);
300
+ if (!regionIds.includes(region)) throw new Error(`Invalid region: ${region}. Available regions: ${regionIds.join(", ")}`);
301
+ return region;
302
+ }
303
+
304
+ //#endregion
305
+ //#region src/index.ts
306
+ dotenv.config({ quiet: true });
307
+ const CREATE_DB_WORKER_URL = process.env.CREATE_DB_WORKER_URL || "https://create-db-temp.prisma.io";
308
+ const CLAIM_DB_WORKER_URL = process.env.CLAIM_DB_WORKER_URL || "https://create-db.prisma.io";
309
+ const sendAnalyticsWithUrl = (eventName, properties, cliRunId) => sendAnalytics(eventName, properties, cliRunId, CREATE_DB_WORKER_URL);
310
+ const checkOnlineWithUrl = async () => {
311
+ try {
312
+ await checkOnline(CREATE_DB_WORKER_URL);
313
+ } catch {
314
+ await flushAnalytics();
315
+ process.exit(1);
316
+ }
317
+ };
318
+ const getRegionsWithUrl = () => getRegions(CREATE_DB_WORKER_URL);
319
+ const validateRegionWithUrl = (region) => validateRegion(region, CREATE_DB_WORKER_URL);
320
+ const createDatabaseCoreWithUrl = (region, userAgent, cliRunId) => createDatabaseCore(region, CREATE_DB_WORKER_URL, CLAIM_DB_WORKER_URL, userAgent, cliRunId);
321
+ const router = os.router({
322
+ create: os.meta({
323
+ description: "Create a new Prisma Postgres database",
324
+ default: true
325
+ }).input(z.object({
326
+ region: RegionSchema.optional().describe("AWS region for the database").meta({ alias: "r" }),
327
+ interactive: z.boolean().optional().default(false).describe("Run in interactive mode to select a region").meta({ alias: "i" }),
328
+ json: z.boolean().optional().default(false).describe("Output machine-readable JSON").meta({ alias: "j" }),
329
+ env: z.string().optional().describe("Write DATABASE_URL and CLAIM_URL to the specified .env file").meta({ alias: "e" })
330
+ })).handler(async ({ input }) => {
331
+ const cliRunId = randomUUID();
332
+ const CLI_NAME = getCommandName();
333
+ let userAgent;
334
+ const userEnvVars = readUserEnvFile();
335
+ if (userEnvVars.PRISMA_ACTOR_NAME && userEnvVars.PRISMA_ACTOR_PROJECT) userAgent = `${userEnvVars.PRISMA_ACTOR_NAME}/${userEnvVars.PRISMA_ACTOR_PROJECT}`;
336
+ sendAnalyticsWithUrl("create_db:cli_command_ran", {
337
+ command: CLI_NAME,
338
+ "has-region-flag": !!input.region,
339
+ "has-interactive-flag": input.interactive,
340
+ "has-json-flag": input.json,
341
+ "has-env-flag": !!input.env,
342
+ "has-user-agent-from-env": !!userAgent,
343
+ "node-version": process.version,
344
+ platform: process.platform,
345
+ arch: process.arch
346
+ }, cliRunId);
347
+ let region = input.region ?? "us-east-1";
348
+ if (!input.region) region = getRegionClosestToLocation(await detectUserLocation()) ?? region;
349
+ const envPath = input.env;
350
+ const envEnabled = typeof envPath === "string" && envPath.trim().length > 0;
351
+ if (input.json || envEnabled) {
352
+ if (input.interactive) {
353
+ await checkOnlineWithUrl();
354
+ const regions$1 = await getRegionsWithUrl();
355
+ const selectedRegion = await select({
356
+ message: "Choose a region:",
357
+ options: regions$1.map((r) => ({
358
+ value: r.id,
359
+ label: r.name || r.id
360
+ })),
361
+ initialValue: regions$1.find((r) => r.id === region)?.id || regions$1[0]?.id
362
+ });
363
+ if (isCancel(selectedRegion)) {
364
+ cancel(pc.red("Operation cancelled."));
365
+ await flushAnalytics();
366
+ process.exit(0);
367
+ }
368
+ region = selectedRegion;
369
+ sendAnalyticsWithUrl("create_db:region_selected", {
370
+ region,
371
+ "selection-method": "interactive"
372
+ }, cliRunId);
373
+ } else if (input.region) {
374
+ await validateRegionWithUrl(region);
375
+ sendAnalyticsWithUrl("create_db:region_selected", {
376
+ region,
377
+ "selection-method": "flag"
378
+ }, cliRunId);
379
+ }
380
+ await checkOnlineWithUrl();
381
+ const result$1 = await createDatabaseCoreWithUrl(region, userAgent, cliRunId);
382
+ await flushAnalytics();
383
+ if (input.json) {
384
+ console.log(JSON.stringify(result$1, null, 2));
385
+ return;
386
+ }
387
+ if (!result$1.success) {
388
+ console.error(result$1.message);
389
+ process.exit(1);
390
+ }
391
+ try {
392
+ const targetEnvPath = envPath;
393
+ const lines = [
394
+ `DATABASE_URL="${result$1.connectionString ?? ""}"`,
395
+ `CLAIM_URL="${result$1.claimUrl}"`,
396
+ ""
397
+ ];
398
+ let prefix = "";
399
+ if (fs.existsSync(targetEnvPath)) {
400
+ const existing = fs.readFileSync(targetEnvPath, "utf8");
401
+ if (existing.length > 0 && !existing.endsWith("\n")) prefix = "\n";
402
+ }
403
+ fs.appendFileSync(targetEnvPath, prefix + lines.join("\n"), { encoding: "utf8" });
404
+ console.log(pc.green(`Wrote DATABASE_URL and CLAIM_URL to ${targetEnvPath}`));
405
+ } catch (err) {
406
+ console.error(pc.red(`Failed to write environment variables to ${envPath}: ${err instanceof Error ? err.message : String(err)}`));
407
+ process.exit(1);
408
+ }
409
+ return;
410
+ }
411
+ await checkOnlineWithUrl();
412
+ intro(pc.bold(pc.cyan("🚀 Creating a Prisma Postgres database")));
413
+ if (input.interactive) {
414
+ const regions$1 = await getRegionsWithUrl();
415
+ const selectedRegion = await select({
416
+ message: "Choose a region:",
417
+ options: regions$1.map((r) => ({
418
+ value: r.id,
419
+ label: r.name || r.id
420
+ })),
421
+ initialValue: regions$1.find((r) => r.id === region)?.id || regions$1[0]?.id
422
+ });
423
+ if (isCancel(selectedRegion)) {
424
+ cancel(pc.red("Operation cancelled."));
425
+ await flushAnalytics();
426
+ process.exit(0);
427
+ }
428
+ region = selectedRegion;
429
+ sendAnalyticsWithUrl("create_db:region_selected", {
430
+ region,
431
+ "selection-method": "interactive"
432
+ }, cliRunId);
433
+ } else if (input.region) {
434
+ await validateRegionWithUrl(region);
435
+ sendAnalyticsWithUrl("create_db:region_selected", {
436
+ region,
437
+ "selection-method": "flag"
438
+ }, cliRunId);
439
+ }
440
+ const s = spinner();
441
+ s.start(`Creating database in ${pc.cyan(region)}...`);
442
+ const result = await createDatabaseCoreWithUrl(region, userAgent, cliRunId);
443
+ if (!result.success) {
444
+ s.stop(pc.red(`Error: ${result.message}`));
445
+ await flushAnalytics();
446
+ process.exit(1);
447
+ }
448
+ s.stop(pc.green("Database created successfully!"));
449
+ const expiryFormatted = new Date(result.deletionDate).toLocaleString();
450
+ const clickableUrl = terminalLink(result.claimUrl, result.claimUrl, { fallback: false });
451
+ log.message("");
452
+ log.info(pc.bold("Database Connection"));
453
+ log.message("");
454
+ if (result.connectionString) {
455
+ log.message(pc.cyan(" Connection String:"));
456
+ log.message(" " + pc.yellow(result.connectionString));
457
+ log.message("");
458
+ } else {
459
+ log.warning(pc.yellow(" Connection details are not available."));
460
+ log.message("");
461
+ }
462
+ log.success(pc.bold("Claim Your Database"));
463
+ log.message(pc.cyan(" Keep your database for free:"));
464
+ log.message(" " + pc.yellow(clickableUrl));
465
+ log.message(pc.italic(pc.dim(` Database will be deleted on ${expiryFormatted} if not claimed.`)));
466
+ outro(pc.dim("Done!"));
467
+ await flushAnalytics();
468
+ }),
469
+ regions: os.meta({ description: "List available Prisma Postgres regions" }).handler(async () => {
470
+ const regions$1 = await getRegionsWithUrl();
471
+ log.message("");
472
+ log.info(pc.bold(pc.cyan("Available Prisma Postgres regions:")));
473
+ log.message("");
474
+ for (const r of regions$1) log.message(` ${pc.green(r.id)} - ${r.name || r.id}`);
475
+ log.message("");
476
+ })
477
+ });
478
+ function createDbCli() {
479
+ return createCli({
480
+ router,
481
+ name: getCommandName(),
482
+ version: "1.1.0",
483
+ description: "Instantly create a temporary Prisma Postgres database"
484
+ });
485
+ }
486
+ createRouterClient(router, { context: {} });
487
+ /**
488
+ * Create a new Prisma Postgres database programmatically.
489
+ *
490
+ * @param options - Options for creating the database
491
+ * @param options.region - The AWS region for the database (optional)
492
+ * @param options.userAgent - Custom user agent string (optional)
493
+ * @returns A promise that resolves to either a {@link DatabaseResult} or {@link DatabaseError}
494
+ *
495
+ * @example
496
+ * ```typescript
497
+ * import { create } from "create-db";
498
+ *
499
+ * const result = await create({ region: "us-east-1" });
500
+ *
501
+ * if (result.success) {
502
+ * console.log(`Connection string: ${result.connectionString}`);
503
+ * console.log(`Claim URL: ${result.claimUrl}`);
504
+ * } else {
505
+ * console.error(`Error: ${result.message}`);
506
+ * }
507
+ * ```
508
+ */
509
+ async function create(options) {
510
+ return createDatabaseCoreWithUrl(options?.region || "us-east-1", options?.userAgent);
511
+ }
512
+ /**
513
+ * List available Prisma Postgres regions programmatically.
514
+ *
515
+ * @example
516
+ * ```typescript
517
+ * import { regions } from "create-db";
518
+ *
519
+ * const availableRegions = await regions();
520
+ * console.log(availableRegions);
521
+ * ```
522
+ */
523
+ async function regions() {
524
+ return getRegionsWithUrl();
525
+ }
526
+
527
+ //#endregion
528
+ export { isDatabaseError as a, RegionSchema as i, createDbCli as n, isDatabaseSuccess as o, regions as r, create as t };