@cdwr/fly-node 0.2.3 → 0.3.1

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.js CHANGED
@@ -1,47 +1,528 @@
1
+ // packages/fly-node/src/lib/schemas/certificate.schema.ts
2
+ import { z } from "zod";
3
+ var CertificateApiResponseSchema = z.object({
4
+ hostname: z.string(),
5
+ /** Issued and serving. This is what decides whether a domain is usable */
6
+ isConfigured: z.boolean(),
7
+ id: z.string().optional(),
8
+ /** The apex or a subdomain — apex domains cannot use a CNAME */
9
+ isApex: z.boolean().optional(),
10
+ isWildcard: z.boolean().optional(),
11
+ /** Which ACME challenge has been satisfied, if any */
12
+ isAcmeDnsConfigured: z.boolean().optional(),
13
+ isAcmeAlpnConfigured: z.boolean().optional(),
14
+ isAcmeHttpConfigured: z.boolean().optional(),
15
+ certificateAuthority: z.string().nullish(),
16
+ certificateRequestedAt: z.string().nullish(),
17
+ createdAt: z.string().nullish(),
18
+ domain: z.string().nullish(),
19
+ dnsProvider: z.string().nullish(),
20
+ /** Hostname the validation record must be created on */
21
+ dnsValidationHostname: z.string().nullish(),
22
+ /** Value that record must contain */
23
+ dnsValidationTarget: z.string().nullish(),
24
+ /** Fly's own prose describing the records to create */
25
+ dnsValidationInstructions: z.string().nullish(),
26
+ /** Fly's summary of where issuance has got to */
27
+ clientStatus: z.string().nullish(),
28
+ /**
29
+ * Set when Let's Encrypt has rate-limited further attempts for this domain.
30
+ *
31
+ * Worth surfacing rather than swallowing: it is the one failure a customer
32
+ * cannot fix by correcting DNS, and retrying only makes it worse.
33
+ */
34
+ rateLimitedUntil: z.string().nullish(),
35
+ source: z.string().nullish(),
36
+ /**
37
+ * Fly's own prose for a failed issuance attempt — what the dashboard shows,
38
+ * unlike `HostnameCheck.errors`, which is SCREAMING_SNAKE_CASE codes
39
+ */
40
+ validationErrors: z.array(
41
+ z.object({
42
+ message: z.string(),
43
+ timestamp: z.string()
44
+ })
45
+ ).nullish(),
46
+ /**
47
+ * The certificates actually issued for this hostname, once any have been.
48
+ *
49
+ * A connection rather than a list because that is how Fly models it. Two
50
+ * nodes is the normal count — one RSA and one ECDSA — sharing an expiry,
51
+ * which is why a caller usually wants the expiry rather than the rows.
52
+ */
53
+ issued: z.object({
54
+ nodes: z.array(
55
+ z.object({
56
+ id: z.string().nullish(),
57
+ /** Key type, e.g. `RSA` or `ECDSA` */
58
+ type: z.string().nullish(),
59
+ hostname: z.string().nullish(),
60
+ expiresAt: z.string().nullish()
61
+ })
62
+ ).nullish()
63
+ }).nullish()
64
+ });
65
+ var HostnameCheckApiResponseSchema = z.object({
66
+ aRecords: z.array(z.string()).nullish(),
67
+ aaaaRecords: z.array(z.string()).nullish(),
68
+ cnameRecords: z.array(z.string()).nullish(),
69
+ caaRecords: z.array(z.string()).nullish(),
70
+ soa: z.string().nullish(),
71
+ dnsProvider: z.string().nullish(),
72
+ dnsVerificationRecord: z.string().nullish(),
73
+ dnsConfigured: z.boolean().nullish(),
74
+ acmeDnsConfigured: z.boolean().nullish(),
75
+ resolvedAddresses: z.array(z.string()).nullish(),
76
+ isProxied: z.boolean().nullish(),
77
+ errors: z.array(z.string()).nullish()
78
+ });
79
+ var DnsInstructionsSchema = z.object({
80
+ hostname: z.string().nullish(),
81
+ target: z.string().nullish(),
82
+ instructions: z.string().nullish(),
83
+ isApex: z.boolean().optional()
84
+ });
85
+ var CertificateListApiResponseSchema = z.array(
86
+ CertificateApiResponseSchema
87
+ );
88
+
89
+ // packages/fly-node/src/lib/schemas/machine.schema.ts
90
+ import { z as z2 } from "zod";
91
+ var MachineApiResponseSchema = z2.object({
92
+ id: z2.string(),
93
+ name: z2.string().nullish(),
94
+ /** `started`, `stopped`, `suspended`, … — Fly owns this vocabulary */
95
+ state: z2.string().nullish(),
96
+ region: z2.string().nullish()
97
+ });
98
+ var MachineListApiResponseSchema = z2.array(MachineApiResponseSchema);
99
+
100
+ // packages/fly-node/src/lib/fly-api.class.ts
101
+ var FLY_API_URL = "https://api.fly.io/graphql";
102
+ var FLY_MACHINES_URL = "https://api.machines.dev/v1";
103
+ var FlyApiError = class extends Error {
104
+ errors;
105
+ constructor(message, errors) {
106
+ super(message);
107
+ this.name = "FlyApiError";
108
+ this.errors = errors;
109
+ }
110
+ /** Whether every error is Fly saying the thing simply does not exist */
111
+ get isNotFound() {
112
+ return this.errors.length > 0 && this.errors.every((error) => error.extensions?.code === "NOT_FOUND");
113
+ }
114
+ /**
115
+ * Whether every error is Fly refusing a hostname that already has a
116
+ * certificate on the app.
117
+ *
118
+ * No `extensions.code` comes with this one — Fly's own dashboard and
119
+ * `flyctl` hit the same message, and both work around it the same way this
120
+ * class does, by re-reading rather than retrying the mutation.
121
+ */
122
+ get isAlreadyExists() {
123
+ return this.errors.length > 0 && this.errors.every((error) => /already exists/i.test(error.message));
124
+ }
125
+ };
126
+ var FlyApi = class {
127
+ token;
128
+ apiUrl;
129
+ machinesUrl;
130
+ log;
131
+ constructor(config) {
132
+ if (!config.token) {
133
+ throw new Error("[fly-api] A Fly API token is required");
134
+ }
135
+ this.token = config.token;
136
+ this.apiUrl = config.apiUrl ?? FLY_API_URL;
137
+ this.machinesUrl = config.machinesUrl ?? FLY_MACHINES_URL;
138
+ this.log = config.log ?? (() => void 0);
139
+ }
140
+ /**
141
+ * Manage certificates for an app.
142
+ *
143
+ * Every method takes the app name explicitly: this client is used by a
144
+ * process acting on *other* apps — the cms managing a tenant's web app — so
145
+ * there is no ambient "current app" to default to.
146
+ */
147
+ certs = {
148
+ /**
149
+ * Request a certificate for a hostname.
150
+ *
151
+ * Safe to call when one already exists: Fly's own mutation is not
152
+ * idempotent — a hostname it already has a certificate for on this app is
153
+ * a fault, not a no-op, so this re-reads the existing certificate itself
154
+ * rather than surfacing that as an error a caller has to know to expect.
155
+ *
156
+ * Requesting before DNS is in place is normal and expected — the
157
+ * certificate stays pending until the records resolve, and the returned
158
+ * validation fields are what you show the customer meanwhile.
159
+ *
160
+ * @param app - Fly app name the domain should serve from
161
+ * @param hostname - Domain without a scheme, e.g. `tours.example.com`
162
+ * @returns The certificate, plus what Fly resolves for that hostname now
163
+ */
164
+ add: async (app, hostname) => {
165
+ try {
166
+ const data = await this.request(
167
+ `mutation AddCertificate($appId: ID!, $hostname: String!) {
168
+ addCertificate(appId: $appId, hostname: $hostname) {
169
+ certificate { ${CERTIFICATE_FIELDS} }
170
+ check { ${HOSTNAME_CHECK_FIELDS} }
171
+ }
172
+ }`,
173
+ { appId: app, hostname }
174
+ );
175
+ return {
176
+ certificate: CertificateApiResponseSchema.parse(
177
+ data.addCertificate.certificate
178
+ ),
179
+ // Live resolution, and it comes back with the mutation for free —
180
+ // the customer has usually just edited DNS and wants to know if it
181
+ // took
182
+ check: data.addCertificate.check ? HostnameCheckApiResponseSchema.parse(data.addCertificate.check) : null
183
+ };
184
+ } catch (error) {
185
+ if (error instanceof FlyApiError && error.isAlreadyExists) {
186
+ const certificate = await this.certs.get(app, hostname);
187
+ if (certificate) {
188
+ return { certificate, check: null };
189
+ }
190
+ }
191
+ throw error;
192
+ }
193
+ },
194
+ /**
195
+ * Read one certificate, or `null` when the app has none for that hostname.
196
+ *
197
+ * This is the call behind a "check" button: it re-reads issuance state from
198
+ * Fly rather than trusting anything stored locally.
199
+ *
200
+ * Fly reports an absent certificate as a `NOT_FOUND` *error* rather than a
201
+ * null field, so that case is translated here — asking about a domain
202
+ * nobody has added yet is an ordinary question with an ordinary answer.
203
+ */
204
+ get: async (app, hostname) => {
205
+ let data;
206
+ try {
207
+ data = await this.request(
208
+ `query AppCertificate($appName: String!, $hostname: String!) {
209
+ app(name: $appName) {
210
+ certificate(hostname: $hostname) { ${CERTIFICATE_FIELDS} }
211
+ }
212
+ }`,
213
+ { appName: app, hostname }
214
+ );
215
+ } catch (error) {
216
+ if (error instanceof FlyApiError && error.isNotFound) {
217
+ return null;
218
+ }
219
+ throw error;
220
+ }
221
+ const certificate = data.app?.certificate;
222
+ return certificate ? CertificateApiResponseSchema.parse(certificate) : null;
223
+ },
224
+ /**
225
+ * What Fly resolves for a hostname right now, and what it objects to.
226
+ *
227
+ * A mutation on Fly's side despite reading rather than writing anything —
228
+ * `AppCertificate.check` is a plain boolean flag, and `HostnameCheck` is
229
+ * only ever returned by `addCertificate` and this, `checkCertificate`.
230
+ * Separate from `get` rather than folded into it: triggering a live dns
231
+ * resolution on every read would cost a caller that only wants issuance
232
+ * state. Pair the two when a person has just edited their records and
233
+ * wants to know whether it took.
234
+ *
235
+ * `errors` is the useful half — it is what Fly's own dashboard prints as
236
+ * "validation issues", already phrased for whoever owns the domain.
237
+ *
238
+ * @returns `null` when the app has no certificate for that hostname
239
+ */
240
+ check: async (app, hostname) => {
241
+ let data;
242
+ try {
243
+ data = await this.request(
244
+ `mutation CheckCertificate($appId: ID!, $hostname: String!) {
245
+ checkCertificate(input: { appId: $appId, hostname: $hostname }) {
246
+ check { ${HOSTNAME_CHECK_FIELDS} }
247
+ }
248
+ }`,
249
+ { appId: app, hostname }
250
+ );
251
+ } catch (error) {
252
+ if (error instanceof FlyApiError && error.isNotFound) {
253
+ return null;
254
+ }
255
+ throw error;
256
+ }
257
+ const check = data.checkCertificate?.check;
258
+ return check ? HostnameCheckApiResponseSchema.parse(check) : null;
259
+ },
260
+ /** Every certificate on an app */
261
+ list: async (app) => {
262
+ const data = await this.request(
263
+ `query AppCertificates($appName: String!) {
264
+ app(name: $appName) {
265
+ certificates { nodes { ${CERTIFICATE_FIELDS} } }
266
+ }
267
+ }`,
268
+ { appName: app }
269
+ );
270
+ return CertificateListApiResponseSchema.parse(
271
+ data.app?.certificates?.nodes ?? []
272
+ );
273
+ },
274
+ /**
275
+ * Remove a certificate.
276
+ *
277
+ * The hostname keeps resolving until its DNS is changed — this only stops
278
+ * Fly serving TLS for it.
279
+ */
280
+ remove: async (app, hostname) => {
281
+ await this.request(
282
+ `mutation DeleteCertificate($appId: ID!, $hostname: String!) {
283
+ deleteCertificate(appId: $appId, hostname: $hostname) {
284
+ certificate { hostname }
285
+ }
286
+ }`,
287
+ { appId: app, hostname }
288
+ );
289
+ }
290
+ };
291
+ /**
292
+ * Operate an app's machines.
293
+ *
294
+ * Over Fly's REST Machines API rather than GraphQL, which has no current
295
+ * equivalent — the GraphQL mutations date from the Nomad platform and no
296
+ * longer apply.
297
+ */
298
+ machines = {
299
+ /** Every machine on an app */
300
+ list: async (app) => {
301
+ const data = await this.machinesRequest(
302
+ "GET",
303
+ `/apps/${encodeURIComponent(app)}/machines`
304
+ );
305
+ return MachineListApiResponseSchema.parse(data ?? []);
306
+ },
307
+ /**
308
+ * Restart an app's machines.
309
+ *
310
+ * One at a time on purpose: a settings change that only takes effect at
311
+ * boot should not cost the app its availability to apply. Restarting them
312
+ * together would drop every machine at once, while sequentially leaves the
313
+ * others serving. The trade is that a large app takes longer.
314
+ *
315
+ * A machine that fails to restart stops the run rather than being skipped —
316
+ * a half-restarted app is running two configurations at the same time, and
317
+ * silently returning "some of them" invites calling that done.
318
+ *
319
+ * @param app - Fly app name
320
+ * @param machineId - Restart only this machine, instead of all of them
321
+ * @returns Ids of the machines that were restarted, in the order they were
322
+ */
323
+ restart: async (app, machineId) => {
324
+ const ids = machineId ? [machineId] : (await this.machines.list(app)).map((machine) => machine.id);
325
+ const restarted = [];
326
+ for (const id of ids) {
327
+ await this.machinesRequest(
328
+ "POST",
329
+ `/apps/${encodeURIComponent(app)}/machines/${encodeURIComponent(id)}/restart`
330
+ );
331
+ restarted.push(id);
332
+ }
333
+ return restarted;
334
+ }
335
+ };
336
+ /**
337
+ * The DNS records a customer must create for a certificate to validate.
338
+ *
339
+ * Pulled out of the certificate rather than fetched, so a caller that
340
+ * already has one does not pay for a second round trip.
341
+ */
342
+ static dnsInstructions(certificate) {
343
+ return {
344
+ hostname: certificate.dnsValidationHostname,
345
+ target: certificate.dnsValidationTarget,
346
+ instructions: certificate.dnsValidationInstructions,
347
+ isApex: certificate.isApex
348
+ };
349
+ }
350
+ /**
351
+ * @private
352
+ * One GraphQL round trip.
353
+ *
354
+ * Fly answers a failed query with HTTP 200 and an `errors` array, so a
355
+ * response is only successful when both are checked — trusting the status
356
+ * alone would turn "permission denied" into a parse error further down.
357
+ */
358
+ async request(query, variables) {
359
+ const operation = /(?:query|mutation)\s+(\w+)/.exec(query)?.[1] ?? "query";
360
+ this.log(`[fly-api] ${operation} ${JSON.stringify(variables)}`);
361
+ let response;
362
+ try {
363
+ response = await fetch(this.apiUrl, {
364
+ method: "POST",
365
+ headers: {
366
+ Authorization: `Bearer ${this.token}`,
367
+ "Content-Type": "application/json"
368
+ },
369
+ body: JSON.stringify({ query, variables })
370
+ });
371
+ } catch (error) {
372
+ throw new Error(`[fly-api] ${operation} could not reach Fly: ${error}`);
373
+ }
374
+ if (!response.ok) {
375
+ throw new Error(
376
+ `[fly-api] ${operation} failed: ${response.status} ${response.statusText}`
377
+ );
378
+ }
379
+ const body = await response.json();
380
+ if (body.errors?.length) {
381
+ throw new FlyApiError(
382
+ `[fly-api] ${operation} failed: ${body.errors.map((error) => error.message).join("; ")}`,
383
+ body.errors
384
+ );
385
+ }
386
+ if (!body.data) {
387
+ throw new Error(`[fly-api] ${operation} returned no data`);
388
+ }
389
+ return body.data;
390
+ }
391
+ /**
392
+ * @private
393
+ * One call to the Machines REST API.
394
+ *
395
+ * Unlike GraphQL this one reports failure through the status code, and puts
396
+ * its reason in an `error` field. Worth reading rather than reporting the
397
+ * status alone: "machine not found" and "unauthorized" are different problems
398
+ * with different fixes.
399
+ */
400
+ async machinesRequest(method, path) {
401
+ this.log(`[fly-api] ${method} ${path}`);
402
+ let response;
403
+ try {
404
+ response = await fetch(`${this.machinesUrl}${path}`, {
405
+ method,
406
+ headers: {
407
+ Authorization: `Bearer ${this.token}`,
408
+ "Content-Type": "application/json"
409
+ }
410
+ });
411
+ } catch (error) {
412
+ throw new Error(
413
+ `[fly-api] ${method} ${path} could not reach Fly: ${error}`
414
+ );
415
+ }
416
+ const body = await response.json().catch(() => null);
417
+ if (!response.ok) {
418
+ throw new Error(
419
+ `[fly-api] ${method} ${path} failed: ${response.status} ${body?.error ?? response.statusText}`
420
+ );
421
+ }
422
+ return body;
423
+ }
424
+ };
425
+ var CERTIFICATE_FIELDS = `
426
+ id
427
+ hostname
428
+ isConfigured
429
+ isApex
430
+ isWildcard
431
+ isAcmeDnsConfigured
432
+ isAcmeAlpnConfigured
433
+ isAcmeHttpConfigured
434
+ certificateAuthority
435
+ certificateRequestedAt
436
+ createdAt
437
+ domain
438
+ dnsProvider
439
+ dnsValidationHostname
440
+ dnsValidationTarget
441
+ dnsValidationInstructions
442
+ clientStatus
443
+ rateLimitedUntil
444
+ source
445
+ validationErrors {
446
+ message
447
+ timestamp
448
+ }
449
+ # Fly issues one certificate per key type (RSA and ECDSA), so a hostname
450
+ # with a single expiry date still comes back as two rows
451
+ issued(first: 10) {
452
+ nodes {
453
+ id
454
+ type
455
+ hostname
456
+ expiresAt
457
+ }
458
+ }
459
+ `;
460
+ var HOSTNAME_CHECK_FIELDS = `
461
+ aRecords
462
+ aaaaRecords
463
+ cnameRecords
464
+ caaRecords
465
+ soa
466
+ dnsProvider
467
+ dnsVerificationRecord
468
+ dnsConfigured
469
+ acmeDnsConfigured
470
+ resolvedAddresses
471
+ isProxied
472
+ errors
473
+ `;
474
+
1
475
  // packages/fly-node/src/lib/fly.class.ts
