@cdwr/fly-node 0.3.0 → 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/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@cdwr/fly-node",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "The flyctl node wrapper for programmatic deployments to fly.io.",
5
5
  "repository": {
6
6
  "type": "git",
7
- "url": "https://github.com/codeware-sthlm/codeware.git",
7
+ "url": "https://github.com/codeware-sthlm/cdwr.git",
8
8
  "directory": "packages/fly-node"
9
9
  },
10
10
  "author": {
@@ -37,6 +37,11 @@
37
37
  "types": "./src/index.d.ts",
38
38
  "import": "./index.js",
39
39
  "require": "./index.cjs"
40
+ },
41
+ "./api": {
42
+ "types": "./src/api.d.ts",
43
+ "import": "./api.js",
44
+ "require": "./api.cjs"
40
45
  }
41
46
  },
42
47
  "types": "./src/index.d.ts",
package/src/api.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Fly over its GraphQL API, without the CLI.
3
+ *
4
+ * A separate entry point because the two halves of this package have different
5
+ * runtime requirements: the `Fly` class shells out to `flyctl` and reaches a
6
+ * native pty module through `@codeware/shared/util/misc`, neither of which
7
+ * exists inside an application image. Importing the root barrel to reach
8
+ * `FlyApi` would pull all of that into the bundle.
9
+ *
10
+ * Nothing here touches the filesystem or spawns a process, so it runs anywhere
11
+ * `fetch` does.
12
+ */
13
+ export { FlyApi, FlyApiError, type FlyApiConfig } from './lib/fly-api.class';
14
+ export { type Certificate, CertificateApiResponseSchema, CertificateListApiResponseSchema, type DnsInstructions, DnsInstructionsSchema, type HostnameCheck, HostnameCheckApiResponseSchema } from './lib/schemas/certificate.schema';
15
+ export { type Machine, MachineApiResponseSchema, MachineListApiResponseSchema } from './lib/schemas/machine.schema';
package/src/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
+ export * from './api';
1
2
  export * from './lib/fly.class';
