@cdwr/fly-node 0.1.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/index.cjs ADDED
@@ -0,0 +1,1281 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // packages/fly-node/src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ Fly: () => Fly
34
+ });
35
+ module.exports = __toCommonJS(src_exports);
36
+
37
+ // packages/fly-node/src/lib/fly.class.ts
38
+ var import_fs = require("fs");
39
+ var import_path = require("path");
40
+ var import_process = require("process");
41
+
42
+ // packages/core/src/lib/utils/docker-build.ts
43
+ var import_docker_cli_js = require("docker-cli-js");
44
+ var import_tiny_invariant = __toESM(require("tiny-invariant"), 1);
45
+
46
+ // packages/core/src/lib/utils/log-utils.ts
47
+ var import_chalk = __toESM(require("chalk"), 1);
48
+
49
+ // packages/core/src/lib/utils/get-package-version.ts
50
+ var import_child_process = require("child_process");
51
+ var import_util = require("util");
52
+ var execAsync = (0, import_util.promisify)(import_child_process.execFile);
53
+
54
+ // packages/core/src/lib/utils/kill-port.ts
55
+ var import_kill_port = __toESM(require("kill-port"), 1);
56
+ var import_tcp_port_used = require("tcp-port-used");
57
+
58
+ // packages/core/src/lib/utils/kill-process-tree.ts
59
+ var import_util2 = require("util");
60
+ var import_tree_kill = __toESM(require("tree-kill"), 1);
61
+ var killProcessTree = (0, import_util2.promisify)(import_tree_kill.default);
62
+
63
+ // packages/core/src/lib/utils/promisified-exec.ts
64
+ var import_child_process2 = require("child_process");
65
+ var import_util3 = require("util");
66
+ var exec = (0, import_util3.promisify)(import_child_process2.exec);
67
+
68
+ // packages/core/src/lib/utils/run-command.ts
69
+ var import_testing = require("@nx/plugin/testing");
70
+
71
+ // packages/core/src/lib/utils/whoami.ts
72
+ var import_npm_whoami = __toESM(require("npm-whoami"), 1);
73
+
74
+ // packages/fly-node/src/lib/fly.class.ts
75
+ var import_zod29 = require("zod");
76
+
77
+ // packages/core/src/lib/zod/json.schema.ts
78
+ var import_zod = require("zod");
79
+ var LiteralSchema = import_zod.z.union([import_zod.z.string(), import_zod.z.number(), import_zod.z.boolean(), import_zod.z.null()]);
80
+ var JsonSchema = import_zod.z.lazy(
81
+ () => import_zod.z.union([LiteralSchema, import_zod.z.array(JsonSchema), import_zod.z.record(JsonSchema)])
82
+ );
83
+
84
+ // packages/core/src/lib/zod/with-camel-case.preprocess.ts
85
+ var import_zod2 = require("zod");
86
+ var toCamelCase = (str, specialCases = {}) => {
87
+ if (specialCases[str]) {
88
+ return specialCases[str];
89
+ }
90
+ if (str.includes("_")) {
91
+ return str.toLowerCase().replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
92
+ }
93
+ if (str === str.toUpperCase()) {
94
+ return str.toLowerCase();
95
+ }
96
+ return str.charAt(0).toLowerCase() + str.slice(1);
97
+ };
98
+ var transformKeys = (options) => {
99
+ const { currentPath, data, preserve, specialCases } = options;
100
+ if (Array.isArray(data)) {
101
+ return data.map(
102
+ (item) => transformKeys({
103
+ currentPath,
104
+ data: item,
105
+ preserve,
106
+ specialCases
107
+ })
108
+ );
109
+ }
110
+ if (data && typeof data === "object" && data !== null) {
111
+ return Object.entries(data).reduce((acc, [key, value]) => {
112
+ const shouldPreserveValue = preserve.some(
113
+ (path) => [...currentPath, key].join(".").match(new RegExp(`^${path}.`))
114
+ );
115
+ const newKey = shouldPreserveValue ? key : toCamelCase(key, specialCases);
116
+ const newPath = [...currentPath, newKey];
117
+ return {
118
+ ...acc,
119
+ [newKey]: transformKeys({
120
+ currentPath: newPath,
121
+ data: value,
122
+ preserve,
123
+ specialCases
124
+ })
125
+ };
126
+ }, {});
127
+ }
128
+ return data;
129
+ };
130
+ var withCamelCase = (schema, options = {}) => {
131
+ const { preserve = [], specialCases = {} } = options;
132
+ return import_zod2.z.preprocess(
133
+ (data) => transformKeys({
134
+ currentPath: [],
135
+ data,
136
+ preserve,
137
+ specialCases
138
+ }),
139
+ schema
140
+ );
141
+ };
142
+
143
+ // packages/core/src/lib/zod/with-env-vars.preprocess.ts
144
+ var import_zod3 = require("zod");
145
+
146
+ // packages/core/src/lib/zod/with-replace-all.preprocess.ts
147
+ var import_zod4 = require("zod");
148
+
149
+ // packages/fly-node/src/lib/schemas/apps-create.schema.ts
150
+ var import_zod6 = require("zod");
151
+ var AppsCreateTransformedResponseSchema = withCamelCase(
152
+ import_zod6.z.object({
153
+ id: import_zod6.z.string(),
154
+ name: import_zod6.z.string(),
155
+ organization: import_zod6.z.object({
156
+ id: import_zod6.z.string(),
157
+ name: import_zod6.z.string()
158
+ })
159
+ })
160
+ );
161
+
162
+ // packages/fly-node/src/lib/schemas/apps-list.schema.ts
163
+ var import_zod8 = require("zod");
164
+ var AppsListTransformedResponseSchema = import_zod8.z.array(
165
+ withCamelCase(
166
+ import_zod8.z.object({
167
+ id: import_zod8.z.string(),
168
+ name: import_zod8.z.string(),
169
+ status: import_zod8.z.string(),
170
+ deployed: import_zod8.z.boolean(),
171
+ hostname: import_zod8.z.string(),
172
+ organization: import_zod8.z.object({
173
+ name: import_zod8.z.string(),
174
+ slug: import_zod8.z.string()
175
+ }),
176
+ currentRelease: import_zod8.z.nullable(
177
+ import_zod8.z.object({
178
+ status: import_zod8.z.string(),
179
+ createdAt: import_zod8.z.string().datetime()
180
+ })
181
+ )
182
+ })
183
+ )
184
+ );
185
+
186
+ // packages/fly-node/src/lib/schemas/certs-list-with-app.schema.ts
187
+ var import_zod12 = require("zod");
188
+
189
+ // packages/fly-node/src/lib/schemas/certs-list.schema.ts
190
+ var import_zod10 = require("zod");
191
+ var CertsListFlyResponseElementSchema = import_zod10.z.object({
192
+ createdAt: import_zod10.z.string().datetime(),
193
+ hostname: import_zod10.z.string(),
194
+ clientStatus: import_zod10.z.string()
195
+ });
196
+ var CertsListTransformedResponseSchema = import_zod10.z.array(
197
+ withCamelCase(CertsListFlyResponseElementSchema)
198
+ );
199
+
200
+ // packages/fly-node/src/lib/schemas/certs-list-with-app.schema.ts
201
+ var CertsListWithAppTransformedResponseSchema = import_zod12.z.array(
202
+ withCamelCase(
203
+ CertsListFlyResponseElementSchema.extend({
204
+ app: import_zod12.z.string()
205
+ })
206
+ )
207
+ );
208
+
209
+ // packages/fly-node/src/lib/schemas/config-show.schema.ts
210
+ var import_zod14 = require("zod");
211
+ var ConfigShowResponseSchema = withCamelCase(
212
+ import_zod14.z.object({
213
+ app: import_zod14.z.string(),
214
+ primaryRegion: import_zod14.z.string().optional(),
215
+ build: import_zod14.z.record(import_zod14.z.string(), import_zod14.z.any()).optional().or(
216
+ import_zod14.z.object({
217
+ args: import_zod14.z.record(import_zod14.z.string(), import_zod14.z.string()).optional(),
218
+ dockerfile: import_zod14.z.string().optional(),
219
+ image: import_zod14.z.string().optional()
220
+ })
221
+ ),
222
+ deploy: import_zod14.z.record(import_zod14.z.string(), import_zod14.z.any()).optional().or(import_zod14.z.object({ strategy: import_zod14.z.string().optional() })),
223
+ env: import_zod14.z.record(import_zod14.z.string(), import_zod14.z.string()).optional(),
224
+ httpService: import_zod14.z.record(import_zod14.z.string(), import_zod14.z.any()).optional(),
225
+ mounts: import_zod14.z.record(import_zod14.z.string(), import_zod14.z.any()).optional(),
226
+ services: import_zod14.z.array(import_zod14.z.record(import_zod14.z.string(), import_zod14.z.any())).optional()
227
+ }),
228
+ {
229
+ preserve: ["build.args", "env"]
230
+ }
231
+ );
232
+
233
+ // packages/fly-node/src/lib/schemas/deploy.schema.ts
234
+ var import_zod15 = require("zod");
235
+ var DeployResponseSchema = import_zod15.z.object({
236
+ app: import_zod15.z.string(),
237
+ hostname: import_zod15.z.string(),
238
+ url: import_zod15.z.string().url()
239
+ });
240
+
241
+ // packages/fly-node/src/lib/schemas/helper-schemas.ts
242
+ var import_zod16 = require("zod");
243
+ var AllowEmptyUrlSchema = import_zod16.z.string().url().or(import_zod16.z.literal(""));
244
+ var NameSchema = import_zod16.z.string({ message: "App name must be a valid slug" }).regex(/^[a-z0-9-]+$/);
245
+
246
+ // packages/fly-node/src/lib/schemas/postgres-list.ts
247
+ var import_zod18 = require("zod");
248
+ var PostgresListTransformedResponseSchema = import_zod18.z.array(
249
+ withCamelCase(
250
+ import_zod18.z.object({
251
+ deployed: import_zod18.z.boolean(),
252
+ hostname: import_zod18.z.string(),
253
+ id: import_zod18.z.string(),
254
+ name: import_zod18.z.string(),
255
+ organization: import_zod18.z.object({ id: import_zod18.z.string(), slug: import_zod18.z.string() }),
256
+ status: import_zod18.z.string(),
257
+ version: import_zod18.z.number()
258
+ })
259
+ )
260
+ );
261
+
262
+ // packages/fly-node/src/lib/schemas/postgres-users-list.ts
263
+ var import_zod20 = require("zod");
264
+ var PostgresUsersListTransformedResponseSchema = import_zod20.z.array(
265
+ withCamelCase(
266
+ import_zod20.z.object({
267
+ username: import_zod20.z.string(),
268
+ superuser: import_zod20.z.boolean(),
269
+ databases: import_zod20.z.array(import_zod20.z.string())
270
+ })
271
+ )
272
+ );
273
+
274
+ // packages/fly-node/src/lib/schemas/secrets-list-with-app.schema.ts
275
+ var import_zod24 = require("zod");
276
+
277
+ // packages/fly-node/src/lib/schemas/secrets-list.schema.ts
278
+ var import_zod22 = require("zod");
279
+ var SecretsListFlyResponseElementSchema = import_zod22.z.object({
280
+ name: import_zod22.z.string(),
281
+ digest: import_zod22.z.string(),
282
+ createdAt: import_zod22.z.string().datetime()
283
+ });
284
+ var SecretsListTransformedResponseSchema = import_zod22.z.array(
285
+ withCamelCase(SecretsListFlyResponseElementSchema)
286
+ );
287
+
288
+ // packages/fly-node/src/lib/schemas/secrets-list-with-app.schema.ts
289
+ var SecretsListWithAppTransformedResponseSchema = import_zod24.z.array(
290
+ withCamelCase(
291
+ SecretsListFlyResponseElementSchema.extend({
292
+ app: import_zod24.z.string()
293
+ })
294
+ )
295
+ );
296
+
297
+ // packages/fly-node/src/lib/schemas/status-extended.schema.ts
298
+ var import_zod28 = require("zod");
299
+
300
+ // packages/fly-node/src/lib/schemas/status.schema.ts
301
+ var import_zod26 = require("zod");
302
+ var statusFlyResponseSchema = import_zod26.z.object({
303
+ deployed: import_zod26.z.boolean(),
304
+ hostname: import_zod26.z.string(),
305
+ id: import_zod26.z.string(),
306
+ machines: import_zod26.z.array(
307
+ import_zod26.z.object({
308
+ id: import_zod26.z.string(),
309
+ name: import_zod26.z.string(),
310
+ state: import_zod26.z.string(),
311
+ region: import_zod26.z.string(),
312
+ createdAt: import_zod26.z.string().datetime(),
313
+ updatedAt: import_zod26.z.string().datetime(),
314
+ config: import_zod26.z.object({
315
+ env: import_zod26.z.record(import_zod26.z.string()),
316
+ metadata: import_zod26.z.record(import_zod26.z.string())
317
+ }),
318
+ events: import_zod26.z.array(
319
+ import_zod26.z.object({
320
+ type: import_zod26.z.string(),
321
+ status: import_zod26.z.string(),
322
+ timestamp: import_zod26.z.number()
323
+ })
324
+ ),
325
+ checks: import_zod26.z.array(
326
+ import_zod26.z.object({
327
+ name: import_zod26.z.string(),
328
+ status: import_zod26.z.string(),
329
+ output: import_zod26.z.string(),
330
+ updatedAt: import_zod26.z.string().datetime()
331
+ })
332
+ ).optional(),
333
+ hostStatus: import_zod26.z.string()
334
+ })
335
+ ),
336
+ name: import_zod26.z.string(),
337
+ organization: import_zod26.z.object({
338
+ id: import_zod26.z.string(),
339
+ slug: import_zod26.z.string()
340
+ }),
341
+ status: import_zod26.z.string(),
342
+ version: import_zod26.z.number()
343
+ });
344
+ var StatusTransformedResponseSchema = withCamelCase(
345
+ statusFlyResponseSchema,
346
+ {
347
+ preserve: ["machines.config.env", "machines.config.metadata"],
348
+ specialCases: { AppURL: "appUrl" }
349
+ }
350
+ );
351
+
352
+ // packages/fly-node/src/lib/schemas/status-extended.schema.ts
353
+ var StatusExtendedTransformedResponseSchema = withCamelCase(
354
+ statusFlyResponseSchema.extend({
355
+ domains: import_zod28.z.array(import_zod28.z.object({ hostname: import_zod28.z.string() })),
356
+ secrets: import_zod28.z.array(import_zod28.z.object({ name: import_zod28.z.string() }))
357
+ }),
358
+ {
359
+ preserve: ["machines.config.env", "machines.config.metadata"]
360
+ }
361
+ );
362
+
363
+ // packages/fly-node/src/lib/fly.class.ts
364
+ var Fly = class {
365
+ /** Use underscore to avoid conflict with public `config` property */
366
+ _config;
367
+ /**
368
+ * Whether a user is authenticated via local login.
369
+ * In this case a token is not needed, though it can still have been provided.
370
+ */
371
+ authByLogin = false;
372
+ initialized = false;
373
+ logger;
374
+ /**
375
+ * Get the app name from the instance config
376
+ */
377
+ get instanceApp() {
378
+ if ("app" in this._config) {
379
+ return this._config.app ?? "";
380
+ }
381
+ return "";
382
+ }
383
+ /**
384
+ * Get the config file path from the instance config
385
+ */
386
+ get instanceConfig() {
387
+ if ("config" in this._config) {
388
+ return this._config.config ?? "";
389
+ }
390
+ return "";
391
+ }
392
+ constructor(config) {
393
+ this._config = config || {};
394
+ this.logger = {
395
+ info: config?.logger?.info || console.log,
396
+ error: config?.logger?.error || console.error,
397
+ traceCLI: config?.logger?.traceCLI || false
398
+ };
399
+ if (!this._config.token) {
400
+ this._config.token = process.env["FLY_API_TOKEN"] || "";
401
+ }
402
+ }
403
+ /**
404
+ * Verify that the Fly client is ready to use.
405
+ *
406
+ * This means that the Fly CLI is installed and authenticated to Fly.io.
407
+ *
408
+ * Use as ad-hoc check when needed instead of waiting for the first Fly command to run.
409
+ *
410
+ * @param mode - Whether to use assertion mode instead of returning `false`
411
+ * @returns `true` if the Fly client is ready, `false` otherwise
412
+ * @throws An error in assertion mode if the Fly client is not ready
413
+ */
414
+ async isReady(mode) {
415
+ try {
416
+ await this.ensureInitialized();
417
+ return true;
418
+ } catch (error) {
419
+ if (mode === "assert") {
420
+ throw error;
421
+ }
422
+ this.logger.info(`Fly client is not ready
423
+ ${error}`);
424
+ return false;
425
+ }
426
+ }
427
+ /**
428
+ * Manage the Fly CLI tool
429
+ */
430
+ cli = {
431
+ /**
432
+ * Check if the Fly CLI tool is installed
433
+ *
434
+ * @returns `true` if the Fly CLI tool is installed, `false` otherwise
435
+ */
436
+ isInstalled: async () => await this.isInstalled()
437
+ };
438
+ //
439
+ // External API following the `flyctl` CLI commands structure
440
+ //
441
+ /**
442
+ * Manage apps
443
+ */
444
+ apps = {
445
+ /**
446
+ * Create a new application with a generated name when not provided.
447
+ *
448
+ * @param options - Options for creating an application
449
+ * @returns The name of the created application
450
+ * @throws An error if the application cannot be created
451
+ */
452
+ create: async (options) => {
453
+ try {
454
+ await this.ensureInitialized();
455
+ const { name } = await this.createApp(options);
456
+ this.logger.info(`Application '${name}' was created`);
457
+ return name;
458
+ } catch (error) {
459
+ throw new Error(
460
+ `[create app] something broke, check your apps
461
+ ${error}`
462
+ );
463
+ }
464
+ },
465
+ /**
466
+ * Destroy an application and make sure it gets detached from any Postgres clusters
467
+ *
468
+ * @param app - The name of the app to destroy
469
+ * @param options - Options for destroying an application
470
+ * @throws An error if the app cannot be destroyed
471
+ */
472
+ destroy: async (app, options) => {
473
+ try {
474
+ await this.ensureInitialized();
475
+ const attachedClusters = await this.getAttachedPostgresClusters(app);
476
+ for (const cluster of attachedClusters) {
477
+ this.logger.info(
478
+ `Detaching Postgres cluster '${cluster}' from application '${app}'`
479
+ );
480
+ await this.detachPostgres(cluster, app);
481
+ }
482
+ await this.destroyApp(app, options?.force);
483
+ this.logger.info(`Application '${app}' was destroyed`);
484
+ } catch (error) {
485
+ throw new Error(
486
+ `[destroy app] something broke, check your apps
487
+ ${error}`
488
+ );
489
+ }
490
+ },
491
+ /**
492
+ * List all applications
493
+ *
494
+ * @returns A list of applications
495
+ * @throws An error if listing applications fails
496
+ */
497
+ list: async () => {
498
+ try {
499
+ return await this.fetchAllApps("throwOnError");
500
+ } catch (error) {
501
+ throw new Error(`[list] something broke
502
+ ${error}`);
503
+ }
504
+ }
505
+ };
506
+ /**
507
+ * Manage certificates
508
+ */
509
+ certs = {
510
+ /**
511
+ * Add a certificate for a domain to an application
512
+ *
513
+ * @param hostname - The hostname to add a certificate for
514
+ * @param options - Options for adding a certificate
515
+ * @throws An error if the certificate cannot be added
516
+ */
517
+ add: async (hostname, options) => {
518
+ try {
519
+ await this.ensureInitialized();
520
+ const appName = await this.addAppCertificate(hostname, options);
521
+ this.logger.info(
522
+ `Certificate for domain '${hostname}' was added to '${appName}'`
523
+ );
524
+ } catch (error) {
525
+ throw new Error(
526
+ `[add certificate] something broke, check your app certificates
527
+ ${error}`
528
+ );
529
+ }
530
+ },
531
+ /**
532
+ * List certificates for an application
533
+ *
534
+ * @param options - List certificates for an application or all certificates
535
+ * @returns A list of certificates
536
+ * @throws An error if listing certificates fails
537
+ */
538
+ list: async (options) => {
539
+ try {
540
+ await this.ensureInitialized();
541
+ const result = options === "all" ? await this.fetchAllCerts("throwOnError") : await this.fetchAppCerts("throwOnError", options);
542
+ return result;
543
+ } catch (error) {
544
+ throw new Error(`[list certificates] something broke
545
+ ${error}`);
546
+ }
547
+ },
548
+ /**
549
+ * Remove a certificate for a domain from an application
550
+ *
551
+ * @param hostname - The hostname to remove a certificate for
552
+ * @param options - Options for removing a certificate
553
+ * @throws An error if the certificate cannot be removed
554
+ */
555
+ remove: async (hostname, options) => {
556
+ try {
557
+ await this.ensureInitialized();
558
+ const appName = await this.removeAppCertificate(hostname, options);
559
+ this.logger.info(
560
+ `Certificate for domain '${hostname}' was removed from '${appName}'`
561
+ );
562
+ } catch (error) {
563
+ throw new Error(
564
+ `[remove certificate] something broke, check your app certificates
565
+ ${error}`
566
+ );
567
+ }
568
+ }
569
+ };
570
+ /**
571
+ * Manage an app's configuration
572
+ */
573
+ config = {
574
+ /**
575
+ * Show an application's configuration.
576
+ *
577
+ * @param options - Options for showing an application's configuration
578
+ * @returns The application's JSON configuration
579
+ * @throws An error if the configuration cannot be found or parsed
580
+ */
581
+ show: async (options) => {
582
+ try {
583
+ await this.ensureInitialized();
584
+ return await this.showConfig("throwOnError", options);
585
+ } catch (error) {
586
+ throw new Error(`[show config] something broke
587
+ ${error}`);
588
+ }
589
+ }
590
+ };
591
+ /**
592
+ * Deploy an application.
593
+ *
594
+ * A valid config file is required but the app doesn't have to exist,
595
+ * since it gets created if needed.
596
+ *
597
+ * The app name is selected from:
598
+ * 1. Provided app name
599
+ * 2. Instance app name
600
+ * 3. App name from the provided config file
601
+ *
602
+ * Existing secrets are preserved.
603
+ *
604
+ * @param options - Options for deploying an application
605
+ * @throws An error if the deployment fails
606
+ */
607
+ deploy = async (options) => {
608
+ try {
609
+ await this.ensureInitialized();
610
+ const appName = await this.deployApp(options);
611
+ this.logger.info(`Application '${appName}' was deployed`);
612
+ const status = await this.fetchAppStatus("throwOnError", {
613
+ app: appName
614
+ });
615
+ return DeployResponseSchema.parse({
616
+ app: status.name,
617
+ hostname: status.hostname,
618
+ url: `https://${status.hostname}`
619
+ });
620
+ } catch (error) {
621
+ throw new Error(
622
+ `[deploy] something broke, check your deployments
623
+ ${error}`
624
+ );
625
+ }
626
+ };
627
+ /**
628
+ * Manage application secrets
629
+ */
630
+ secrets = {
631
+ /**
632
+ * Set secrets for an application
633
+ *
634
+ * @param secrets - The secrets to set
635
+ * @param options - Options for setting secrets
636
+ * @throws An error if the secrets cannot be set
637
+ */
638
+ set: async (secrets, options) => {
639
+ try {
640
+ await this.ensureInitialized();
641
+ const appName = await this.setAppSecrets(secrets, options);
642
+ const keys = Object.keys(secrets);
643
+ this.logger.info(
644
+ `Secrets were set for '${appName}': ${keys.join(", ")}`
645
+ );
646
+ } catch (error) {
647
+ throw new Error(
648
+ `[set secrets] something broke, check your app secrets
649
+ ${error}`
650
+ );
651
+ }
652
+ },
653
+ /**
654
+ * List secrets for an application
655
+ *
656
+ * @param options - List secrets for an application or all secrets
657
+ * @returns A list of secrets
658
+ * @throws An error if listing secrets fails
659
+ */
660
+ list: async (options) => {
661
+ try {
662
+ await this.ensureInitialized();
663
+ const result = options === "all" ? await this.fetchAllSecrets("throwOnError") : await this.fetchAppSecrets("throwOnError", options);
664
+ return result;
665
+ } catch (error) {
666
+ throw new Error(`[list secrets] something broke
667
+ ${error}`);
668
+ }
669
+ },
670
+ /**
671
+ * Unset secrets for an application
672
+ *
673
+ * @param keys - The keys to unset
674
+ * @param options - Options for unsetting secrets
675
+ * @throws An error if the secrets cannot be unset
676
+ */
677
+ unset: async (keys, options) => {
678
+ try {
679
+ await this.ensureInitialized();
680
+ const keysArray = Array.isArray(keys) ? keys : [keys];
681
+ const appName = await this.unsetAppSecrets(keysArray, options);
682
+ this.logger.info(
683
+ `Secrets were unset for '${appName}': ${keysArray.join(", ")}`
684
+ );
685
+ } catch (error) {
686
+ throw new Error(
687
+ `[unset secrets] something broke, check your app secrets
688
+ ${error}`
689
+ );
690
+ }
691
+ }
692
+ };
693
+ /**
694
+ * Get the status details of an application
695
+ *
696
+ * @param options - Options for getting app status
697
+ * @returns The app status, or `null` if an app could not be found
698
+ */
699
+ status = async (options) => {
700
+ try {
701
+ await this.ensureInitialized();
702
+ const status = await this.fetchAppStatus("nullOnError", options);
703
+ if (status === null) {
704
+ return null;
705
+ }
706
+ return status;
707
+ } catch (error) {
708
+ this.logger.info(`[status] something broke
709
+ ${error}`);
710
+ return null;
711
+ }
712
+ };
713
+ /**
714
+ * Get the extended details of an application
715
+ *
716
+ * @param options - Options for getting app details
717
+ * @returns The app details, or `null` if an app could not be found
718
+ */
719
+ statusExtended = async (options) => {
720
+ try {
721
+ await this.ensureInitialized();
722
+ const status = await this.fetchAppStatus("nullOnError", options);
723
+ if (status === null) {
724
+ return null;
725
+ }
726
+ const certs = await this.fetchAppCerts("nullOnError", options) || [];
727
+ const secrets = await this.fetchAppSecrets("nullOnError", options) || [];
728
+ return StatusExtendedTransformedResponseSchema.parse({
729
+ ...status,
730
+ domains: certs.map(({ hostname }) => ({ hostname })),
731
+ secrets: secrets.map(({ name }) => ({ name }))
732
+ });
733
+ } catch (error) {
734
+ this.logger.info(`[status extended] something broke
735
+ ${error}`);
736
+ return null;
737
+ }
738
+ };
739
+ //
740
+ // Private methods
741
+ //
742
+ /**
743
+ * @private
744
+ * A name will be generated when not provided.
745
+ * @returns The name of the created application
746
+ * @throws An error if the application cannot be created
747
+ */
748
+ async createApp(options) {
749
+ const args = ["apps", "create"];
750
+ args.push(options?.app || "--generate-name");
751
+ args.push("--org", options?.org || this._config.org || "personal");
752
+ args.push("--json");
753
+ return AppsCreateTransformedResponseSchema.parseAsync(
754
+ await this.execFly(args)
755
+ );
756
+ }
757
+ /**
758
+ * @private
759
+ * @returns The name of the deployed application
760
+ * @throws An error if the deployment fails
761
+ */
762
+ async deployApp(options) {
763
+ let appName = "";
764
+ let appSecrets = [];
765
+ let lookupApp = options?.app || this.instanceApp;
766
+ const lookupConfig = options?.config || this.instanceConfig;
767
+ if (!lookupConfig) {
768
+ throw new Error(
769
+ "Fly config file must be provided to options or class instance, unable to deploy"
770
+ );
771
+ }
772
+ const appConfig = await this.showConfig("nullOnError", {
773
+ config: lookupConfig,
774
+ local: true
775
+ });
776
+ if (!appConfig) {
777
+ throw new Error(
778
+ `Fly config file '${lookupConfig}' does not exist, unable to deploy`
779
+ );
780
+ }
781
+ if (!lookupApp) {
782
+ lookupApp = appConfig.app;
783
+ }
784
+ if (lookupApp) {
785
+ const status = await this.fetchAppStatus("nullOnError", {
786
+ app: lookupApp
787
+ });
788
+ if (status) {
789
+ this.logger.info(
790
+ `Found existing application '${lookupApp}' as target for deployment`
791
+ );
792
+ appName = status.name;
793
+ } else {
794
+ this.logger.info(
795
+ `Application '${lookupApp}' not found, try to create a new one with this name`
796
+ );
797
+ }
798
+ }
799
+ if (!appName) {
800
+ this.logger.info("Creating a new application...");
801
+ const { name } = await this.createApp({
802
+ app: lookupApp,
803
+ org: options?.org
804
+ });
805
+ appName = name;
806
+ this.logger.info(`Application '${appName}' was created`);
807
+ } else {
808
+ appSecrets = await this.fetchAppSecrets("throwOnError", { app: appName });
809
+ this.logger.info(`Updating existing application '${appName}'`);
810
+ }
811
+ NameSchema.parse(appName);
812
+ if (options?.secrets) {
813
+ const existingSecrets = new Set(appSecrets.map(({ name }) => name));
814
+ const newSecrets = {};
815
+ for (const [key, value] of Object.entries(options.secrets)) {
816
+ if (!existingSecrets.has(key)) {
817
+ newSecrets[key] = value;
818
+ } else {
819
+ this.logger.info(
820
+ `Secret '${key}' already exists for '${appName}', skipping`
821
+ );
822
+ }
823
+ }
824
+ const keys = Object.keys(newSecrets);
825
+ if (keys.length > 0) {
826
+ this.logger.info(`Adding secrets to '${appName}': ${keys.join(", ")}`);
827
+ await this.setAppSecrets(newSecrets, {
828
+ app: appName,
829
+ stage: true
830
+ });
831
+ }
832
+ }
833
+ if (options?.app && options.app !== appName) {
834
+ this.logger.info(
835
+ `Using provided app name '${options.app}' instead of '${appName}'`
836
+ );
837
+ appName = options.app;
838
+ }
839
+ if (options?.postgres) {
840
+ const users = await this.fetchPostgresUsers(
841
+ options.postgres,
842
+ "nullOnError"
843
+ );
844
+ if (!users) {
845
+ this.logger.error(
846
+ `Failed to fetch users for Postgres cluster '${options.postgres}', unable to attach '${appName}'`
847
+ );
848
+ } else if (users.find((user) => user.username === appName.replace(/-/g, "_"))) {
849
+ this.logger.info(
850
+ `Postgres cluster '${options.postgres}' already attached to '${appName}', skipping`
851
+ );
852
+ } else {
853
+ this.logger.info(
854
+ `Attach Postgres cluster '${options.postgres}' to '${appName}'`
855
+ );
856
+ await this.attachPostgres(options.postgres, appName);
857
+ }
858
+ }
859
+ const args = ["deploy", "--app", appName, "--config", lookupConfig];
860
+ if (options?.region) {
861
+ args.push("--region", options.region);
862
+ }
863
+ if (options?.environment) {
864
+ args.push("--env", `DEPLOY_ENV=${options.environment}`);
865
+ }
866
+ for (const [key, value] of Object.entries(options?.env || {})) {
867
+ args.push("--env", `${key}=${this.safeArg(value)}`);
868
+ }
869
+ args.push("--yes");
870
+ this.logger.info(`Deploying '${appName}'...`);
871
+ await this.execFly(args);
872
+ return appName;
873
+ }
874
+ /**
875
+ * @private
876
+ * @throws An error if the Postgres database cannot be attached
877
+ */
878
+ async attachPostgres(postgres, app) {
879
+ const args = ["postgres", "attach", postgres, "--app", app, "--yes"];
880
+ await this.execFly(args);
881
+ }
882
+ /**
883
+ * @private
884
+ * @throws An error if the app cannot be destroyed
885
+ */
886
+ async destroyApp(app, force) {
887
+ const args = ["apps", "destroy", app, "--yes"];
888
+ if (force)
889
+ args.push("--force");
890
+ await this.execFly(args);
891
+ }
892
+ /**
893
+ * @private
894
+ * @throws An error if the Postgres database cannot be detached from an app
895
+ */
896
+ async detachPostgres(postgres, app) {
897
+ const args = ["postgres", "detach", postgres, "--app", app];
898
+ await this.execFly(args);
899
+ }
900
+ /**
901
+ * @private
902
+ * @returns The name of the application
903
+ * @throws An error if the secrets cannot be set
904
+ */
905
+ async setAppSecrets(secrets, options) {
906
+ const status = await this.fetchAppStatus("throwOnError", options);
907
+ const args = ["secrets", "set"];
908
+ args.push(...this.getAppOrConfigArgs(options));
909
+ if (options?.stage) {
910
+ args.push("--stage");
911
+ }
912
+ for (const [key, value] of Object.entries(secrets)) {
913
+ args.push(`${key}=${this.safeArg(value)}`);
914
+ }
915
+ await this.execFly(args);
916
+ return NameSchema.parse(status.name);
917
+ }
918
+ /**
919
+ * @private
920
+ * @returns The name of the application
921
+ * @throws An error if the secrets cannot be unset
922
+ */
923
+ async unsetAppSecrets(keys, options) {
924
+ const status = await this.fetchAppStatus("throwOnError", options);
925
+ const args = ["secrets", "unset"];
926
+ args.push(...this.getAppOrConfigArgs(options));
927
+ if (options?.stage) {
928
+ args.push("--stage");
929
+ }
930
+ args.push(...keys);
931
+ await this.execFly(args);
932
+ return NameSchema.parse(status.name);
933
+ }
934
+ /**
935
+ * @private
936
+ * @returns The name of the application
937
+ * @throws An error if the domain cannot be added
938
+ */
939
+ async addAppCertificate(hostname, options) {
940
+ const status = await this.fetchAppStatus("throwOnError", options);
941
+ const args = ["certs", "add", hostname];
942
+ args.push(...this.getAppOrConfigArgs(options));
943
+ args.push("--json");
944
+ await this.execFly(args);
945
+ return NameSchema.parse(status.name);
946
+ }
947
+ /**
948
+ * @private
949
+ * @returns The name of the application
950
+ * @throws An error if the domain cannot be removed
951
+ */
952
+ async removeAppCertificate(hostname, options) {
953
+ const status = await this.fetchAppStatus("throwOnError", options);
954
+ const args = ["certs", "remove", hostname];
955
+ args.push(...this.getAppOrConfigArgs(options));
956
+ args.push("--yes");
957
+ await this.execFly(args);
958
+ return NameSchema.parse(status.name);
959
+ }
960
+ async fetchAllApps(onError) {
961
+ const args = ["apps", "list", "--json"];
962
+ try {
963
+ return AppsListTransformedResponseSchema.parseAsync(
964
+ await this.execFly(args)
965
+ );
966
+ } catch (error) {
967
+ if (onError === "throwOnError") {
968
+ throw error;
969
+ }
970
+ return null;
971
+ }
972
+ }
973
+ async fetchAllCerts(onError) {
974
+ try {
975
+ const certs = [];
976
+ const apps = await this.fetchAllApps("throwOnError");
977
+ for (const app of apps) {
978
+ const appCerts = await this.fetchAppCerts("throwOnError", {
979
+ app: app.name
980
+ });
981
+ certs.push(...appCerts.map((cert) => ({ ...cert, app: app.name })));
982
+ }
983
+ return CertsListWithAppTransformedResponseSchema.parse(certs);
984
+ } catch (error) {
985
+ if (onError === "throwOnError") {
986
+ throw error;
987
+ }
988
+ return null;
989
+ }
990
+ }
991
+ async fetchAllPostgres(onError) {
992
+ const args = ["postgres", "list", "--json"];
993
+ try {
994
+ const response = await this.execFly(args);
995
+ return PostgresListTransformedResponseSchema.parse(response);
996
+ } catch (error) {
997
+ if (onError === "throwOnError") {
998
+ throw error;
999
+ }
1000
+ return null;
1001
+ }
1002
+ }
1003
+ async fetchAllSecrets(onError) {
1004
+ try {
1005
+ const secrets = [];
1006
+ const apps = await this.fetchAllApps("throwOnError");
1007
+ for (const app of apps) {
1008
+ const appSecrets = await this.fetchAppSecrets("throwOnError", {
1009
+ app: app.name
1010
+ });
1011
+ secrets.push(
1012
+ ...appSecrets.map((secret) => ({ ...secret, app: app.name }))
1013
+ );
1014
+ }
1015
+ return SecretsListWithAppTransformedResponseSchema.parse(secrets);
1016
+ } catch (error) {
1017
+ if (onError === "throwOnError") {
1018
+ throw error;
1019
+ }
1020
+ return null;
1021
+ }
1022
+ }
1023
+ async fetchAppStatus(onError, options) {
1024
+ const args = ["status"];
1025
+ args.push(...this.getAppOrConfigArgs(options));
1026
+ args.push("--json");
1027
+ let response = null;
1028
+ try {
1029
+ response = await this.execFly(args);
1030
+ return StatusTransformedResponseSchema.parse(response);
1031
+ } catch (error) {
1032
+ if (onError === "throwOnError") {
1033
+ throw error;
1034
+ }
1035
+ if (error instanceof import_zod29.ZodError) {
1036
+ this.logger.info(`Failed to parse response:
1037
+ ${error.message}`);
1038
+ this.logger.info(`Raw response:
1039
+ ${JSON.stringify(response, null, 2)}`);
1040
+ }
1041
+ return null;
1042
+ }
1043
+ }
1044
+ async fetchAppCerts(onError, options) {
1045
+ const args = ["certs", "list"];
1046
+ args.push(...this.getAppOrConfigArgs(options));
1047
+ args.push("--json");
1048
+ try {
1049
+ return CertsListTransformedResponseSchema.parseAsync(
1050
+ await this.execFly(args)
1051
+ );
1052
+ } catch (error) {
1053
+ if (onError === "throwOnError") {
1054
+ throw error;
1055
+ }
1056
+ return null;
1057
+ }
1058
+ }
1059
+ async fetchAppSecrets(onError, options) {
1060
+ const args = ["secrets", "list"];
1061
+ args.push(...this.getAppOrConfigArgs(options));
1062
+ args.push("--json");
1063
+ try {
1064
+ return SecretsListTransformedResponseSchema.parseAsync(
1065
+ await this.execFly(args)
1066
+ );
1067
+ } catch (error) {
1068
+ if (onError === "throwOnError") {
1069
+ throw error;
1070
+ }
1071
+ return null;
1072
+ }
1073
+ }
1074
+ async fetchPostgresUsers(postgresApp, onError) {
1075
+ const args = ["postgres", "users", "list", "--app", postgresApp, "--json"];
1076
+ try {
1077
+ const users = await this.execFly(args);
1078
+ return PostgresUsersListTransformedResponseSchema.parse(users);
1079
+ } catch (error) {
1080
+ if (onError === "throwOnError") {
1081
+ throw error;
1082
+ }
1083
+ return null;
1084
+ }
1085
+ }
1086
+ async showConfig(onError, options) {
1087
+ const normalized = this.normalizeOptions(options);
1088
+ const config = normalized.config || this.instanceConfig;
1089
+ if (config && !(0, import_fs.existsSync)((0, import_path.join)((0, import_process.cwd)(), config))) {
1090
+ throw new Error(`Config file '${config}' does not exist`);
1091
+ }
1092
+ const args = ["config", "show"];
1093
+ args.push(...this.getAppOrConfigArgs(options));
1094
+ if (options && "local" in options && options.local) {
1095
+ args.push("--local");
1096
+ }
1097
+ try {
1098
+ return ConfigShowResponseSchema.parse(await this.execFly(args));
1099
+ } catch (error) {
1100
+ if (onError === "throwOnError") {
1101
+ throw error;
1102
+ }
1103
+ return null;
1104
+ }
1105
+ }
1106
+ /**
1107
+ * @private
1108
+ * Ensure Fly CLI is installed and authenticated
1109
+ *
1110
+ * @throws An error if Fly CLI is not installed or authentication fails
1111
+ */
1112
+ async ensureInitialized() {
1113
+ if (this.initialized)
1114
+ return;
1115
+ try {
1116
+ if (!await this.isInstalled()) {
1117
+ throw new Error("Fly CLI must be installed to use this library");
1118
+ }
1119
+ this.logger.info("Authenticating with Fly.io...");
1120
+ let user = await this.execFly(
1121
+ ["auth", "whoami"],
1122
+ "nullOnError",
1123
+ true
1124
+ // won't use token
1125
+ );
1126
+ if (user) {
1127
+ this.logger.info(`Detected logged in user '${user}'`);
1128
+ this.authByLogin = true;
1129
+ } else {
1130
+ user = await this.execFly(["auth", "whoami"]);
1131
+ this.logger.info(`Authenticated by token as '${user}'`);
1132
+ }
1133
+ this.initialized = true;
1134
+ } catch (error) {
1135
+ this.logger.error("Failed to initialize Fly");
1136
+ throw error;
1137
+ }
1138
+ }
1139
+ async execFly(command, onError = "throwOnError", skipToken) {
1140
+ const cmdArr = Array.isArray(command) ? command : [command];
1141
+ if (!skipToken && !this.authByLogin && this._config.token) {
1142
+ cmdArr.push("--access-token", this._config.token);
1143
+ }
1144
+ const flyCmd = `flyctl ${cmdArr.filter(Boolean).join(" ")}`;
1145
+ let stdout = "";
1146
+ try {
1147
+ this.traceCLI("CALL", flyCmd);
1148
+ const result = await exec(flyCmd);
1149
+ stdout = result.stdout.trim();
1150
+ this.traceCLI("RESULT", stdout);
1151
+ } catch (error) {
1152
+ this.traceCLI("RESULT", error);
1153
+ if (onError === "throwOnError") {
1154
+ throw new Error(`Command failed: ${flyCmd}
1155
+ ${error}`);
1156
+ }
1157
+ return null;
1158
+ }
1159
+ try {
1160
+ return JSON.parse(stdout);
1161
+ } catch {
1162
+ if (stdout) {
1163
+ if (this.logger.traceCLI) {
1164
+ this.logger.info(`Failed to parse as JSON, returning raw output`);
1165
+ }
1166
+ return stdout;
1167
+ }
1168
+ }
1169
+ return void 0;
1170
+ }
1171
+ /**
1172
+ * @private
1173
+ * Get the arguments for `AppOrConfig` options
1174
+ * where either the application or configuration can be provided
1175
+ * but not both.
1176
+ *
1177
+ * First check `options` and then the class configuration.
1178
+ *
1179
+ * Should be used in Fly commands with optional flags
1180
+ * - `--app`
1181
+ * - `--config`
1182
+ *
1183
+ * @param options - Options to get the arguments for
1184
+ * @returns The arguments to use in a fly command
1185
+ */
1186
+ getAppOrConfigArgs(options) {
1187
+ const normalized = this.normalizeOptions(options);
1188
+ const app = normalized.app || this.instanceApp;
1189
+ const config = normalized.config || this.instanceConfig;
1190
+ const args = [];
1191
+ if (app) {
1192
+ args.push("--app", app);
1193
+ }
1194
+ if (config) {
1195
+ args.push("--config", config);
1196
+ }
1197
+ if (app && config) {
1198
+ this.logger.info(
1199
+ `Both app '${app}' and config '${config}' were provided, check your implementation!`
1200
+ );
1201
+ }
1202
+ return args;
1203
+ }
1204
+ /**
1205
+ * @private
1206
+ * Get the Postgres clusters attached to an app
1207
+ *
1208
+ * @param app - The app to get the attached Postgres clusters for
1209
+ * @returns The attached Postgres clusters
1210
+ * @throws An error if the Postgres clusters cannot be retrieved
1211
+ */
1212
+ async getAttachedPostgresClusters(app) {
1213
+ const attached = /* @__PURE__ */ new Set();
1214
+ const postgres = await this.fetchAllPostgres("throwOnError");
1215
+ for (const { name } of postgres) {
1216
+ const users = await this.fetchPostgresUsers(name, "nullOnError");
1217
+ if (!users) {
1218
+ this.logger.info(
1219
+ `Failed to fetch users for Postgres cluster '${name}', ignoring`
1220
+ );
1221
+ continue;
1222
+ }
1223
+ if (users.some((user) => user.username === app.replace(/-/g, "_"))) {
1224
+ attached.add(name);
1225
+ }
1226
+ }
1227
+ return Array.from(attached);
1228
+ }
1229
+ /**
1230
+ * @private
1231
+ * Check if the Fly CLI is installed
1232
+ *
1233
+ * @returns `true` if the Fly CLI is installed, `false` otherwise
1234
+ */
1235
+ async isInstalled() {
1236
+ return await this.execFly("version", "nullOnError") !== null;
1237
+ }
1238
+ /**
1239
+ * @private
1240
+ * Normalize the options matching `AppOrConfig` type.
1241
+ *
1242
+ * A missing value gets an empty string.
1243
+ *
1244
+ * @param options - The options to normalize
1245
+ * @returns The normalized options
1246
+ */
1247
+ normalizeOptions(options) {
1248
+ if (!options) {
1249
+ return { app: "", config: "" };
1250
+ }
1251
+ const app = "app" in options && options.app ? options.app : "";
1252
+ const config = "config" in options && options.config ? options.config : "";
1253
+ return { app, config };
1254
+ }
1255
+ /**
1256
+ * Escape an argument for Fly cli
1257
+ *
1258
+ * @param arg - The argument to escape
1259
+ * @returns The escaped argument
1260
+ */
1261
+ safeArg(arg) {
1262
+ return arg.replace(/\\/g, "\\\\").replace(/ /g, "\\ ");
1263
+ }
1264
+ /**
1265
+ * @private
1266
+ * Trace the CLI calls, mocks and results
1267
+ *
1268
+ * @param type - The type of trace
1269
+ * @param msg - The message to trace
1270
+ */
1271
+ traceCLI(type, msg) {
1272
+ if (this.logger.traceCLI) {
1273
+ const typeLabel = type === "CALL" ? " CALL " : type === "MOCK" ? " MOCK " : "RESULT";
1274
+ this.logger.info(`[${typeLabel}] ${msg}`);
1275
+ }
1276
+ }
1277
+ };
1278
+ // Annotate the CommonJS export names for ESM import in node:
1279
+ 0 && (module.exports = {
1280
+ Fly
1281
+ });