2
- import { existsSync } from "fs";
3
- import { join } from "path";
476
+ import { existsSync, mkdirSync, writeFileSync } from "fs";
477
+ import { dirname, join } from "path";
4
478
  import { cwd } from "process";
5
479
 
6
- // packages/core/src/lib/utils/docker-build.ts
480
+ // libs/shared/util/misc/src/lib/docker-build.ts
7
481
  import { dockerCommand } from "docker-cli-js";
8
482
  import invariant from "tiny-invariant";
9
483
 
10
- // packages/core/src/lib/utils/log-utils.ts
484
+ // libs/shared/util/misc/src/lib/log-utils.ts
11
485
  import chalk from "chalk";
12
486
 
13
- // packages/core/src/lib/utils/promisified-exec.ts
487
+ // libs/shared/util/misc/src/lib/promisified-exec.ts
14
488
  import { exec as cpExec, execFile as cpExecFile } from "child_process";
15
489
  import { promisify } from "util";
16
490
  var exec = promisify(cpExec);
17
491
  var execFile = promisify(cpExecFile);
18
492
 
19
- // packages/core/src/lib/utils/kill-port.ts
493
+ // libs/shared/util/misc/src/lib/kill-port.ts
20
494
  import kill from "kill-port";
21
495
  import { check as portCheck } from "tcp-port-used";