2
- export type { Config, DeployAppOptions, DeployResponse, SaveConfigOptions } from './lib/types';
3
+ export type { BuildResponse, Config, DeployAppOptions, DeployResponse, MachineOperationOptions, SaveConfigOptions, StatusResponse } from './lib/types';
@@ -0,0 +1,193 @@
1
+ import { type Certificate, type DnsInstructions, type HostnameCheck } from './schemas/certificate.schema';
2
+ import { type Machine } from './schemas/machine.schema';
3
+ export type FlyApiConfig = {
4
+ /** Fly API token. An org-scoped token can manage certificates for its apps */
5
+ token: string;
6
+ /** Override the endpoint, for tests or a private Fly instance */
7
+ apiUrl?: string;
8
+ /** Override the machines endpoint, for tests or a private Fly instance */
9
+ machinesUrl?: string;
10
+ /** Called with a one-line description of every request; defaults to silence */
11
+ log?: (message: string) => void;
12
+ };
13
+ /** A GraphQL error as Fly returns it — status 200 with an `errors` array */
14
+ type GraphQLError = {
15
+ message: string;
16
+ extensions?: {
17
+ code?: string;
18
+ };
19
+ };
20
+ /**
21
+ * A rejection from Fly, carrying the codes it sent.
22
+ *
23
+ * The codes matter: `NOT_FOUND` for a hostname with no certificate is an
24
+ * answer, while everything else is a fault. Callers should not have to match
25
+ * on message text to tell them apart.
26
+ */
27
+ export declare class FlyApiError extends Error {
28
+ readonly errors: Array<GraphQLError>;
29
+ constructor(message: string, errors: Array<GraphQLError>);
30
+ /** Whether every error is Fly saying the thing simply does not exist */
31
+ get isNotFound(): boolean;
32
+ /**
33
+ * Whether every error is Fly refusing a hostname that already has a
34
+ * certificate on the app.
35
+ *
36
+ * No `extensions.code` comes with this one — Fly's own dashboard and
37
+ * `flyctl` hit the same message, and both work around it the same way this
38
+ * class does, by re-reading rather than retrying the mutation.
39
+ */
40
+ get isAlreadyExists(): boolean;
41
+ }
42
+ /**
43
+ * Fly over its HTTP APIs, with no `flyctl` in sight.
44
+ *
45
+ * The `Fly` class in this package drives the CLI, which is the right tool in
46
+ * CI: it can build and deploy, and a runner has the binary. It cannot run
47
+ * inside an application server — there is no binary in the image, and the
48
+ * interactive paths need a pty.
49
+ *
50
+ * This class exists for the operations an application needs to perform on
51
+ * itself at runtime. It is deliberately a small subset rather than a second
52
+ * implementation of the whole CLI: certificates, because a custom domain has to
53
+ * be requested, checked and shown to a customer while they wait, and machine
54
+ * restarts, because a setting read at boot needs a boot to take effect.
55
+ *
56
+ * Fly splits those across two APIs and so does this class — certificates over
57
+ * GraphQL, machines over the REST Machines API. One token authenticates both.
58
+ * The split is Fly's; it is not hidden here, because the two have different
59
+ * hosts and different failure shapes.
60
+ *
61
+ * Where this and the CLI can do the same thing the returned shapes agree, so a
62
+ * caller can move between them. Where they differ, the API gives *more*:
63
+ * issuance state and the DNS records to create come back as fields rather than
64
+ * as text a human was meant to read.
65
+ */
66
+ export declare class FlyApi {
67
+ private readonly token;
68
+ private readonly apiUrl;
69
+ private readonly machinesUrl;
70
+ private readonly log;
71
+ constructor(config: FlyApiConfig);
72
+ /**
73
+ * Manage certificates for an app.
74
+ *
75
+ * Every method takes the app name explicitly: this client is used by a
76
+ * process acting on *other* apps — the cms managing a tenant's web app — so
77
+ * there is no ambient "current app" to default to.
78
+ */
79
+ certs: {
80
+ /**
81
+ * Request a certificate for a hostname.
82
+ *
83
+ * Safe to call when one already exists: Fly's own mutation is not
84
+ * idempotent — a hostname it already has a certificate for on this app is
85
+ * a fault, not a no-op, so this re-reads the existing certificate itself
86
+ * rather than surfacing that as an error a caller has to know to expect.
87
+ *
88
+ * Requesting before DNS is in place is normal and expected — the
89
+ * certificate stays pending until the records resolve, and the returned
90
+ * validation fields are what you show the customer meanwhile.
91
+ *
92
+ * @param app - Fly app name the domain should serve from
93
+ * @param hostname - Domain without a scheme, e.g. `tours.example.com`
94
+ * @returns The certificate, plus what Fly resolves for that hostname now
95
+ */
96
+ add: (app: string, hostname: string) => Promise<{
97
+ certificate: Certificate;
98
+ check: HostnameCheck | null;
99
+ }>;
100
+ /**
101
+ * Read one certificate, or `null` when the app has none for that hostname.
102
+ *
103
+ * This is the call behind a "check" button: it re-reads issuance state from
104
+ * Fly rather than trusting anything stored locally.
105
+ *
106
+ * Fly reports an absent certificate as a `NOT_FOUND` *error* rather than a
107
+ * null field, so that case is translated here — asking about a domain
108
+ * nobody has added yet is an ordinary question with an ordinary answer.
109
+ */
110
+ get: (app: string, hostname: string) => Promise<Certificate | null>;
111
+ /**
112
+ * What Fly resolves for a hostname right now, and what it objects to.
113
+ *
114
+ * A mutation on Fly's side despite reading rather than writing anything —
115
+ * `AppCertificate.check` is a plain boolean flag, and `HostnameCheck` is
116
+ * only ever returned by `addCertificate` and this, `checkCertificate`.
117
+ * Separate from `get` rather than folded into it: triggering a live dns
118
+ * resolution on every read would cost a caller that only wants issuance
119
+ * state. Pair the two when a person has just edited their records and
120
+ * wants to know whether it took.
121
+ *
122
+ * `errors` is the useful half — it is what Fly's own dashboard prints as
123
+ * "validation issues", already phrased for whoever owns the domain.
124
+ *
125
+ * @returns `null` when the app has no certificate for that hostname
126
+ */
127
+ check: (app: string, hostname: string) => Promise<HostnameCheck | null>;
128
+ /** Every certificate on an app */
129
+ list: (app: string) => Promise<Array<Certificate>>;
130
+ /**
131
+ * Remove a certificate.
132
+ *
133
+ * The hostname keeps resolving until its DNS is changed — this only stops
134
+ * Fly serving TLS for it.
135
+ */
136
+ remove: (app: string, hostname: string) => Promise<void>;
137
+ };
138
+ /**
139
+ * Operate an app's machines.
140
+ *
141
+ * Over Fly's REST Machines API rather than GraphQL, which has no current
142
+ * equivalent — the GraphQL mutations date from the Nomad platform and no
143
+ * longer apply.
144
+ */
145
+ machines: {
146
+ /** Every machine on an app */
147
+ list: (app: string) => Promise<Array<Machine>>;
148
+ /**
149
+ * Restart an app's machines.
150
+ *
151
+ * One at a time on purpose: a settings change that only takes effect at
152
+ * boot should not cost the app its availability to apply. Restarting them
153
+ * together would drop every machine at once, while sequentially leaves the
154
+ * others serving. The trade is that a large app takes longer.
155
+ *
156
+ * A machine that fails to restart stops the run rather than being skipped —
157
+ * a half-restarted app is running two configurations at the same time, and
158
+ * silently returning "some of them" invites calling that done.
159
+ *
160
+ * @param app - Fly app name
161
+ * @param machineId - Restart only this machine, instead of all of them
162
+ * @returns Ids of the machines that were restarted, in the order they were
163
+ */
164
+ restart: (app: string, machineId?: string) => Promise<Array<string>>;
165
+ };
166
+ /**
167
+ * The DNS records a customer must create for a certificate to validate.
168
+ *
169
+ * Pulled out of the certificate rather than fetched, so a caller that
170
+ * already has one does not pay for a second round trip.
171
+ */
172
+ static dnsInstructions(certificate: Certificate): DnsInstructions;
173
+ /**
174
+ * @private
175
+ * One GraphQL round trip.
176
+ *
177
+ * Fly answers a failed query with HTTP 200 and an `errors` array, so a
178
+ * response is only successful when both are checked — trusting the status
179
+ * alone would turn "permission denied" into a parse error further down.
180
+ */
181
+ private request;
182
+ /**
183
+ * @private
184
+ * One call to the Machines REST API.
185
+ *
186
+ * Unlike GraphQL this one reports failure through the status code, and puts
187
+ * its reason in an `error` field. Worth reading rather than reporting the
188
+ * status alone: "machine not found" and "unauthorized" are different problems
189
+ * with different fixes.
190
+ */
191
+ private machinesRequest;
192
+ }
193
+ export {};
@@ -1,6 +1,15 @@
1
- import { SpawnOptions, SpawnPtyOptions } from '@codeware/core/utils';
2
- import type { AppOrConfig, Config, CreateAppOptions, CreateAppResponse, DeployAppOptions, DeployResponse, ListAppResponse, ListCertForAllResponse, ListCertForAppResponse, ListSecretForAllResponse, ListSecretForAppResponse, SaveConfigOptions, SetAppSecretsOptions, ShowConfigOptions, ShowConfigResponse, StatusExtendedResponse, StatusResponse, UnsetAppSecretsOptions, VersionResponse } from './types';
3
- export type ExecFlyOptions = SpawnOptions & SpawnPtyOptions;
1
+ import { SpawnOptions, SpawnPtyOptions } from '@codeware/shared/util/misc';
2
+ import type { AppOrConfig, BuildResponse, Config, CreateAppOptions, CreateAppResponse, DeployAppOptions, DeployResponse, ListAppResponse, ListCertForAllResponse, ListCertForAppResponse, ListSecretForAllResponse, ListSecretForAppResponse, SaveConfigOptions, SetAppSecretsOptions, ShowConfigOptions, ShowConfigResponse, StatusExtendedResponse, StatusResponse, UnsetAppSecretsOptions, VersionResponse } from './types';
3
+ export type ExecFlyOptions = SpawnOptions & SpawnPtyOptions & {
4
+ /**
5
+ * How to assemble the returned output string from the spawned process.
6
+ * - `'stdout'` (default): return stdout only — correct for JSON and most text commands
7
+ * - `'stderr'`: return stderr only
8
+ * - `'combined'`: return stdout + stderr — use when the data of interest
9
+ * may appear in either stream (e.g. `fly deploy --build-only`)
10
+ */
11
+ streamStrategy?: 'stdout' | 'stderr' | 'combined';
12
+ };
4
13
  /**
5
14
  * Manages deployments to Fly.io using the `flyctl` CLI tool.
6
15
  */
