@cdwr/fly-node 0.3.0 → 0.3.2

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";
476
+ import { existsSync, mkdirSync, writeFileSync } from "fs";
3
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,83 +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()
662
+ z9.object({
663
+ id: z9.string(),
664
+ name: z9.string()
178
665
  })
179
666
  );
180
667
 
181
668
  // packages/fly-node/src/lib/schemas/apps-list.schema.ts
182
- import { z as z5 } from "zod";
183
- var AppsListTransformedResponseSchema = z5.array(
669
+ import { z as z10 } from "zod";
670
+ var AppsListTransformedResponseSchema = z10.array(
184
671
  withCamelCase(
185
- z5.object({
186
- id: z5.string(),
187
- name: z5.string(),
188
- status: z5.string(),
189
- deployed: z5.boolean(),
190
- hostname: z5.string(),
191
- organization: z5.object({
192
- name: z5.string(),
193
- 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()
194
681
  }),
195
- currentRelease: z5.nullable(
196
- z5.object({
197
- status: z5.string(),
198
- createdAt: z5.string().datetime()
682
+ currentRelease: z10.nullable(
683
+ z10.object({
684
+ status: z10.string(),
685
+ createdAt: z10.string().datetime()
199
686
  })
200
687
  )
201
688
  })
202
689
  )
203
690
  );
204
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
+
205
699
  // packages/fly-node/src/lib/schemas/certs-list-with-app.schema.ts
206
- import { z as z7 } from "zod";
700
+ import { z as z13 } from "zod";
207
701
 
208
702
  // packages/fly-node/src/lib/schemas/certs-list.schema.ts
209
- import { z as z6 } from "zod";
210
- var CertsListFlyResponseElementSchema = z6.object({
211
- createdAt: z6.string().datetime(),
212
- hostname: z6.string(),
213
- 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()
214
708
  });
215
- var CertsListTransformedResponseSchema = z6.array(
709
+ var CertsListTransformedResponseSchema = z12.array(
216
710
  withCamelCase(CertsListFlyResponseElementSchema)
217
711
  );
218
712
 
219
713
  // packages/fly-node/src/lib/schemas/certs-list-with-app.schema.ts
220
- var CertsListWithAppTransformedResponseSchema = z7.array(
714
+ var CertsListWithAppTransformedResponseSchema = z13.array(
221
715
  withCamelCase(
222
716
  CertsListFlyResponseElementSchema.extend({
223
- app: z7.string()
717
+ app: z13.string()
224
718
  })
225
719
  )
226
720
  );
227
721
 
228
722
  // packages/fly-node/src/lib/schemas/config-show.schema.ts
229
- import { z as z8 } from "zod";
723
+ import { z as z14 } from "zod";
230
724
  var ConfigShowResponseSchema = withCamelCase(
231
- z8.object({
232
- app: z8.string(),
233
- primaryRegion: z8.string().optional(),
234
- build: z8.record(z8.string(), z8.any()).optional().or(
235
- z8.object({
236
- args: z8.record(z8.string(), z8.string()).optional(),
237
- dockerfile: z8.string().optional(),
238
- 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()
239
733
  })
240
734
  ),
241
- deploy: z8.record(z8.string(), z8.any()).optional().or(z8.object({ strategy: z8.string().optional() })),
242
- env: z8.record(z8.string(), z8.string()).optional(),
243
- httpService: z8.record(z8.string(), z8.any()).optional(),
244
- mounts: z8.record(z8.string(), z8.any()).optional(),
245
- 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()
246
740
  }),
247
741
  {
248
742
  preserve: ["build.args", "env"]
@@ -250,119 +744,149 @@ var ConfigShowResponseSchema = withCamelCase(
250
744
  );
251
745
 
252
746
  // packages/fly-node/src/lib/schemas/deploy.schema.ts
253
- import { z as z9 } from "zod";
254
- var DeployResponseSchema = z9.object({
255
- app: z9.string(),
256
- hostname: z9.string(),
257
- 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()
258
752
  });
259
753
 
260
754
  // packages/fly-node/src/lib/schemas/helper-schemas.ts
261
- import { z as z10 } from "zod";
262
- var AllowEmptyUrlSchema = z10.string().url().or(z10.literal(""));
263
- 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-]+$/);
758
+
759
+ // packages/fly-node/src/lib/schemas/ips-list.schema.ts
760
+ import { z as z17 } from "zod";
761
+ var IpTypeSchema = z17.enum(["v4", "v6", "shared_v4", "private_v6"]).or(z17.string());
762
+ var IpsListFlyResponseElementSchema = z17.object({
763
+ id: z17.string(),
764
+ address: z17.string(),
765
+ type: IpTypeSchema,
766
+ region: z17.string(),
767
+ createdAt: z17.string()
768
+ });
769
+ var IpsListTransformedResponseSchema = z17.array(
770
+ withCamelCase(IpsListFlyResponseElementSchema)
771
+ );
264
772
 
265
773
  // packages/fly-node/src/lib/schemas/postgres-list.ts
266
- import { z as z11 } from "zod";
267
- var PostgresListTransformedResponseSchema = z11.array(
774
+ import { z as z18 } from "zod";
775
+ var PostgresListTransformedResponseSchema = z18.array(
268
776
  withCamelCase(
269
- z11.object({
270
- deployed: z11.boolean(),
271
- hostname: z11.string(),
272
- id: z11.string(),
273
- name: z11.string(),
274
- organization: z11.object({ id: z11.string(), slug: z11.string() }),
275
- status: z11.string(),
276
- version: z11.number()
777
+ z18.object({
778
+ deployed: z18.boolean(),
779
+ hostname: z18.string(),
780
+ id: z18.string(),
781
+ name: z18.string(),
782
+ organization: z18.object({ id: z18.string(), slug: z18.string() }),
783
+ status: z18.string(),
784
+ version: z18.number()
277
785
  })
278
786
  )
279
- ).or(z11.string());
787
+ ).or(z18.string());
280
788
 
281
789
  // packages/fly-node/src/lib/schemas/postgres-users-list.ts
282
- import { z as z12 } from "zod";
283
- var PostgresUsersListTransformedResponseSchema = z12.array(
790
+ import { z as z19 } from "zod";
791
+ var PostgresUsersListTransformedResponseSchema = z19.array(
284
792
  withCamelCase(
285
- z12.object({
286
- username: z12.string(),
287
- superuser: z12.boolean(),
288
- databases: z12.array(z12.string())
793
+ z19.object({
794
+ username: z19.string(),
795
+ superuser: z19.boolean(),
796
+ databases: z19.array(z19.string())
289
797
  })
290
798
  )
291
799
  );
292
800
 
293
801
  // packages/fly-node/src/lib/schemas/secrets-list-with-app.schema.ts
294
- import { z as z14 } from "zod";
802
+ import { z as z21 } from "zod";
295
803
 
296
804
  // packages/fly-node/src/lib/schemas/secrets-list.schema.ts
297
- import { z as z13 } from "zod";
298
- var SecretsListFlyResponseElementSchema = z13.object({
299
- name: z13.string(),
300
- digest: z13.string()
805
+ import { z as z20 } from "zod";
806
+ var SecretsListFlyResponseElementSchema = z20.object({
807
+ name: z20.string(),
808
+ digest: z20.string()
301
809
  });
302
- var SecretsListTransformedResponseSchema = z13.array(
810
+ var SecretsListTransformedResponseSchema = z20.array(
303
811
  withCamelCase(SecretsListFlyResponseElementSchema)
304
812
  );
305
813
 
306
814
  // packages/fly-node/src/lib/schemas/secrets-list-with-app.schema.ts
307
- var SecretsListWithAppTransformedResponseSchema = z14.array(
815
+ var SecretsListWithAppTransformedResponseSchema = z21.array(
308
816
  withCamelCase(
309
817
  SecretsListFlyResponseElementSchema.extend({
310
- app: z14.string()
818
+ app: z21.string()
311
819
  })
312
820
  )
313
821
  );
314
822
 
315
823
  // packages/fly-node/src/lib/schemas/status-extended.schema.ts
316
- import { z as z16 } from "zod";
824
+ import { z as z23 } from "zod";
317
825
 
318
826
  // packages/fly-node/src/lib/schemas/status.schema.ts
319
- import { z as z15 } from "zod";
320
- var statusFlyResponseSchema = z15.object({
321
- deployed: z15.boolean(),
322
- hostname: z15.string(),
323
- id: z15.string(),
324
- machines: z15.array(
325
- z15.object({
326
- id: z15.string(),
327
- name: z15.string(),
328
- state: z15.string(),
329
- region: z15.string(),
330
- createdAt: z15.string().datetime(),
331
- updatedAt: z15.string().datetime(),
332
- config: z15.object({
333
- env: z15.record(z15.string()),
334
- metadata: z15.record(z15.string())
827
+ import { z as z22 } from "zod";
828
+ var statusFlyResponseSchema = z22.object({
829
+ deployed: z22.boolean(),
830
+ hostname: z22.string(),
831
+ id: z22.string(),
832
+ machines: z22.array(
833
+ z22.object({
834
+ id: z22.string(),
835
+ name: z22.string(),
836
+ state: z22.string(),
837
+ region: z22.string(),
838
+ imageRef: z22.object({
839
+ registry: z22.string(),
840
+ repository: z22.string(),
841
+ tag: z22.string(),
842
+ digest: z22.string(),
843
+ labels: z22.record(z22.string()).optional()
844
+ }),
845
+ createdAt: z22.string().datetime(),
846
+ updatedAt: z22.string().datetime(),
847
+ config: z22.object({
848
+ env: z22.record(z22.string()),
849
+ metadata: z22.record(z22.string()),
850
+ guest: z22.object({
851
+ cpu_kind: z22.string().optional(),
852
+ cpus: z22.number().optional(),
853
+ memory_mb: z22.number().optional()
854
+ }).optional()
335
855
  }),
336
- events: z15.array(
337
- z15.object({
338
- type: z15.string(),
339
- status: z15.string(),
340
- timestamp: z15.number()
856
+ events: z22.array(
857
+ z22.object({
858
+ type: z22.string(),
859
+ status: z22.string(),
860
+ timestamp: z22.number()
341
861
  })
342
862
  ),
343
- checks: z15.array(
344
- z15.object({
345
- name: z15.string(),
346
- status: z15.string(),
347
- output: z15.string(),
348
- updatedAt: z15.string().datetime()
863
+ checks: z22.array(
864
+ z22.object({
865
+ name: z22.string(),
866
+ status: z22.string(),
867
+ output: z22.string(),
868
+ updatedAt: z22.string().datetime()
349
869
  })
350
870
  ).optional(),
351
- hostStatus: z15.string()
871
+ hostStatus: z22.string()
352
872
  })
353
873
  ),
354
- name: z15.string(),
355
- organization: z15.object({
356
- id: z15.string(),
357
- slug: z15.string()
874
+ name: z22.string(),
875
+ organization: z22.object({
876
+ id: z22.string(),
877
+ slug: z22.string()
358
878
  }),
359
- status: z15.string(),
360
- version: z15.number()
879
+ status: z22.string(),
880
+ version: z22.number()
361
881
  });
362
882
  var StatusTransformedResponseSchema = withCamelCase(
363
883
  statusFlyResponseSchema,
364
884
  {
365
- preserve: ["machines.config.env", "machines.config.metadata"],
885
+ preserve: [
886
+ "machines.config.env",
887
+ "machines.config.metadata",
888
+ "machines.config.guest"
889
+ ],
366
890
  specialCases: { AppURL: "appUrl" }
367
891
  }
368
892
  );
@@ -370,30 +894,36 @@ var StatusTransformedResponseSchema = withCamelCase(
370
894
  // packages/fly-node/src/lib/schemas/status-extended.schema.ts
371
895
  var StatusExtendedTransformedResponseSchema = withCamelCase(
372
896
  statusFlyResponseSchema.extend({
373
- domains: z16.array(z16.object({ hostname: z16.string() })),
374
- secrets: z16.array(z16.object({ name: z16.string() }))
897
+ domains: z23.array(z23.object({ hostname: z23.string() })),
898
+ secrets: z23.array(z23.object({ name: z23.string() }))
375
899
  }),
376
900
  {
377
- preserve: ["machines.config.env", "machines.config.metadata"]
901
+ preserve: [
902
+ "machines.config.env",
903
+ "machines.config.metadata",
904
+ "machines.config.guest"
905
+ ]
378
906
  }
379
907
  );
380
908
 
381
909
  // packages/fly-node/src/lib/schemas/version.schema.ts
382
- import { z as z17 } from "zod";
910
+ import { z as z24 } from "zod";
383
911
  var VersionTransformedResponseSchema = withCamelCase(
384
- z17.object({
385
- name: z17.string(),
386
- version: z17.string(),
387
- commit: z17.string(),
388
- branchName: z17.string(),
389
- buildDate: z17.string().datetime(),
390
- os: z17.string(),
391
- architecture: z17.string(),
392
- environment: z17.string()
912
+ z24.object({
913
+ name: z24.string(),
914
+ version: z24.string(),
915
+ commit: z24.string(),
916
+ branchName: z24.string(),
917
+ buildDate: z24.string().datetime(),
918
+ os: z24.string(),
919
+ architecture: z24.string(),
920
+ environment: z24.string()
393
921
  })
394
922
  );
395
923
 
396
924
  // packages/fly-node/src/lib/fly.class.ts
925
+ var MACHINE_STATE_INTERVAL_MS = 2e3;
926
+ var MACHINE_STATE_TIMEOUT_MS = 12e4;
397
927
  var Fly = class {
398
928
  /** Use underscore to avoid conflict with public `config` property */
399
929
  _config;
@@ -423,7 +953,10 @@ var Fly = class {
423
953
  info: config?.logger?.info || console.log,
424
954
  error: config?.logger?.error || console.error,
425
955
  traceCLI: config?.logger?.traceCLI ?? false,
426
- redactSecrets: config?.logger?.redactSecrets ?? true
956
+ redactSecrets: config?.logger?.redactSecrets ?? true,
957
+ verbose: config?.logger?.verbose ?? false,
958
+ debug: config?.logger?.debug ?? false,
959
+ streamToConsole: config?.logger?.streamToConsole ?? false
427
960
  };
428
961
  if (this._config.token) {
429
962
  process.env["FLY_ACCESS_TOKEN"] = this._config.token;
@@ -615,7 +1148,10 @@ ${error}`
615
1148
  */
616
1149
  config = {
617
1150
  /**
618
- * Save an application's remote configuration locally as TOML file.
1151
+ * Save an application's remote configuration locally.
1152
+ *
1153
+ * TOML by default; name the path `.json` or `.yaml`/`.yml` for either of
1154
+ * those instead.
619
1155
  *
620
1156
  * @param options - Options for saving an application's configuration
621
1157
  * @throws An error if the configuration cannot be saved
@@ -650,7 +1186,12 @@ ${error}`);
650
1186
  }
651
1187
  };
652
1188
  /**
653
- * Deploy an application.
1189
+ * Deploy an application, or just build its Docker image without deploying when
1190
+ * `buildOnly` is set (equivalent to using `build(options)`).
1191
+ *
1192
+ * Pre-building is useful to ensure the image can be built successfully and exists
1193
+ * before running a deploy that depends on it, and also to get the image reference for use in
1194
+ * subsequent operations.
654
1195
  *
655
1196
  * A valid config file is required but the app doesn't have to exist,
656
1197
  * since it gets created if needed.
@@ -660,15 +1201,28 @@ ${error}`);
660
1201
  * 2. Instance app name
661
1202
  * 3. App name from the provided config file
662
1203
  *
663
- * Existing secrets are preserved.
664
- *
665
- * @param options - Options for deploying an application
666
- * @throws An error if the deployment fails
1204
+ * @param options - Deployment or build options
1205
+ * @returns Build or deploy response depending on `buildOnly` option
1206
+ * @throws An error if the operation fails
667
1207
  */
668
1208
  deploy = async (options) => {
1209
+ const isBuildOnly = options?.buildOnly === true;
669
1210
  try {
670
1211
  await this.ensureInitialized();
671
- const appName = await this.deployApp(options);
1212
+ if (isBuildOnly) {
1213
+ const { appName: appName2, imageRef } = await this.deployApp({
1214
+ ...options,
1215
+ buildOnly: true
1216
+ });
1217
+ if (!imageRef) {
1218
+ throw new Error(
1219
+ "Build completed but image reference not found in output"
1220
+ );
1221
+ }
1222
+ this.logger.info(`Image for '${appName2}' built: ${imageRef}`);
1223
+ return BuildResponseSchema.parse({ appName: appName2, imageRef });
1224
+ }
1225
+ const { appName } = await this.deployApp(options);
672
1226
  this.logger.info(`Application '${appName}' was deployed`);
673
1227
  const status = await this.fetchAppStatus("throwOnError", {
674
1228
  app: appName
@@ -680,16 +1234,184 @@ ${error}`);
680
1234
  });
681
1235
  } catch (error) {
682
1236
  throw new Error(
683
- `[deploy] something broke, check your deployments
1237
+ `[deploy] something broke, check your ${isBuildOnly ? "builds" : "deployments"}
684
1238
  ${error}`
685
1239
  );
686
1240
  }
687
1241
  };
1242
+ /**
1243
+ * Manage public IP addresses
1244
+ */
1245
+ ips = {
1246
+ /**
1247
+ * List the public IP addresses allocated to an application
1248
+ *
1249
+ * @param options - The application or configuration to list addresses for
1250
+ * @returns The allocated addresses, empty when the app has none
1251
+ * @throws An error if listing addresses fails
1252
+ */
1253
+ list: async (options) => {
1254
+ try {
1255
+ await this.ensureInitialized();
1256
+ return await this.fetchAppIps("throwOnError", options);
1257
+ } catch (error) {
1258
+ throw new Error(`[list ips] something broke
1259
+ ${error}`);
1260
+ }
1261
+ },
1262
+ /**
1263
+ * Give an application the public addresses it needs to be reachable.
1264
+ *
1265
+ * Idempotent by inspection: it allocates only what is missing, so it is
1266
+ * safe on every deploy rather than only on create. That matters because
1267
+ * `flyctl` allocates addresses only for an app it creates itself — an app
1268
+ * that arrives any other way, such as a registry push auto-creating it,
1269
+ * deploys green and answers nothing.
1270
+ *
1271
+ * @param options - The application, and which addresses to ensure
1272
+ * @returns The addresses the application holds afterwards
1273
+ * @throws An error if an address cannot be allocated
1274
+ */
1275
+ ensure: async (options) => {
1276
+ try {
1277
+ await this.ensureInitialized();
1278
+ const { sharedV4 = true, v6 = true } = options ?? {};
1279
+ const existing = await this.fetchAppIps("throwOnError", options);
1280
+ const has = (...types) => existing.some((ip) => types.includes(ip.type));
1281
+ if (sharedV4 && !has("v4", "shared_v4")) {
1282
+ await this.allocateIp("allocate-v4", options);
1283
+ this.logger.info("Allocated a shared IPv4 address");
1284
+ }
1285
+ if (v6 && !has("v6")) {
1286
+ await this.allocateIp("allocate-v6", options);
1287
+ this.logger.info("Allocated a dedicated IPv6 address");
1288
+ }
1289
+ return await this.fetchAppIps("throwOnError", options);
1290
+ } catch (error) {
1291
+ throw new Error(
1292
+ `[ensure ips] something broke, check your app addresses
1293
+ ${error}`
1294
+ );
1295
+ }
1296
+ }
1297
+ };
1298
+ /**
1299
+ * Manage machines
1300
+ */
1301
+ machines = {
1302
+ /**
1303
+ * Start a machine
1304
+ *
1305
+ * @param app - The name of the application
1306
+ * @param machineId - The machine ID to start
1307
+ * @throws An error if the machine cannot be started
1308
+ */
1309
+ start: async (app, machineId) => {
1310
+ try {
1311
+ await this.ensureInitialized();
1312
+ await this.startMachine(app, machineId);
1313
+ this.logger.info(`Machine '${machineId}' in app '${app}' was started`);
1314
+ } catch (error) {
1315
+ throw new Error(`[start machine] something broke
1316
+ ${error}`);
1317
+ }
1318
+ },
1319
+ /**
1320
+ * Stop a machine
1321
+ *
1322
+ * @param app - The name of the application
1323
+ * @param machineId - The machine ID to stop
1324
+ * @throws An error if the machine cannot be stopped
1325
+ */
1326
+ stop: async (app, machineId) => {
1327
+ try {
1328
+ await this.ensureInitialized();
1329
+ await this.stopMachine(app, machineId);
1330
+ this.logger.info(`Machine '${machineId}' in app '${app}' was stopped`);
1331
+ } catch (error) {
1332
+ throw new Error(`[stop machine] something broke
1333
+ ${error}`);
1334
+ }
1335
+ },
1336
+ /**
1337
+ * Restart a machine by stopping then starting it.
1338
+ *
1339
+ * Waits until Fly reports the machine stopped (or suspended) before
1340
+ * starting it, then until it is started. If the start fails after the
1341
+ * stop, the error says the machine was left stopped.
1342
+ *
1343
+ * @param app - The name of the application
1344
+ * @param machineId - The machine ID to restart
1345
+ * @throws An error if the machine cannot be restarted
1346
+ */
1347
+ restart: async (app, machineId) => {
1348
+ try {
1349
+ await this.ensureInitialized();
1350
+ await this.restartMachine(app, machineId);
1351
+ this.logger.info(
1352
+ `Machine '${machineId}' in app '${app}' was restarted`
1353
+ );
1354
+ } catch (error) {
1355
+ throw new Error(`[restart machine] something broke
1356
+ ${error}`);
1357
+ }
1358
+ },
1359
+ /**
1360
+ * Update a machine's per-machine configuration (env vars, etc.).
1361
+ *
1362
+ * Unlike `restart`, this creates a new machine version from the updated config
1363
+ * and forces a cold start — it does NOT resume from a suspended memory snapshot.
1364
+ *
1365
+ * @param app - The name of the application
1366
+ * @param machineId - The machine ID to update
1367
+ * @param options - Fields to update; env values set to `''` clear that var
1368
+ * @throws An error if the machine cannot be updated
1369
+ */
1370
+ update: async (app, machineId, options) => {
1371
+ try {
1372
+ await this.ensureInitialized();
1373
+ await this.updateMachine(app, machineId, options);
1374
+ this.logger.info(`Machine '${machineId}' in app '${app}' was updated`);
1375
+ } catch (error) {
1376
+ throw new Error(`[update machine] something broke
1377
+ ${error}`);
1378
+ }
1379
+ }
1380
+ };
688
1381
  postgres = {
689
1382
  detach: async (cluster, app) => {
690
1383
  await this.detachPostgres(cluster, app);
691
1384
  }
692
1385
  };
1386
+ /**
1387
+ * Run commands inside a running machine
1388
+ */
1389
+ ssh = {
1390
+ /**
1391
+ * Execute a command in a running machine and return its output.
1392
+ *
1393
+ * Requires a started machine - Fly cannot connect to a stopped or
1394
+ * suspended one. Use `machines.start` first when the app may be idle.
1395
+ *
1396
+ * The output is returned to the caller and not logged unless CLI tracing
1397
+ * is enabled, so it can be used to read values that are otherwise
1398
+ * write-only, such as secrets injected at deploy time.
1399
+ *
1400
+ * @param app - The name of the application
1401
+ * @param command - The command to run inside the machine
1402
+ * @returns The command output
1403
+ * @throws An error if there is no started machine or the command fails
1404
+ */
1405
+ exec: async (app, command) => {
1406
+ try {
1407
+ await this.ensureInitialized();
1408
+ return await this.sshExec(app, command);
1409
+ } catch (error) {
1410
+ throw new Error(`[ssh exec] something broke
1411
+ ${error}`);
1412
+ }
1413
+ }
1414
+ };
693
1415
  /**
694
1416
  * Manage application secrets
695
1417
  */
@@ -716,6 +1438,28 @@ ${error}`
716
1438
  );
717
1439
  }
718
1440
  },
1441
+ /**
1442
+ * Apply secrets that were staged with `set({ stage: true })`.
1443
+ *
1444
+ * Staging first and deploying afterwards lets a set of apps take a new
1445
+ * value together, instead of each restarting as its own secret is written.
1446
+ *
1447
+ * Fly needs a started machine to update, so an app whose machines are all
1448
+ * stopped or suspended has to be started before this will do anything.
1449
+ *
1450
+ * @param app - The name of the application
1451
+ * @throws An error if the staged secrets cannot be deployed
1452
+ */
1453
+ deploy: async (app) => {
1454
+ try {
1455
+ await this.ensureInitialized();
1456
+ await this.deployStagedSecrets(app);
1457
+ this.logger.info(`Staged secrets were deployed for '${app}'`);
1458
+ } catch (error) {
1459
+ throw new Error(`[deploy secrets] something broke
1460
+ ${error}`);
1461
+ }
1462
+ },
719
1463
  /**
720
1464
  * List secrets for an application or all secrets when options is 'all'
721
1465
  *
@@ -776,6 +1520,22 @@ ${error}`);
776
1520
  return null;
777
1521
  }
778
1522
  };
1523
+ //
1524
+ // DX friendly methods outside what Fly CLI provides
1525
+ //
1526
+ /**
1527
+ * Build a Docker image for an application and push it to the Fly registry
1528
+ * without deploying.
1529
+ *
1530
+ * The image reference is returned for use in a subsequent `deploy` that depends on it.
1531
+ *
1532
+ * Shorthand for `deploy({ ...options, buildOnly: true })`.
1533
+ *
1534
+ * @param options - Build options
1535
+ * @returns The app name and image reference for use in a subsequent `deploy`
1536
+ * @throws An error if the build fails or the image reference cannot be parsed
1537
+ */
1538
+ build = (options) => this.deploy({ ...options, buildOnly: true });
779
1539
  /**
780
1540
  * Get the extended details of an application
781
1541
  *
@@ -822,12 +1582,11 @@ ${error}`);
822
1582
  }
823
1583
  /**
824
1584
  * @private
825
- * @returns The name of the deployed application
1585
+ * @returns The app name and optional image reference (only set when buildOnly is true)
826
1586
  * @throws An error if the deployment fails
827
1587
  */
828
1588
  async deployApp(options) {
829
1589
  let appName = "";
830
- let appSecrets = [];
831
1590
  let deployConfig = options?.config || this.instanceConfig;
832
1591
  let lookupApp = options?.app || this.instanceApp;
833
1592
  const lookupConfig = deployConfig;
@@ -892,26 +1651,30 @@ ${error}`);
892
1651
  appName = name;
893
1652
  this.logger.info(`Application '${appName}' was created`);
894
1653
  } else {
895
- appSecrets = await this.fetchAppSecrets("throwOnError", { app: appName });
896
1654
  this.logger.info(`Updating existing application '${appName}'`);
897
1655
  }
898
1656
  NameSchema.parse(appName);
899
- if (options?.secrets) {
900
- const existingSecrets = new Set(appSecrets.map(({ name }) => name));
901
- const newSecrets = {};
1657
+ if (!options?.buildOnly && options?.secrets) {
1658
+ const staged = {};
1659
+ const empty = [];
902
1660
  for (const [key, value] of Object.entries(options.secrets)) {
903
- if (!existingSecrets.has(key)) {
904
- newSecrets[key] = value;
1661
+ if (value === "") {
1662
+ empty.push(key);
905
1663
  } else {
906
- this.logger.info(
907
- `Secret '${key}' already exists for '${appName}', skipping`
908
- );
1664
+ staged[key] = value;
909
1665
  }
910
1666
  }
911
- const keys = Object.keys(newSecrets);
1667
+ if (empty.length > 0) {
1668
+ this.logger.error(
1669
+ `Refusing to blank secrets with no value for '${appName}': ${empty.join(", ")}`
1670
+ );
1671
+ }
1672
+ const keys = Object.keys(staged);
912
1673
  if (keys.length > 0) {
913
- this.logger.info(`Adding secrets to '${appName}': ${keys.join(", ")}`);
914
- await this.setAppSecrets(newSecrets, {
1674
+ this.logger.info(
1675
+ `Staging secrets for '${appName}': ${keys.join(", ")}`
1676
+ );
1677
+ await this.setAppSecrets(staged, {
915
1678
  app: appName,
916
1679
  stage: true
917
1680
  });
@@ -923,7 +1686,7 @@ ${error}`);
923
1686
  );
924
1687
  appName = options.app;
925
1688
  }
926
- if (options?.postgres) {
1689
+ if (!options?.buildOnly && options?.postgres) {
927
1690
  const users = await this.fetchPostgresUsers(
928
1691
  options.postgres,
929
1692
  "nullOnError"
@@ -938,9 +1701,13 @@ ${error}`);
938
1701
  );
939
1702
  } else {
940
1703
  this.logger.info(
941
- `Attach Postgres cluster '${options.postgres}' to '${appName}'`
1704
+ `Attach Postgres cluster '${options.postgres}' to '${appName}'${options.databaseName ? ` with database '${options.databaseName}'` : ""}`
1705
+ );
1706
+ await this.attachPostgres(
1707
+ options.postgres,
1708
+ appName,
1709
+ options.databaseName
942
1710
  );
943
- await this.attachPostgres(options.postgres, appName);
944
1711
  }
945
1712
  }
946
1713
  const args = ["deploy", "--app", appName, "--config", deployConfig];
@@ -953,20 +1720,39 @@ ${error}`);
953
1720
  for (const [key, value] of Object.entries(options?.env || {})) {
954
1721
  args.push("--env", `${key}=${this.safeArg(value)}`);
955
1722
  }
1723
+ for (const [key, value] of Object.entries(options?.buildArgs || {})) {
1724
+ args.push("--build-arg", `${key}=${this.safeArg(value)}`);
1725
+ }
1726
+ if (options?.image) {
1727
+ args.push("--image", options.image);
1728
+ }
1729
+ if (options?.buildOnly) {
1730
+ args.push("--build-only", "--push");
1731
+ }
956
1732
  if (options?.optOutDepotBuilder) {
957
1733
  args.push("--depot=false");
958
1734
  }
959
1735
  args.push("--yes");
960
- this.logger.info(`Deploying '${appName}'...`);
961
- await this.execFly(args);
962
- return appName;
1736
+ this.logger.info(
1737
+ options?.buildOnly ? `Building image for '${appName}'...` : `Deploying '${appName}'...`
1738
+ );
1739
+ const output = await this.execFly(
1740
+ args,
1741
+ options?.buildOnly ? { streamStrategy: "combined" } : void 0
1742
+ );
1743
+ const imageRef = options?.buildOnly ? output?.match(/registry\.fly\.io\/\S+/)?.[0] : void 0;
1744
+ return { appName, imageRef };
963
1745
  }
964
1746
  /**
965
1747
  * @private
966
1748
  * @throws An error if the Postgres database cannot be attached
967
1749
  */
968
- async attachPostgres(postgres, app) {
969
- const args = ["postgres", "attach", postgres, "--app", app, "--yes"];
1750
+ async attachPostgres(postgres, app, databaseName) {
1751
+ const args = ["postgres", "attach", postgres, "--app", app];
1752
+ if (databaseName) {
1753
+ args.push("--database-name", databaseName);
1754
+ }
1755
+ args.push("--yes");
970
1756
  await this.execFly(args);
971
1757
  }
972
1758
  /**
@@ -1040,6 +1826,45 @@ ${error}`);
1040
1826
  await this.execFly(args);
1041
1827
  return NameSchema.parse(status.name);
1042
1828
  }
1829
+ /**
1830
+ * Allocate one public address.
1831
+ *
1832
+ * A dedicated v4 is billed, so the v4 path is always `--shared`.
1833
+ *
1834
+ * The two commands do not take the same flags: `allocate-v4` has `--yes`
1835
+ * because a dedicated v4 costs money and prompts, while `allocate-v6` is
1836
+ * free, never prompts, and rejects the flag outright with `unknown flag`.
1837
+ * The asymmetry is flyctl's, not ours — do not tidy it away.
1838
+ *
1839
+ * @private
1840
+ * @throws An error if the address cannot be allocated
1841
+ */
1842
+ async allocateIp(command, options) {
1843
+ const args = ["ips", command];
1844
+ if (command === "allocate-v4") {
1845
+ args.push("--shared");
1846
+ }
1847
+ args.push(...this.getAppOrConfigArgs(options));
1848
+ if (command === "allocate-v4") {
1849
+ args.push("--yes");
1850
+ }
1851
+ await this.execFly(args);
1852
+ }
1853
+ async fetchAppIps(onError, options) {
1854
+ const args = ["ips", "list"];
1855
+ args.push(...this.getAppOrConfigArgs(options));
1856
+ args.push("--json");
1857
+ try {
1858
+ return await IpsListTransformedResponseSchema.parseAsync(
1859
+ await this.execFly(args)
1860
+ );
1861
+ } catch (error) {
1862
+ if (onError === "throwOnError") {
1863
+ throw error;
1864
+ }
1865
+ return null;
1866
+ }
1867
+ }
1043
1868
  /**
1044
1869
  * @private
1045
1870
  * @returns The name of the application
@@ -1053,6 +1878,102 @@ ${error}`);
1053
1878
  await this.execFly(args);
1054
1879
  return NameSchema.parse(status.name);
1055
1880
  }
1881
+ /**
1882
+ * @private
1883
+ * Deploy secrets previously staged for an application
1884
+ * @throws An error if the staged secrets cannot be deployed
1885
+ */
1886
+ async deployStagedSecrets(app) {
1887
+ const args = ["secrets", "deploy", "--app", app];
1888
+ await this.execFly(args);
1889
+ }
1890
+ /**
1891
+ * @private
1892
+ * Execute a command inside a running machine
1893
+ * @returns The command output
1894
+ * @throws An error if the command fails
1895
+ */
1896
+ async sshExec(app, command) {
1897
+ const args = ["ssh", "console", "--app", app, "--command", command];
1898
+ return await this.execFly(args);
1899
+ }
1900
+ /**
1901
+ * @private
1902
+ * Start a machine
1903
+ * @throws An error if the machine cannot be started
1904
+ */
1905
+ async startMachine(app, machineId) {
1906
+ const args = ["machine", "start", machineId, "--app", app];
1907
+ await this.execFly(args);
1908
+ }
1909
+ /**
1910
+ * @private
1911
+ * Stop a machine
1912
+ * @throws An error if the machine cannot be stopped
1913
+ */
1914
+ async stopMachine(app, machineId) {
1915
+ const args = ["machine", "stop", machineId, "--app", app];
1916
+ await this.execFly(args);
1917
+ }
1918
+ /**
1919
+ * @private
1920
+ * Restart a machine by stopping then starting it, waiting on the state Fly
1921
+ * reports rather than a fixed delay: the start is only issued once the
1922
+ * machine is stopped (or suspended), and the restart is done once it is
1923
+ * started again.
1924
+ * @throws An error saying the machine was left stopped when anything after
1925
+ * the stop fails
1926
+ */
1927
+ async restartMachine(app, machineId) {
1928
+ await this.stopMachine(app, machineId);
1929
+ try {
1930
+ await this.waitForMachineState(app, machineId, ["stopped", "suspended"]);
1931
+ await this.startMachine(app, machineId);
1932
+ await this.waitForMachineState(app, machineId, ["started"]);
1933
+ } catch (error) {
1934
+ const reason = error instanceof Error ? error.message : String(error);
1935
+ throw new Error(
1936
+ `Machine '${machineId}' in app '${app}' was stopped but did not start again: ${reason}`,
1937
+ { cause: error }
1938
+ );
1939
+ }
1940
+ }
1941
+ /**
1942
+ * @private
1943
+ * Poll the app status until the machine reports one of the given states
1944
+ * @throws An error if the machine does not reach a state in time
1945
+ */
1946
+ async waitForMachineState(app, machineId, states) {
1947
+ const deadline = Date.now() + MACHINE_STATE_TIMEOUT_MS;
1948
+ while (Date.now() < deadline) {
1949
+ const status = await this.fetchAppStatus("nullOnError", { app });
1950
+ const machine = status?.machines.find(({ id }) => id === machineId);
1951
+ if (machine && states.includes(machine.state)) {
1952
+ return;
1953
+ }
1954
+ await new Promise(
1955
+ (resolve) => setTimeout(resolve, MACHINE_STATE_INTERVAL_MS)
1956
+ );
1957
+ }
1958
+ throw new Error(
1959
+ `Machine '${machineId}' in app '${app}' did not reach ${states.join("/")} in time`
1960
+ );
1961
+ }
1962
+ /**
1963
+ * @private
1964
+ * Update a machine's per-machine config (env vars, etc.).
1965
+ * Creates a new machine version so the machine cold-starts from the updated config,
1966
+ * bypassing any suspended memory snapshot.
1967
+ * @throws An error if the machine cannot be updated
1968
+ */
1969
+ async updateMachine(app, machineId, options) {
1970
+ const args = ["machine", "update", machineId, "--app", app];
1971
+ for (const [key, value] of Object.entries(options.env || {})) {
1972
+ args.push("--env", `${key}=${this.safeArg(value)}`);
1973
+ }
1974
+ args.push("--yes");
1975
+ await this.execFly(args);
1976
+ }
1056
1977
  async fetchAllApps(onError) {
1057
1978
  const args = ["apps", "list", "--json"];
1058
1979
  try {
@@ -1207,9 +2128,23 @@ ${JSON.stringify(response, null, 2)}`);
1207
2128
  * @private
1208
2129
  * Save remote config to a local file
1209
2130
  *
2131
+ * Two things flyctl expects that a first-time caller would not: the output
2132
+ * format is no longer sniffed from the path's extension — `--json`/`--yaml`
2133
+ * has to be passed, TOML being what is left over when neither is — and the
2134
+ * destination must already exist as a parseable file of that format, or
2135
+ * `flyctl` refuses to write to it at all, mistaking "does not exist yet"
2136
+ * for "path is wrong". A fresh, empty seed of the right shape satisfies
2137
+ * that read without affecting what gets written back over it.
2138
+ *
1210
2139
  * @throws An error if the config cannot be saved
1211
2140
  */
1212
2141
  async saveConfig(options) {
2142
+ const isJson = options.config.endsWith(".json");
2143
+ const isYaml = /\.ya?ml$/.test(options.config);
2144
+ if (!existsSync(options.config)) {
2145
+ mkdirSync(dirname(options.config), { recursive: true });
2146
+ writeFileSync(options.config, isJson ? "{}" : "");
2147
+ }
1213
2148
  const args = [
1214
2149
  "config",
1215
2150
  "save",
@@ -1217,6 +2152,7 @@ ${JSON.stringify(response, null, 2)}`);
1217
2152
  options.app,
1218
2153
  "--config",
1219
2154
  options.config,
2155
+ ...isJson ? ["--json"] : isYaml ? ["--yaml"] : [],
1220
2156
  "--yes"
1221
2157
  ];
1222
2158
  await this.execFly(args);
@@ -1228,8 +2164,7 @@ ${JSON.stringify(response, null, 2)}`);
1228
2164
  * @throws An error if Fly CLI is not installed or not authenticated
1229
2165
  */
1230
2166
  async ensureInitialized() {
1231
- if (this.initialized)
1232
- return;
2167
+ if (this.initialized) return;
1233
2168
  try {
1234
2169
  if (!await this.isInstalled()) {
1235
2170
  throw new Error("Fly CLI must be installed to use this library");
@@ -1246,6 +2181,12 @@ ${JSON.stringify(response, null, 2)}`);
1246
2181
  }
1247
2182
  async execFly(command, options, onError = "throwOnError") {
1248
2183
  const args = Array.isArray(command) ? command : command.split(" ");
2184
+ if (this.logger.verbose) {
2185
+ args.push("--verbose");
2186
+ }
2187
+ if (this.logger.debug) {
2188
+ args.push("--debug");
2189
+ }
1249
2190
  const flyCmd = "flyctl";
1250
2191
  const toLogCmd = `${flyCmd} ${args.join(" ")}`;
1251
2192
  let output = "";
@@ -1255,11 +2196,17 @@ ${JSON.stringify(response, null, 2)}`);
1255
2196
  output = await spawnPty(flyCmd, args, { prompt: options.prompt });
1256
2197
  this.traceCLI("RESULT", output);
1257
2198
  } else {
1258
- const result = await spawn(flyCmd, args, options);
1259
- output = result.stdout.trim();
2199
+ const { streamStrategy = "stdout", ...spawnOpts } = options ?? {};
2200
+ const result = await spawn(flyCmd, args, {
2201
+ ...spawnOpts,
2202
+ streamToConsole: this.logger.streamToConsole
2203
+ });
2204
+ const stdout = result.stdout.trim();
1260
2205
  const stderr = result.stderr.trim();
1261
- this.traceCLI("RESULT", `${output}${stderr ? `
2206
+ this.traceCLI("RESULT", `${stdout}${stderr ? `
1262
2207
  ${stderr}` : ""}`);
2208
+ output = streamStrategy === "combined" ? `${stdout}
2209
+ ${stderr}` : streamStrategy === "stderr" ? stderr : stdout;
1263
2210
  }
1264
2211
  } catch (error) {
1265
2212
  const errorMsg = error.message;
@@ -1429,5 +2376,13 @@ ${errorMsg}`);
1429
2376
  }
1430
2377
  };
1431
2378
  export {
1432
- Fly
2379
+ CertificateApiResponseSchema,
2380
+ CertificateListApiResponseSchema,
2381
+ DnsInstructionsSchema,
2382
+ Fly,
2383
+ FlyApi,
2384
+ FlyApiError,
2385
+ HostnameCheckApiResponseSchema,
2386
+ MachineApiResponseSchema,
2387
+ MachineListApiResponseSchema
1433
2388
  };