22
496
 
23
- // packages/core/src/lib/utils/kill-process-tree.ts
497
+ // libs/shared/util/misc/src/lib/kill-process-tree.ts
24
498
  import { promisify as promisify2 } from "util";
25
499
  import treeKill from "tree-kill";
26
500
  var killProcessTree = promisify2(treeKill);
27
501
 
28
- // packages/core/src/lib/utils/promisified-spawn.ts
502
+ // libs/shared/util/misc/src/lib/promisified-spawn.ts
29
503
  import {
30
504
  spawn as cpSpawn
31
505
  } from "child_process";
32
506
  function spawn(command, args, options) {
33
507
  return new Promise((resolve, reject) => {
508
+ const { streamToConsole, ...spawnOptions } = options || {};
34
509
  const process2 = cpSpawn(command, args, {
35
- ...options,
510
+ ...spawnOptions,
36
511
  stdio: "pipe"
37
512
  });
38
513
  const stdoutChunks = [];
39
514
  const stderrChunks = [];
40
515
  process2.stdout.on("data", (data) => {
41
516
  stdoutChunks.push(Buffer.from(data));
517
+ if (streamToConsole) {
518
+ global.process.stdout.write(data);
519
+ }
42
520
  });
43
521
  process2.stderr.on("data", (data) => {
44
522
  stderrChunks.push(Buffer.from(data));
523
+ if (streamToConsole) {
524
+ global.process.stderr.write(data);
525
+ }
45
526
  });
46
527
  process2.on("close", (code) => {
47
528
  const stdout = Buffer.concat(stdoutChunks).toString();
@@ -57,10 +538,7 @@ Error: ${stderr}`));
57
538
  });
58
539
  }
59
540
 
60
- // packages/core/src/lib/utils/run-command.ts
61
- import { tmpProjPath } from "@nx/plugin/testing";
62
-
63
- // packages/core/src/lib/utils/spawn-pty.ts
541
+ // libs/shared/util/misc/src/lib/spawn-pty.ts
64
542
  import { spawn as spawn2 } from "@homebridge/node-pty-prebuilt-multiarch";
65
543
  function spawnPty(command, args, options) {
66
544
  return new Promise((resolve, reject) => {
@@ -94,21 +572,24 @@ Output: ${output}`)
94
572
  });
95
573
  }
96
574
 
97
- // packages/core/src/lib/utils/whoami.ts
98
- import npmWhoami from "npm-whoami";
99
-
100
575
  // packages/fly-node/src/lib/fly.class.ts
101
576
  import { ZodError } from "zod";
102
577
 
103
- // packages/core/src/lib/zod/json.schema.ts
104
- import { z } from "zod";
105
- var LiteralSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
106
- var JsonSchema = z.lazy(
107
- () => z.union([LiteralSchema, z.array(JsonSchema), z.record(JsonSchema)])
578
+ // libs/shared/util/zod/src/lib/coerce-boolean.ts
579
+ import { z as z3 } from "zod";
580
+
581
+ // libs/shared/util/zod/src/lib/create-lowercase-schema.ts
582
+ import { z as z4 } from "zod";
583
+
584
+ // libs/shared/util/zod/src/lib/json.schema.ts
585
+ import { z as z5 } from "zod";
586
+ var LiteralSchema = z5.union([z5.string(), z5.number(), z5.boolean(), z5.null()]);
587
+ var JsonSchema = z5.lazy(
588
+ () => z5.union([LiteralSchema, z5.array(JsonSchema), z5.record(JsonSchema)])
108
589
  );
109
590
 
110
- // packages/core/src/lib/zod/with-camel-case.preprocess.ts
111
- import { z as z2 } from "zod";
591
+ // libs/shared/util/zod/src/lib/with-camel-case.preprocess.ts
592
+ import { z as z6 } from "zod";
112
593
  var toCamelCase = (str, specialCases = {}) => {
113
594
  if (specialCases[str]) {
114
595
  return specialCases[str];
@@ -134,28 +615,31 @@ var transformKeys = (options) => {
134
615
  );
135
616
  }
136
617
  if (data && typeof data === "object" && data !== null) {
137
- return Object.entries(data).reduce((acc, [key, value]) => {
138
- const shouldPreserveValue = preserve.some(
139
- (path) => [...currentPath, key].join(".").match(new RegExp(`^${path}.`))
140
- );
141
- const newKey = shouldPreserveValue ? key : toCamelCase(key, specialCases);
142
- const newPath = [...currentPath, newKey];
143
- return {
144
- ...acc,
145
- [newKey]: transformKeys({
146
- currentPath: newPath,
147
- data: value,
148
- preserve,
149
- specialCases
150
- })
151
- };
152
- }, {});
618
+ return Object.fromEntries(
619
+ Object.entries(data).map(([key, value]) => {
620
+ const fullPath = [...currentPath, key].join(".");
621
+ const shouldPreserveValue = preserve.some(
622
+ (path) => fullPath.startsWith(`${path}.`)
623
+ );
624
+ const newKey = shouldPreserveValue ? key : toCamelCase(key, specialCases);
625
+ const newPath = [...currentPath, newKey];
626
+ return [
627
+ newKey,
628
+ transformKeys({
629
+ currentPath: newPath,
630
+ data: value,
631
+ preserve,
632
+ specialCases
633
+ })
634
+ ];
635
+ })
636
+ );
153
637
  }
154
638
  return data;
155
639
  };
156
640
  var withCamelCase = (schema, options = {}) => {
157
641
  const { preserve = [], specialCases = {} } = options;
158
- return z2.preprocess(
642
+ return z6.preprocess(
159
643
  (data) => transformKeys({
160
644
  currentPath: [],
161
645
  data,
@@ -166,87 +650,93 @@ var withCamelCase = (schema, options = {}) => {
166
650
  );
167
651
  };
168
652
 
169
- // packages/core/src/lib/zod/with-replace-all.preprocess.ts
170
- import { z as z3 } from "zod";
653
+ // libs/shared/util/zod/src/lib/with-env-vars.preprocess.ts
654
+ import { z as z7 } from "zod";
655
+
656
+ // libs/shared/util/zod/src/lib/with-replace-all.preprocess.ts
657
+ import { z as z8 } from "zod";
171
658
 
172
659
  // packages/fly-node/src/lib/schemas/apps-create.schema.ts
173
- import { z as z4 } from "zod";
660
+ import { z as z9 } from "zod";
174
661
  var AppsCreateTransformedResponseSchema = withCamelCase(
175
- z4.object({
176
- id: z4.string(),
177
- name: z4.string(),
178
- organization: z4.object({
179
- id: z4.string(),
180
- name: z4.string()
181
- })
662
+ z9.object({
663
+ id: z9.string(),
664
+ name: z9.string()
182
665
  })
183
666
  );
184
667
 
185
668
  // packages/fly-node/src/lib/schemas/apps-list.schema.ts
186
- import { z as z5 } from "zod";
187
- var AppsListTransformedResponseSchema = z5.array(
669
+ import { z as z10 } from "zod";
670
+ var AppsListTransformedResponseSchema = z10.array(
188
671
  withCamelCase(
189
- z5.object({
190
- id: z5.string(),
191
- name: z5.string(),
192
- status: z5.string(),
193
- deployed: z5.boolean(),
194
- hostname: z5.string(),
195
- organization: z5.object({
196
- name: z5.string(),
197
- slug: z5.string()
672
+ z10.object({
673
+ id: z10.string(),
674
+ name: z10.string(),
675
+ status: z10.string(),
676
+ deployed: z10.boolean(),
677
+ hostname: z10.string(),
678
+ organization: z10.object({
679
+ name: z10.string(),
680
+ slug: z10.string()
198
681
  }),
199
- currentRelease: z5.nullable(
200
- z5.object({
201
- status: z5.string(),
202
- createdAt: z5.string().datetime()
682
+ currentRelease: z10.nullable(
683
+ z10.object({
684
+ status: z10.string(),
685
+ createdAt: z10.string().datetime()
203
686
  })
204
687
  )
205
688
  })
206
689
  )
207
690
  );
208
691
 
692
+ // packages/fly-node/src/lib/schemas/build-response.schema.ts
693
+ import { z as z11 } from "zod";
694
+ var BuildResponseSchema = z11.object({
695
+ appName: z11.string(),
696
+ imageRef: z11.string()
697
+ });
698
+
209
699
  // packages/fly-node/src/lib/schemas/certs-list-with-app.schema.ts
210
- import { z as z7 } from "zod";
700
+ import { z as z13 } from "zod";
211
701
 
212
702
  // packages/fly-node/src/lib/schemas/certs-list.schema.ts
213
- import { z as z6 } from "zod";
214
- var CertsListFlyResponseElementSchema = z6.object({
215
- createdAt: z6.string().datetime(),
216
- hostname: z6.string(),
217
- clientStatus: z6.string()
703
+ import { z as z12 } from "zod";
704
+ var CertsListFlyResponseElementSchema = z12.object({
705
+ createdAt: z12.string().datetime(),
706
+ hostname: z12.string(),
707
+ clientStatus: z12.string()
218
708
  });
219
- var CertsListTransformedResponseSchema = z6.array(
709
+ var CertsListTransformedResponseSchema = z12.array(
220
710
  withCamelCase(CertsListFlyResponseElementSchema)
221
711
  );
222
712
 
223
713
  // packages/fly-node/src/lib/schemas/certs-list-with-app.schema.ts
224
- var CertsListWithAppTransformedResponseSchema = z7.array(
714
+ var CertsListWithAppTransformedResponseSchema = z13.array(
225
715
  withCamelCase(
226
716
  CertsListFlyResponseElementSchema.extend({
227
- app: z7.string()
717
+ app: z13.string()
228
718
  })
229
719
  )
230
720
  );
231
721
 
232
722
  // packages/fly-node/src/lib/schemas/config-show.schema.ts
233
- import { z as z8 } from "zod";
723
+ import { z as z14 } from "zod";
234
724
  var ConfigShowResponseSchema = withCamelCase(
235
- z8.object({
236
- app: z8.string(),
237
- primaryRegion: z8.string().optional(),
238
- build: z8.record(z8.string(), z8.any()).optional().or(
239
- z8.object({
240
- args: z8.record(z8.string(), z8.string()).optional(),
241
- dockerfile: z8.string().optional(),
242
- image: z8.string().optional()
725
+ z14.object({
726
+ app: z14.string(),
727
+ primaryRegion: z14.string().optional(),
728
+ build: z14.record(z14.string(), z14.any()).optional().or(
729
+ z14.object({
730
+ args: z14.record(z14.string(), z14.string()).optional(),
731
+ dockerfile: z14.string().optional(),
732
+ image: z14.string().optional()
243
733
  })
244
734
  ),
245
- deploy: z8.record(z8.string(), z8.any()).optional().or(z8.object({ strategy: z8.string().optional() })),
246
- env: z8.record(z8.string(), z8.string()).optional(),
247
- httpService: z8.record(z8.string(), z8.any()).optional(),
248
- mounts: z8.record(z8.string(), z8.any()).optional(),
249
- services: z8.array(z8.record(z8.string(), z8.any())).optional()
735
+ deploy: z14.record(z14.string(), z14.any()).optional().or(z14.object({ strategy: z14.string().optional() })),
736
+ env: z14.record(z14.string(), z14.string()).optional(),
737
+ httpService: z14.record(z14.string(), z14.any()).optional(),
738
+ mounts: z14.record(z14.string(), z14.any()).optional(),
739
+ services: z14.array(z14.record(z14.string(), z14.any())).optional()
250
740
  }),
251
741
  {
252
742
  preserve: ["build.args", "env"]
@@ -254,120 +744,135 @@ var ConfigShowResponseSchema = withCamelCase(
254
744
  );
255
745
 
256
746
  // packages/fly-node/src/lib/schemas/deploy.schema.ts
257
- import { z as z9 } from "zod";
258
- var DeployResponseSchema = z9.object({
259
- app: z9.string(),
260
- hostname: z9.string(),
261
- url: z9.string().url()
747
+ import { z as z15 } from "zod";
748
+ var DeployResponseSchema = z15.object({
749
+ app: z15.string(),
750
+ hostname: z15.string(),
751
+ url: z15.string().url()
262
752
  });
263
753
 
264
754
  // packages/fly-node/src/lib/schemas/helper-schemas.ts
265
- import { z as z10 } from "zod";
266
- var AllowEmptyUrlSchema = z10.string().url().or(z10.literal(""));
267
- var NameSchema = z10.string({ message: "App name must be a valid slug" }).regex(/^[a-z0-9-]+$/);
755
+ import { z as z16 } from "zod";
756
+ var AllowEmptyUrlSchema = z16.string().url().or(z16.literal(""));
757
+ var NameSchema = z16.string({ message: "App name must be a valid slug" }).regex(/^[a-z0-9-]+$/);
268
758
 
269
759
  // packages/fly-node/src/lib/schemas/postgres-list.ts
270
- import { z as z11 } from "zod";
271
- var PostgresListTransformedResponseSchema = z11.array(
760
+ import { z as z17 } from "zod";
761
+ var PostgresListTransformedResponseSchema = z17.array(
272
762
  withCamelCase(
273
- z11.object({
274
- deployed: z11.boolean(),
275
- hostname: z11.string(),
276
- id: z11.string(),
277
- name: z11.string(),
278
- organization: z11.object({ id: z11.string(), slug: z11.string() }),
279
- status: z11.string(),
280
- version: z11.number()
763
+ z17.object({
764
+ deployed: z17.boolean(),
765
+ hostname: z17.string(),
766
+ id: z17.string(),
767
+ name: z17.string(),
768
+ organization: z17.object({ id: z17.string(), slug: z17.string() }),
769
+ status: z17.string(),
770
+ version: z17.number()
281
771
  })
282
772
  )
283
- );
773
+ ).or(z17.string());
284
774
 
285
775
  // packages/fly-node/src/lib/schemas/postgres-users-list.ts
286
- import { z as z12 } from "zod";
287
- var PostgresUsersListTransformedResponseSchema = z12.array(
776
+ import { z as z18 } from "zod";
777
+ var PostgresUsersListTransformedResponseSchema = z18.array(
288
778
  withCamelCase(
289
- z12.object({
290
- username: z12.string(),
291
- superuser: z12.boolean(),
292
- databases: z12.array(z12.string())
779
+ z18.object({
780
+ username: z18.string(),
781
+ superuser: z18.boolean(),
782
+ databases: z18.array(z18.string())
293
783
  })
294
784
  )
295
785
  );
296
786
 
297
787
  // packages/fly-node/src/lib/schemas/secrets-list-with-app.schema.ts
298
- import { z as z14 } from "zod";
788
+ import { z as z20 } from "zod";
299
789
 
300
790
  // packages/fly-node/src/lib/schemas/secrets-list.schema.ts
301
- import { z as z13 } from "zod";
302
- var SecretsListFlyResponseElementSchema = z13.object({
303
- name: z13.string(),
304
- digest: z13.string(),
305
- createdAt: z13.string().datetime()
791
+ import { z as z19 } from "zod";
792
+ var SecretsListFlyResponseElementSchema = z19.object({
793
+ name: z19.string(),
794
+ digest: z19.string()
306
795
  });
307
- var SecretsListTransformedResponseSchema = z13.array(
796
+ var SecretsListTransformedResponseSchema = z19.array(
308
797
  withCamelCase(SecretsListFlyResponseElementSchema)
309
798
  );
310
799
 
311
800
  // packages/fly-node/src/lib/schemas/secrets-list-with-app.schema.ts
312
- var SecretsListWithAppTransformedResponseSchema = z14.array(
801
+ var SecretsListWithAppTransformedResponseSchema = z20.array(
313
802
  withCamelCase(
314
803
  SecretsListFlyResponseElementSchema.extend({
315
- app: z14.string()
804
+ app: z20.string()
316
805
  })
317
806
  )
318
807
  );
319
808
 
320
809
  // packages/fly-node/src/lib/schemas/status-extended.schema.ts
321
- import { z as z16 } from "zod";
810
+ import { z as z22 } from "zod";
322
811
 
323
812
  // packages/fly-node/src/lib/schemas/status.schema.ts
324
- import { z as z15 } from "zod";
325
- var statusFlyResponseSchema = z15.object({
326
- deployed: z15.boolean(),
327
- hostname: z15.string(),
328
- id: z15.string(),
329
- machines: z15.array(
330
- z15.object({
331
- id: z15.string(),
332
- name: z15.string(),
333
- state: z15.string(),
334
- region: z15.string(),
335
- createdAt: z15.string().datetime(),
336
- updatedAt: z15.string().datetime(),
337
- config: z15.object({
338
- env: z15.record(z15.string()),
339
- metadata: z15.record(z15.string())
813
+ import { z as z21 } from "zod";
814
+ var statusFlyResponseSchema = z21.object({
815
+ deployed: z21.boolean(),
816
+ hostname: z21.string(),
817
+ id: z21.string(),
818
+ machines: z21.array(
819
+ z21.object({
820
+ id: z21.string(),
821
+ name: z21.string(),
822
+ state: z21.string(),
823
+ region: z21.string(),
824
+ imageRef: z21.object({
825
+ registry: z21.string(),
826
+ repository: z21.string(),
827
+ tag: z21.string(),
828
+ digest: z21.string(),
829
+ labels: z21.record(z21.string()).optional()
340
830
  }),
341
- events: z15.array(
342
- z15.object({
343
- type: z15.string(),
344
- status: z15.string(),
345
- timestamp: z15.number()
831
+ createdAt: z21.string().datetime(),
832
+ updatedAt: z21.string().datetime(),
833
+ config: z21.object({
834
+ env: z21.record(z21.string()),
835
+ metadata: z21.record(z21.string()),
836
+ guest: z21.object({
837
+ cpu_kind: z21.string().optional(),
838
+ cpus: z21.number().optional(),
839
+ memory_mb: z21.number().optional()
840
+ }).optional()
841
+ }),
842
+ events: z21.array(
843
+ z21.object({
844
+ type: z21.string(),
845
+ status: z21.string(),
846
+ timestamp: z21.number()
346
847
  })
347
848
  ),
348
- checks: z15.array(
349
- z15.object({
350
- name: z15.string(),
351
- status: z15.string(),
352
- output: z15.string(),
353
- updatedAt: z15.string().datetime()
849
+ checks: z21.array(
850
+ z21.object({
851
+ name: z21.string(),
852
+ status: z21.string(),
853
+ output: z21.string(),
854
+ updatedAt: z21.string().datetime()
354
855
  })
355
856
  ).optional(),
356
- hostStatus: z15.string()
857
+ hostStatus: z21.string()
357
858
  })
358
859
  ),
359
- name: z15.string(),
360
- organization: z15.object({
361
- id: z15.string(),
362
- slug: z15.string()
860
+ name: z21.string(),
861
+ organization: z21.object({
862
+ id: z21.string(),
863
+ slug: z21.string()
363
864
  }),
364
- status: z15.string(),
365
- version: z15.number()
865
+ status: z21.string(),
866
+ version: z21.number()
366
867
  });
367
868
  var StatusTransformedResponseSchema = withCamelCase(
368
869
  statusFlyResponseSchema,
369
870
  {
370
- preserve: ["machines.config.env", "machines.config.metadata"],
871
+ preserve: [
872
+ "machines.config.env",
873
+ "machines.config.metadata",
874
+ "machines.config.guest"
875
+ ],
371
876
  specialCases: { AppURL: "appUrl" }
372
877
  }
373
878
  );
@@ -375,23 +880,37 @@ var StatusTransformedResponseSchema = withCamelCase(
375
880
  // packages/fly-node/src/lib/schemas/status-extended.schema.ts
376
881
  var StatusExtendedTransformedResponseSchema = withCamelCase(
377
882
  statusFlyResponseSchema.extend({
378
- domains: z16.array(z16.object({ hostname: z16.string() })),
379
- secrets: z16.array(z16.object({ name: z16.string() }))
883
+ domains: z22.array(z22.object({ hostname: z22.string() })),
884
+ secrets: z22.array(z22.object({ name: z22.string() }))
380
885
  }),
381
886
  {
382
- preserve: ["machines.config.env", "machines.config.metadata"]
887
+ preserve: [
888
+ "machines.config.env",
889
+ "machines.config.metadata",
890
+ "machines.config.guest"
891
+ ]
383
892
  }
384
893
  );
385
894
 
895
+ // packages/fly-node/src/lib/schemas/version.schema.ts
896
+ import { z as z23 } from "zod";
897
+ var VersionTransformedResponseSchema = withCamelCase(
898
+ z23.object({
899
+ name: z23.string(),
900
+ version: z23.string(),
901
+ commit: z23.string(),
902
+ branchName: z23.string(),
903
+ buildDate: z23.string().datetime(),
904
+ os: z23.string(),
905
+ architecture: z23.string(),
906
+ environment: z23.string()
907
+ })
908
+ );
909
+
386
910
  // packages/fly-node/src/lib/fly.class.ts
387
911
  var Fly = class {
388
912
  /** Use underscore to avoid conflict with public `config` property */
389
913
  _config;
390
- /**
391
- * Whether a user is authenticated via local login.
392
- * In this case a token is not needed, though it can still have been provided.
393
- */
394
- authByLogin = false;
395
914
  initialized = false;
396
915
  logger;
397
916
  /**
@@ -417,10 +936,14 @@ var Fly = class {
417
936
  this.logger = {
418
937
  info: config?.logger?.info || console.log,
419
938
  error: config?.logger?.error || console.error,
420
- traceCLI: config?.logger?.traceCLI || false
939
+ traceCLI: config?.logger?.traceCLI ?? false,
940
+ redactSecrets: config?.logger?.redactSecrets ?? true,
941
+ verbose: config?.logger?.verbose ?? false,
942
+ debug: config?.logger?.debug ?? false,
943
+ streamToConsole: config?.logger?.streamToConsole ?? false
421
944
  };
422
- if (!this._config.token) {
423
- this._config.token = process.env["FLY_API_TOKEN"] || "";
945
+ if (this._config.token) {
946
+ process.env["FLY_ACCESS_TOKEN"] = this._config.token;
424
947
  }
425
948
  }
426
949
  /**
@@ -456,7 +979,21 @@ ${error}`);
456
979
  *
457
980
  * @returns `true` if the Fly CLI tool is installed, `false` otherwise
458
981
  */
459
- isInstalled: async () => await this.isInstalled()
982
+ isInstalled: async () => await this.isInstalled(),
983
+ /**
984
+ * Get version information about the installed Fly CLI
985
+ *
986
+ * @returns The installed Fly CLI version information
987
+ * @throws An error if the version cannot be retrieved
988
+ */
989
+ version: async () => {
990
+ try {
991
+ return await this.version();
992
+ } catch (error) {
993
+ throw new Error(`[version] something broke
994
+ ${error}`);
995
+ }
996
+ }
460
997
  };
461
998
  //
462
999
  // External API following the `flyctl` CLI commands structure
@@ -475,9 +1012,9 @@ ${error}`);
475
1012
  create: async (options) => {
476
1013
  try {
477
1014
  await this.ensureInitialized();
478
- const { name } = await this.createApp(options);
479
- this.logger.info(`Application '${name}' was created`);
480
- return name;
1015
+ const response = await this.createApp(options);
1016
+ this.logger.info(`Application '${response.name}' was created`);
1017
+ return response;
481
1018
  } catch (error) {
482
1019
  throw new Error(
483
1020
  `[create app] something broke, check your apps
@@ -489,10 +1026,9 @@ ${error}`
489
1026
  * Destroy an application and make sure it gets detached from any Postgres clusters
490
1027
  *
491
1028
  * @param app - The name of the app to destroy
492
- * @param options - Options for destroying an application
493
1029
  * @throws An error if the app cannot be destroyed
494
1030
  */
495
- destroy: async (app, options) => {
1031
+ destroy: async (app) => {
496
1032
  try {
497
1033
  await this.ensureInitialized();
498
1034
  const attachedClusters = await this.getAttachedPostgresClusters(app);
@@ -503,7 +1039,7 @@ ${error}`
503
1039
  const output = await this.detachPostgres(cluster, app);
504
1040
  this.logger.info(output);
505
1041
  }
506
- await this.destroyApp(app, options?.force);
1042
+ await this.destroyApp(app);
507
1043
  this.logger.info(`Application '${app}' was destroyed`);
508
1044
  } catch (error) {
509
1045
  throw new Error(
@@ -595,6 +1131,27 @@ ${error}`
595
1131
  * Manage an app's configuration
596
1132
  */
597
1133
  config = {
1134
+ /**
1135
+ * Save an application's remote configuration locally.
1136
+ *
1137
+ * TOML by default; name the path `.json` or `.yaml`/`.yml` for either of
1138
+ * those instead.
1139
+ *
1140
+ * @param options - Options for saving an application's configuration
1141
+ * @throws An error if the configuration cannot be saved
1142
+ */
1143
+ save: async (options) => {
1144
+ try {
1145
+ await this.ensureInitialized();
1146
+ await this.saveConfig(options);
1147
+ this.logger.info(
1148
+ `Configuration for '${options.app}' was saved to '${options.config}'`
1149
+ );
1150
+ } catch (error) {
1151
+ throw new Error(`[save config] something broke
1152
+ ${error}`);
1153
+ }
1154
+ },
598
1155
  /**
599
1156
  * Show an application's configuration.
600
1157
  *
@@ -613,7 +1170,12 @@ ${error}`);
613
1170
  }
614
1171
  };
615
1172
  /**
616
- * Deploy an application.
1173
+ * Deploy an application, or just build its Docker image without deploying when
1174
+ * `buildOnly` is set (equivalent to using `build(options)`).
1175
+ *
1176
+ * Pre-building is useful to ensure the image can be built successfully and exists
1177
+ * before running a deploy that depends on it, and also to get the image reference for use in
1178
+ * subsequent operations.
617
1179
  *
618
1180
  * A valid config file is required but the app doesn't have to exist,
619
1181
  * since it gets created if needed.
@@ -623,15 +1185,28 @@ ${error}`);
623
1185
  * 2. Instance app name
624
1186
  * 3. App name from the provided config file
625
1187
  *
626
- * Existing secrets are preserved.
627
- *
628
- * @param options - Options for deploying an application
629
- * @throws An error if the deployment fails
1188
+ * @param options - Deployment or build options
1189
+ * @returns Build or deploy response depending on `buildOnly` option
1190
+ * @throws An error if the operation fails
630
1191
  */
631
1192
  deploy = async (options) => {
1193
+ const isBuildOnly = options?.buildOnly === true;
632
1194
  try {
633
1195
  await this.ensureInitialized();
634
- const appName = await this.deployApp(options);
1196
+ if (isBuildOnly) {
1197
+ const { appName: appName2, imageRef } = await this.deployApp({
1198
+ ...options,
1199
+ buildOnly: true
1200
+ });
1201
+ if (!imageRef) {
1202
+ throw new Error(
1203
+ "Build completed but image reference not found in output"
1204
+ );
1205
+ }
1206
+ this.logger.info(`Image for '${appName2}' built: ${imageRef}`);
1207
+ return BuildResponseSchema.parse({ appName: appName2, imageRef });
1208
+ }
1209
+ const { appName } = await this.deployApp(options);
635
1210
  this.logger.info(`Application '${appName}' was deployed`);
636
1211
  const status = await this.fetchAppStatus("throwOnError", {
637
1212
  app: appName
@@ -643,16 +1218,124 @@ ${error}`);
643
1218
  });
644
1219
  } catch (error) {
645
1220
  throw new Error(
646
- `[deploy] something broke, check your deployments
1221
+ `[deploy] something broke, check your ${isBuildOnly ? "builds" : "deployments"}
647
1222
  ${error}`
648
1223
  );
649
1224
  }
650
1225
  };
1226
+ /**
1227
+ * Manage machines
1228
+ */
1229
+ machines = {
1230
+ /**
1231
+ * Start a machine
1232
+ *
1233
+ * @param app - The name of the application
1234
+ * @param machineId - The machine ID to start
1235
+ * @throws An error if the machine cannot be started
1236
+ */
1237
+ start: async (app, machineId) => {
1238
+ try {
1239
+ await this.ensureInitialized();
1240
+ await this.startMachine(app, machineId);
1241
+ this.logger.info(`Machine '${machineId}' in app '${app}' was started`);
1242
+ } catch (error) {
1243
+ throw new Error(`[start machine] something broke
1244
+ ${error}`);
1245
+ }
1246
+ },
1247
+ /**
1248
+ * Stop a machine
1249
+ *
1250
+ * @param app - The name of the application
1251
+ * @param machineId - The machine ID to stop
1252
+ * @throws An error if the machine cannot be stopped
1253
+ */
1254
+ stop: async (app, machineId) => {
1255
+ try {
1256
+ await this.ensureInitialized();
1257
+ await this.stopMachine(app, machineId);
1258
+ this.logger.info(`Machine '${machineId}' in app '${app}' was stopped`);
1259
+ } catch (error) {
1260
+ throw new Error(`[stop machine] something broke
1261
+ ${error}`);
1262
+ }
1263
+ },
1264
+ /**
1265
+ * Restart a machine by stopping then starting it
1266
+ *
1267
+ * @param app - The name of the application
1268
+ * @param machineId - The machine ID to restart
1269
+ * @throws An error if the machine cannot be restarted
1270
+ */
1271
+ restart: async (app, machineId) => {
1272
+ try {
1273
+ await this.ensureInitialized();
1274
+ await this.restartMachine(app, machineId);
1275
+ this.logger.info(
1276
+ `Machine '${machineId}' in app '${app}' was restarted`
1277
+ );
1278
+ } catch (error) {
1279
+ throw new Error(`[restart machine] something broke
1280
+ ${error}`);
1281
+ }
1282
+ },
1283
+ /**
1284
+ * Update a machine's per-machine configuration (env vars, etc.).
1285
+ *
1286
+ * Unlike `restart`, this creates a new machine version from the updated config
1287
+ * and forces a cold start — it does NOT resume from a suspended memory snapshot.
1288
+ *
1289
+ * @param app - The name of the application
1290
+ * @param machineId - The machine ID to update
1291
+ * @param options - Fields to update; env values set to `''` clear that var
1292
+ * @throws An error if the machine cannot be updated
1293
+ */
1294
+ update: async (app, machineId, options) => {
1295
+ try {
1296
+ await this.ensureInitialized();
1297
+ await this.updateMachine(app, machineId, options);
1298
+ this.logger.info(`Machine '${machineId}' in app '${app}' was updated`);
1299
+ } catch (error) {
1300
+ throw new Error(`[update machine] something broke
1301
+ ${error}`);
1302
+ }
1303
+ }
1304
+ };
651
1305
  postgres = {
652
1306
  detach: async (cluster, app) => {
653
1307
  await this.detachPostgres(cluster, app);
654
1308
  }
655
1309
  };
1310
+ /**
1311
+ * Run commands inside a running machine
1312
+ */
1313
+ ssh = {
1314
+ /**
1315
+ * Execute a command in a running machine and return its output.
1316
+ *
1317
+ * Requires a started machine - Fly cannot connect to a stopped or
1318
+ * suspended one. Use `machines.start` first when the app may be idle.
1319
+ *
1320
+ * The output is returned to the caller and not logged unless CLI tracing
1321
+ * is enabled, so it can be used to read values that are otherwise
1322
+ * write-only, such as secrets injected at deploy time.
1323
+ *
1324
+ * @param app - The name of the application
1325
+ * @param command - The command to run inside the machine
1326
+ * @returns The command output
1327
+ * @throws An error if there is no started machine or the command fails
1328
+ */
1329
+ exec: async (app, command) => {
1330
+ try {
1331
+ await this.ensureInitialized();
1332
+ return await this.sshExec(app, command);
1333
+ } catch (error) {
1334
+ throw new Error(`[ssh exec] something broke
1335
+ ${error}`);
1336
+ }
1337
+ }
1338
+ };
656
1339
  /**
657
1340
  * Manage application secrets
658
1341
  */
@@ -680,7 +1363,29 @@ ${error}`
680
1363
  }
681
1364
  },
682
1365
  /**
683
- * List secrets for an application
1366
+ * Apply secrets that were staged with `set({ stage: true })`.
1367
+ *
1368
+ * Staging first and deploying afterwards lets a set of apps take a new
1369
+ * value together, instead of each restarting as its own secret is written.
1370
+ *
1371
+ * Fly needs a started machine to update, so an app whose machines are all
1372
+ * stopped or suspended has to be started before this will do anything.
1373
+ *
1374
+ * @param app - The name of the application
1375
+ * @throws An error if the staged secrets cannot be deployed
1376
+ */
1377
+ deploy: async (app) => {
1378
+ try {
1379
+ await this.ensureInitialized();
1380
+ await this.deployStagedSecrets(app);
1381
+ this.logger.info(`Staged secrets were deployed for '${app}'`);
1382
+ } catch (error) {
1383
+ throw new Error(`[deploy secrets] something broke
1384
+ ${error}`);
1385
+ }
1386
+ },
1387
+ /**
1388
+ * List secrets for an application or all secrets when options is 'all'
684
1389
  *
685
1390
  * @param options - List secrets for an application or all secrets
686
1391
  * @returns A list of secrets
@@ -739,6 +1444,22 @@ ${error}`);
739
1444
  return null;
740
1445
  }
741
1446
  };
1447
+ //
1448
+ // DX friendly methods outside what Fly CLI provides
1449
+ //
1450
+ /**
1451
+ * Build a Docker image for an application and push it to the Fly registry
1452
+ * without deploying.
1453
+ *
1454
+ * The image reference is returned for use in a subsequent `deploy` that depends on it.
1455
+ *
1456
+ * Shorthand for `deploy({ ...options, buildOnly: true })`.
1457
+ *
1458
+ * @param options - Build options
1459
+ * @returns The app name and image reference for use in a subsequent `deploy`
1460
+ * @throws An error if the build fails or the image reference cannot be parsed
1461
+ */
1462
+ build = (options) => this.deploy({ ...options, buildOnly: true });
742
1463
  /**
743
1464
  * Get the extended details of an application
744
1465
  *
@@ -785,14 +1506,15 @@ ${error}`);
785
1506
  }
786
1507
  /**
787
1508
  * @private
788
- * @returns The name of the deployed application
1509
+ * @returns The app name and optional image reference (only set when buildOnly is true)
789
1510
  * @throws An error if the deployment fails
790
1511
  */
791
1512
  async deployApp(options) {
792
1513
  let appName = "";
793
1514
  let appSecrets = [];
1515
+ let deployConfig = options?.config || this.instanceConfig;
794
1516
  let lookupApp = options?.app || this.instanceApp;
795
- const lookupConfig = options?.config || this.instanceConfig;
1517
+ const lookupConfig = deployConfig;
796
1518
  if (!lookupConfig) {
797
1519
  throw new Error(
798
1520
  "Fly config file must be provided to options or class instance, unable to deploy"
@@ -825,6 +1547,26 @@ ${error}`);
825
1547
  );
826
1548
  }
827
1549
  }
1550
+ if (options?.preferRemoteConfig && appName) {
1551
+ const remoteConfigPath = join(
1552
+ dirname(lookupConfig),
1553
+ `fly.${appName}.toml`
1554
+ );
1555
+ try {
1556
+ await this.saveConfig({
1557
+ app: appName,
1558
+ config: remoteConfigPath
1559
+ });
1560
+ deployConfig = remoteConfigPath;
1561
+ this.logger.info(
1562
+ `Using remote config for existing app '${appName}' (saved to ${remoteConfigPath})`
1563
+ );
1564
+ } catch (error) {
1565
+ this.logger.info(
1566
+ `Failed to save remote config, will use local config: ${error}`
1567
+ );
1568
+ }
1569
+ }
828
1570
  if (!appName) {
829
1571
  this.logger.info("Creating a new application...");
830
1572
  const { name } = await this.createApp({
@@ -838,7 +1580,7 @@ ${error}`);
838
1580
  this.logger.info(`Updating existing application '${appName}'`);
839
1581
  }
840
1582
  NameSchema.parse(appName);
841
- if (options?.secrets) {
1583
+ if (!options?.buildOnly && options?.secrets) {
842
1584
  const existingSecrets = new Set(appSecrets.map(({ name }) => name));
843
1585
  const newSecrets = {};
844
1586
  for (const [key, value] of Object.entries(options.secrets)) {
@@ -865,7 +1607,7 @@ ${error}`);
865
1607
  );
866
1608
  appName = options.app;
867
1609
  }
868
- if (options?.postgres) {
1610
+ if (!options?.buildOnly && options?.postgres) {
869
1611
  const users = await this.fetchPostgresUsers(
870
1612
  options.postgres,
871
1613
  "nullOnError"
@@ -880,12 +1622,16 @@ ${error}`);
880
1622
  );
881
1623
  } else {
882
1624
  this.logger.info(
883
- `Attach Postgres cluster '${options.postgres}' to '${appName}'`
1625
+ `Attach Postgres cluster '${options.postgres}' to '${appName}'${options.databaseName ? ` with database '${options.databaseName}'` : ""}`
1626
+ );
1627
+ await this.attachPostgres(
1628
+ options.postgres,
1629
+ appName,
1630
+ options.databaseName
884
1631
  );
885
- await this.attachPostgres(options.postgres, appName);
886
1632
  }
887
1633
  }
888
- const args = ["deploy", "--app", appName, "--config", lookupConfig];
1634
+ const args = ["deploy", "--app", appName, "--config", deployConfig];
889
1635
  if (options?.region) {
890
1636
  args.push("--region", options.region);
891
1637
  }
@@ -895,30 +1641,47 @@ ${error}`);
895
1641
  for (const [key, value] of Object.entries(options?.env || {})) {
896
1642
  args.push("--env", `${key}=${this.safeArg(value)}`);
897
1643
  }
1644
+ for (const [key, value] of Object.entries(options?.buildArgs || {})) {
1645
+ args.push("--build-arg", `${key}=${this.safeArg(value)}`);
1646
+ }
1647
+ if (options?.image) {
1648
+ args.push("--image", options.image);
1649
+ }
1650
+ if (options?.buildOnly) {
1651
+ args.push("--build-only", "--push");
1652
+ }
898
1653
  if (options?.optOutDepotBuilder) {
899
1654
  args.push("--depot=false");
900
1655
  }
901
1656
  args.push("--yes");
902
- this.logger.info(`Deploying '${appName}'...`);
903
- await this.execFly(args);
904
- return appName;
1657
+ this.logger.info(
1658
+ options?.buildOnly ? `Building image for '${appName}'...` : `Deploying '${appName}'...`
1659
+ );
1660
+ const output = await this.execFly(
1661
+ args,
1662
+ options?.buildOnly ? { streamStrategy: "combined" } : void 0
1663
+ );
1664
+ const imageRef = options?.buildOnly ? output?.match(/registry\.fly\.io\/\S+/)?.[0] : void 0;
1665
+ return { appName, imageRef };
905
1666
  }
906
1667
  /**
907
1668
  * @private
908
1669
  * @throws An error if the Postgres database cannot be attached
909
1670
  */
910
- async attachPostgres(postgres, app) {
911
- const args = ["postgres", "attach", postgres, "--app", app, "--yes"];
1671
+ async attachPostgres(postgres, app, databaseName) {
1672
+ const args = ["postgres", "attach", postgres, "--app", app];
1673
+ if (databaseName) {
1674
+ args.push("--database-name", databaseName);
1675
+ }
1676
+ args.push("--yes");
912
1677
  await this.execFly(args);
913
1678
  }
914
1679
  /**
915
1680
  * @private
916
1681
  * @throws An error if the app cannot be destroyed
917
1682
  */
918
- async destroyApp(app, force) {
1683
+ async destroyApp(app) {
919
1684
  const args = ["apps", "destroy", app, "--yes"];
920
- if (force)
921
- args.push("--force");
922
1685
  await this.execFly(args);
923
1686
  }
924
1687
  /**
@@ -997,6 +1760,68 @@ ${error}`);
997
1760
  await this.execFly(args);
998
1761
  return NameSchema.parse(status.name);
999
1762
  }
1763
+ /**
1764
+ * @private
1765
+ * Deploy secrets previously staged for an application
1766
+ * @throws An error if the staged secrets cannot be deployed
1767
+ */
1768
+ async deployStagedSecrets(app) {
1769
+ const args = ["secrets", "deploy", "--app", app];
1770
+ await this.execFly(args);
1771
+ }
1772
+ /**
1773
+ * @private
1774
+ * Execute a command inside a running machine
1775
+ * @returns The command output
1776
+ * @throws An error if the command fails
1777
+ */
1778
+ async sshExec(app, command) {
1779
+ const args = ["ssh", "console", "--app", app, "--command", command];
1780
+ return await this.execFly(args);
1781
+ }
1782
+ /**
1783
+ * @private
1784
+ * Start a machine
1785
+ * @throws An error if the machine cannot be started
1786
+ */
1787
+ async startMachine(app, machineId) {
1788
+ const args = ["machine", "start", machineId, "--app", app];
1789
+ await this.execFly(args);
1790
+ }
1791
+ /**
1792
+ * @private
1793
+ * Stop a machine
1794
+ * @throws An error if the machine cannot be stopped
1795
+ */
1796
+ async stopMachine(app, machineId) {
1797
+ const args = ["machine", "stop", machineId, "--app", app];
1798
+ await this.execFly(args);
1799
+ }
1800
+ /**
1801
+ * @private
1802
+ * Restart a machine by stopping then starting it
1803
+ * @throws An error if the machine cannot be restarted
1804
+ */
1805
+ async restartMachine(app, machineId) {
1806
+ await this.stopMachine(app, machineId);
1807
+ await new Promise((resolve) => setTimeout(resolve, 2e3));
1808
+ await this.startMachine(app, machineId);
1809
+ }
1810
+ /**
1811
+ * @private
1812
+ * Update a machine's per-machine config (env vars, etc.).
1813
+ * Creates a new machine version so the machine cold-starts from the updated config,
1814
+ * bypassing any suspended memory snapshot.
1815
+ * @throws An error if the machine cannot be updated
1816
+ */
1817
+ async updateMachine(app, machineId, options) {
1818
+ const args = ["machine", "update", machineId, "--app", app];
1819
+ for (const [key, value] of Object.entries(options.env || {})) {
1820
+ args.push("--env", `${key}=${this.safeArg(value)}`);
1821
+ }
1822
+ args.push("--yes");
1823
+ await this.execFly(args);
1824
+ }
1000
1825
  async fetchAllApps(onError) {
1001
1826
  const args = ["apps", "list", "--json"];
1002
1827
  try {
@@ -1032,7 +1857,11 @@ ${error}`);
1032
1857
  const args = ["postgres", "list", "--json"];
1033
1858
  try {
1034
1859
  const response = await this.execFly(args);
1035
- return PostgresListTransformedResponseSchema.parse(response);
1860
+ const parsed = PostgresListTransformedResponseSchema.safeParse(response);
1861
+ if (parsed.success) {
1862
+ return Array.isArray(parsed.data) ? parsed.data : [];
1863
+ }
1864
+ throw parsed.error;
1036
1865
  } catch (error) {
1037
1866
  if (onError === "throwOnError") {
1038
1867
  throw error;
@@ -1143,11 +1972,44 @@ ${JSON.stringify(response, null, 2)}`);
1143
1972
  return null;
1144
1973
  }
1145
1974
  }
1975
+ /**
1976
+ * @private
1977
+ * Save remote config to a local file
1978
+ *
1979
+ * Two things flyctl expects that a first-time caller would not: the output
1980
+ * format is no longer sniffed from the path's extension — `--json`/`--yaml`
1981
+ * has to be passed, TOML being what is left over when neither is — and the
1982
+ * destination must already exist as a parseable file of that format, or
1983
+ * `flyctl` refuses to write to it at all, mistaking "does not exist yet"
1984
+ * for "path is wrong". A fresh, empty seed of the right shape satisfies
1985
+ * that read without affecting what gets written back over it.
1986
+ *
1987
+ * @throws An error if the config cannot be saved
1988
+ */
1989
+ async saveConfig(options) {
1990
+ const isJson = options.config.endsWith(".json");
1991
+ const isYaml = /\.ya?ml$/.test(options.config);
1992
+ if (!existsSync(options.config)) {
1993
+ mkdirSync(dirname(options.config), { recursive: true });
1994
+ writeFileSync(options.config, isJson ? "{}" : "");
1995
+ }
1996
+ const args = [
1997
+ "config",
1998
+ "save",
1999
+ "--app",
2000
+ options.app,
2001
+ "--config",
2002
+ options.config,
2003
+ ...isJson ? ["--json"] : isYaml ? ["--yaml"] : [],
2004
+ "--yes"
2005
+ ];
2006
+ await this.execFly(args);
2007
+ }
1146
2008
  /**
1147
2009
  * @private
1148
2010
  * Ensure Fly CLI is installed and authenticated
1149
2011
  *
1150
- * @throws An error if Fly CLI is not installed or authentication fails
2012
+ * @throws An error if Fly CLI is not installed or not authenticated
1151
2013
  */
1152
2014
  async ensureInitialized() {
1153
2015
  if (this.initialized)
@@ -1156,31 +2018,23 @@ ${JSON.stringify(response, null, 2)}`);
1156
2018
  if (!await this.isInstalled()) {
1157
2019
  throw new Error("Fly CLI must be installed to use this library");
1158
2020
  }
1159
- this.logger.info("Authenticating with Fly.io...");
1160
- let user = await this.execFly(
1161
- ["auth", "whoami"],
1162
- void 0,
1163
- "nullOnError",
1164
- true
1165
- // won't use token
1166
- );
1167
- if (user) {
1168
- this.logger.info(`Detected logged in user '${user}'`);
1169
- this.authByLogin = true;
1170
- } else {
1171
- user = await this.execFly(["auth", "whoami"]);
1172
- this.logger.info(`Authenticated by token as '${user}'`);
1173
- }
2021
+ const { version } = await this.version();
2022
+ this.logger.info(`Fly CLI ${version} is installed`);
2023
+ const user = await this.execFly(["auth", "whoami"]);
2024
+ this.logger.info(`Authenticated as '${user}'`);
1174
2025
  this.initialized = true;
1175
2026
  } catch (error) {
1176
2027
  this.logger.error("Failed to initialize Fly");
1177
2028
  throw error;
1178
2029
  }
1179
2030
  }
1180
- async execFly(command, options, onError = "throwOnError", skipToken) {
2031
+ async execFly(command, options, onError = "throwOnError") {
1181
2032
  const args = Array.isArray(command) ? command : command.split(" ");
1182
- if (!skipToken && !this.authByLogin && this._config.token) {
1183
- args.push("--access-token", this._config.token);
2033
+ if (this.logger.verbose) {
2034
+ args.push("--verbose");
2035
+ }
2036
+ if (this.logger.debug) {
2037
+ args.push("--debug");
1184
2038
  }
1185
2039
  const flyCmd = "flyctl";
1186
2040
  const toLogCmd = `${flyCmd} ${args.join(" ")}`;
@@ -1191,11 +2045,17 @@ ${JSON.stringify(response, null, 2)}`);
1191
2045
  output = await spawnPty(flyCmd, args, { prompt: options.prompt });
1192
2046
  this.traceCLI("RESULT", output);
1193
2047
  } else {
1194
- const result = await spawn(flyCmd, args, options);
1195
- output = result.stdout.trim();
2048
+ const { streamStrategy = "stdout", ...spawnOpts } = options ?? {};
2049
+ const result = await spawn(flyCmd, args, {
2050
+ ...spawnOpts,
2051
+ streamToConsole: this.logger.streamToConsole
2052
+ });
2053
+ const stdout = result.stdout.trim();
1196
2054
  const stderr = result.stderr.trim();
1197
- this.traceCLI("RESULT", `${output}${stderr ? `
2055
+ this.traceCLI("RESULT", `${stdout}${stderr ? `
1198
2056
  ${stderr}` : ""}`);
2057
+ output = streamStrategy === "combined" ? `${stdout}
2058
+ ${stderr}` : streamStrategy === "stderr" ? stderr : stdout;
1199
2059
  }
1200
2060
  } catch (error) {
1201
2061
  const errorMsg = error.message;
@@ -1285,6 +2145,18 @@ ${errorMsg}`);
1285
2145
  async isInstalled() {
1286
2146
  return await this.execFly("version", void 0, "nullOnError") !== null;
1287
2147
  }
2148
+ /**
2149
+ * @private
2150
+ * Get the installed Fly CLI version
2151
+ *
2152
+ * @returns The installed Fly CLI version information
2153
+ * @throws An error if the version cannot be retrieved
2154
+ */
2155
+ async version() {
2156
+ return VersionTransformedResponseSchema.parse(
2157
+ await this.execFly(["version", "--json"])
2158
+ );
2159
+ }
1288
2160
  /**
1289
2161
  * @private
1290
2162
  * Normalize the options matching `AppOrConfig` type.
@@ -1311,20 +2183,55 @@ ${errorMsg}`);
1311
2183
  safeArg(arg) {
1312
2184
  return arg.replace(/\\/g, "\\\\").replace(/ /g, "\\ ");
1313
2185
  }
2186
+ /**
2187
+ * @private
2188
+ * Redact sensitive values from text.
2189
+ *
2190
+ * Identifies and redacts:
2191
+ * - Secret values provided with `secrets set KEY1=VALUE1 KEY2=VALUE2 ...`
2192
+ *
2193
+ * @param text - The text to redact
2194
+ * @returns The redacted text
2195
+ */
2196
+ redactSensitiveData(text) {
2197
+ const maskValue = (value) => value.length > 10 ? `${value.slice(0, 3)}[REDACTED]${value.slice(-3)}` : "[REDACTED]";
2198
+ const valuePattern = "((?:\\\\ |\\S)+)";
2199
+ return text.replace(
2200
+ new RegExp(
2201
+ `(secrets\\s+set\\s+.*?)([A-Z_][A-Z0-9_]*)=${valuePattern}`,
2202
+ "g"
2203
+ ),
2204
+ (_, prefix, key, value) => `${prefix}${key}=${maskValue(value)}`
2205
+ );
2206
+ }
1314
2207
  /**
1315
2208
  * @private
1316
2209
  * Trace the CLI calls, mocks and results
1317
2210
  *
2211
+ * Redacts sensitive data from CALL messages when enabled in logger config.
2212
+ *
1318
2213
  * @param type - The type of trace
1319
2214
  * @param msg - The message to trace
1320
2215
  */
1321
2216
  traceCLI(type, msg) {
1322
2217
  if (this.logger.traceCLI) {
1323
2218
  const typeLabel = type === "CALL" ? " CALL " : type === "MOCK" ? " MOCK " : "RESULT";
1324
- this.logger.info(`[${typeLabel}] ${msg}`);
2219
+ let message = msg;
2220
+ if (type === "CALL" && this.logger.redactSecrets && msg) {
2221
+ message = this.redactSensitiveData(msg);
2222
+ }
2223
+ this.logger.info(`[${typeLabel}] ${message}`);
1325
2224
  }
1326
2225
  }
1327
2226
  };
1328
2227
  export {
1329
- Fly
2228
+ CertificateApiResponseSchema,
2229
+ CertificateListApiResponseSchema,
2230
+ DnsInstructionsSchema,
2231
+ Fly,
2232
+ FlyApi,
2233
+ FlyApiError,
2234
+ HostnameCheckApiResponseSchema,
2235
+ MachineApiResponseSchema,
2236
+ MachineListApiResponseSchema
1330
2237
  };