@@ -109,7 +118,10 @@ export declare class Fly {
109
118
  */
110
119
  config: {
111
120
  /**
112
- * Save an application's remote configuration locally as TOML file.
121
+ * Save an application's remote configuration locally.
122
+ *
123
+ * TOML by default; name the path `.json` or `.yaml`/`.yml` for either of
124
+ * those instead.
113
125
  *
114
126
  * @param options - Options for saving an application's configuration
115
127
  * @throws An error if the configuration cannot be saved
@@ -125,7 +137,12 @@ export declare class Fly {
125
137
  show: (options?: ShowConfigOptions) => Promise<ShowConfigResponse>;
126
138
  };
127
139
  /**
128
- * Deploy an application.
140
+ * Deploy an application, or just build its Docker image without deploying when
141
+ * `buildOnly` is set (equivalent to using `build(options)`).
142
+ *
143
+ * Pre-building is useful to ensure the image can be built successfully and exists
144
+ * before running a deploy that depends on it, and also to get the image reference for use in
145
+ * subsequent operations.
129
146
  *
130
147
  * A valid config file is required but the app doesn't have to exist,
131
148
  * since it gets created if needed.
@@ -135,15 +152,80 @@ export declare class Fly {
135
152
  * 2. Instance app name
136
153
  * 3. App name from the provided config file
137
154
  *
138
- * Existing secrets are preserved.
139
- *
140
- * @param options - Options for deploying an application
141
- * @throws An error if the deployment fails
155
+ * @param options - Deployment or build options
156
+ * @returns Build or deploy response depending on `buildOnly` option
157
+ * @throws An error if the operation fails
142
158
  */
143
- deploy: (options?: DeployAppOptions) => Promise<DeployResponse>;
159
+ deploy: <T extends DeployAppOptions>(options?: T) => Promise<T extends {
160
+ buildOnly: true;
161
+ } ? BuildResponse : DeployResponse>;
162
+ /**
163
+ * Manage machines
164
+ */
165
+ machines: {
166
+ /**
167
+ * Start a machine
168
+ *
169
+ * @param app - The name of the application
170
+ * @param machineId - The machine ID to start
171
+ * @throws An error if the machine cannot be started
172
+ */
173
+ start: (app: string, machineId: string) => Promise<void>;
174
+ /**
175
+ * Stop a machine
176
+ *
177
+ * @param app - The name of the application
178
+ * @param machineId - The machine ID to stop
179
+ * @throws An error if the machine cannot be stopped
180
+ */
181
+ stop: (app: string, machineId: string) => Promise<void>;
182
+ /**
183
+ * Restart a machine by stopping then starting it
184
+ *
185
+ * @param app - The name of the application
186
+ * @param machineId - The machine ID to restart
187
+ * @throws An error if the machine cannot be restarted
188
+ */
189
+ restart: (app: string, machineId: string) => Promise<void>;
190
+ /**
191
+ * Update a machine's per-machine configuration (env vars, etc.).
192
+ *
193
+ * Unlike `restart`, this creates a new machine version from the updated config
194
+ * and forces a cold start — it does NOT resume from a suspended memory snapshot.
195
+ *
196
+ * @param app - The name of the application
197
+ * @param machineId - The machine ID to update
198
+ * @param options - Fields to update; env values set to `''` clear that var
199
+ * @throws An error if the machine cannot be updated
200
+ */
201
+ update: (app: string, machineId: string, options: {
202
+ env?: Record<string, string>;
203
+ }) => Promise<void>;
204
+ };
144
205
  postgres: {
145
206
  detach: (cluster: string, app: string) => Promise<void>;
146
207
  };
208
+ /**
209
+ * Run commands inside a running machine
210
+ */
211
+ ssh: {
212
+ /**
213
+ * Execute a command in a running machine and return its output.
214
+ *
215
+ * Requires a started machine - Fly cannot connect to a stopped or
216
+ * suspended one. Use `machines.start` first when the app may be idle.
217
+ *
218
+ * The output is returned to the caller and not logged unless CLI tracing
219
+ * is enabled, so it can be used to read values that are otherwise
220
+ * write-only, such as secrets injected at deploy time.
221
+ *
222
+ * @param app - The name of the application
223
+ * @param command - The command to run inside the machine
224
+ * @returns The command output
225
+ * @throws An error if there is no started machine or the command fails
226
+ */
227
+ exec: (app: string, command: string) => Promise<string>;
228
+ };
147
229
  /**
148
230
  * Manage application secrets
149
231
  */
@@ -156,6 +238,19 @@ export declare class Fly {
156
238
  * @throws An error if the secrets cannot be set
157
239
  */
158
240
  set: (secrets: Record<string, string>, options?: SetAppSecretsOptions) => Promise<void>;
241
+ /**
242
+ * Apply secrets that were staged with `set({ stage: true })`.
243
+ *
244
+ * Staging first and deploying afterwards lets a set of apps take a new
245
+ * value together, instead of each restarting as its own secret is written.
246
+ *
247
+ * Fly needs a started machine to update, so an app whose machines are all
248
+ * stopped or suspended has to be started before this will do anything.
249
+ *
250
+ * @param app - The name of the application
251
+ * @throws An error if the staged secrets cannot be deployed
252
+ */
253
+ deploy: (app: string) => Promise<void>;
159
254
  /**
160
255
  * List secrets for an application or all secrets when options is 'all'
161
256
  *
@@ -180,6 +275,19 @@ export declare class Fly {
180
275
  * @returns The app status, or `null` if an app could not be found
181
276
  */
182
277
  status: (options?: AppOrConfig) => Promise<StatusResponse | null>;
278
+ /**
279
+ * Build a Docker image for an application and push it to the Fly registry
280
+ * without deploying.
281
+ *
282
+ * The image reference is returned for use in a subsequent `deploy` that depends on it.
283
+ *
284
+ * Shorthand for `deploy({ ...options, buildOnly: true })`.
285
+ *
286
+ * @param options - Build options
287
+ * @returns The app name and image reference for use in a subsequent `deploy`
288
+ * @throws An error if the build fails or the image reference cannot be parsed
289
+ */
290
+ build: (options?: Omit<DeployAppOptions, "buildOnly">) => Promise<BuildResponse>;
183
291
  /**
184
292
  * Get the extended details of an application
185
293
  *
@@ -196,7 +304,7 @@ export declare class Fly {
196
304
  private createApp;
197
305
  /**
198
306
  * @private
199
- * @returns The name of the deployed application
307
+ * @returns The app name and optional image reference (only set when buildOnly is true)
200
308
  * @throws An error if the deployment fails
201
309
  */
202
310
  private deployApp;
@@ -240,6 +348,45 @@ export declare class Fly {
240
348
  * @throws An error if the domain cannot be removed
241
349
  */
242
350
  private removeAppCertificate;
351
+ /**
352
+ * @private
353
+ * Deploy secrets previously staged for an application
354
+ * @throws An error if the staged secrets cannot be deployed
355
+ */
356
+ private deployStagedSecrets;
357
+ /**
358
+ * @private
359
+ * Execute a command inside a running machine
360
+ * @returns The command output
361
+ * @throws An error if the command fails
362
+ */
363
+ private sshExec;
364
+ /**
365
+ * @private
366
+ * Start a machine
367
+ * @throws An error if the machine cannot be started
368
+ */
369
+ private startMachine;
370
+ /**
371
+ * @private
372
+ * Stop a machine
373
+ * @throws An error if the machine cannot be stopped
374
+ */
375
+ private stopMachine;
376
+ /**
377
+ * @private
378
+ * Restart a machine by stopping then starting it
379
+ * @throws An error if the machine cannot be restarted
380
+ */
381
+ private restartMachine;
382
+ /**
383
+ * @private
384
+ * Update a machine's per-machine config (env vars, etc.).
385
+ * Creates a new machine version so the machine cold-starts from the updated config,
386
+ * bypassing any suspended memory snapshot.
387
+ * @throws An error if the machine cannot be updated
388
+ */
389
+ private updateMachine;
243
390
  /**
244
391
  * @private
245
392
  * @returns A list of all applications or `null` if listing applications fails and `nullOnError` is used
@@ -300,6 +447,14 @@ export declare class Fly {
300
447
  * @private
301
448
  * Save remote config to a local file
302
449
  *
450
+ * Two things flyctl expects that a first-time caller would not: the output
451
+ * format is no longer sniffed from the path's extension — `--json`/`--yaml`
452
+ * has to be passed, TOML being what is left over when neither is — and the
453
+ * destination must already exist as a parseable file of that format, or
454
+ * `flyctl` refuses to write to it at all, mistaking "does not exist yet"
455
+ * for "path is wrong". A fresh, empty seed of the right shape satisfies
456
+ * that read without affecting what gets written back over it.
457
+ *
303
458
  * @throws An error if the config cannot be saved
304
459
  */
305
460
  private saveConfig;
@@ -10,12 +10,12 @@ export declare const AppsCreateTransformedResponseSchema: z.ZodEffects<z.ZodObje
10
10
  id: z.ZodString;
11
11
  name: z.ZodString;
12
12
  }, "strip", z.ZodTypeAny, {
13
- name: string;
14
13
  id: string;
15
- }, {
16
14
  name: string;
15
+ }, {
17
16
  id: string;
18
- }>, {
19
17
  name: string;
18
+ }>, {
20
19
  id: string;
20
+ name: string;
21
21
  }, unknown>;
@@ -26,52 +26,52 @@ export declare const AppsListTransformedResponseSchema: z.ZodArray<z.ZodEffects<
26
26
  status: z.ZodString;
27
27
  createdAt: z.ZodString;
28
28
  }, "strip", z.ZodTypeAny, {
29
- status: string;
30
29
  createdAt: string;
31
- }, {
32
30
  status: string;
31
+ }, {
33
32
  createdAt: string;
33
+ status: string;
34
34
  }>>;
35
35
  }, "strip", z.ZodTypeAny, {
36
- name: string;
37
- status: string;
36
+ hostname: string;
38
37
  id: string;
38
+ status: string;
39
+ name: string;
39
40
  deployed: boolean;
40
- hostname: string;
41
41
  organization: {
42
42
  name: string;
43
43
  slug: string;
44
44
  };
45
45
  currentRelease: {
46
- status: string;
47
46
  createdAt: string;
47
+ status: string;
48
48
  } | null;
49
49
  }, {
50
- name: string;
51
- status: string;
50
+ hostname: string;
52
51
  id: string;
52
+ status: string;
53
+ name: string;
53
54
  deployed: boolean;
54
- hostname: string;
55
55
  organization: {
56
56
  name: string;
57
57
  slug: string;
58
58
  };
59
59
  currentRelease: {
60
- status: string;
61
60
  createdAt: string;
61
+ status: string;
62
62
  } | null;
63
63
  }>, {
64
- name: string;
65
- status: string;
64
+ hostname: string;
66
65
  id: string;
66
+ status: string;
67
+ name: string;
67
68
  deployed: boolean;
68
- hostname: string;
69
69
  organization: {
70
70
  name: string;
71
71
  slug: string;
72
72
  };
73
73
  currentRelease: {
74
- status: string;
75
74
  createdAt: string;
75
+ status: string;
76
76
  } | null;
77
77
  }, unknown>, "many">;
@@ -0,0 +1,11 @@
1
+ import { z } from 'zod';
2
+ export declare const BuildResponseSchema: z.ZodObject<{
3
+ appName: z.ZodString;
4
+ imageRef: z.ZodString;
5
+ }, "strip", z.ZodTypeAny, {
6
+ appName: string;
7
+ imageRef: string;
8
+ }, {
9
+ appName: string;
10
+ imageRef: string;
11
+ }>;