unfazed 0.0.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,738 @@
1
+ import { UnfazedClient } from "./client.js";
2
+ import { DEPLOYMENT_NOT_FOUND, UnfazedConflictError, UnfazedDeployError, UnfazedGraphQLError, UnfazedNotFoundError, WORKSPACE_NOT_FOUND, isDuplicateWorkspaceName, isNotFoundSentinel as isNotFound, looksLikeCASConflict, } from "./errors.js";
3
+ import * as ops from "./operations.js";
4
+ import { pollWithBackoff, resolveWaitOptions } from "./wait.js";
5
+ /**
6
+ * Layer 2 — the agent workflow layer.
7
+ *
8
+ * Wraps the chains an agent actually performs (create → write → deploy → wait
9
+ * → read logs → roll back) so a code-mode script does in one call what would
10
+ * otherwise be many round trips through a model's context. Everything here is
11
+ * built on {@link UnfazedClient}, exposed as `.client` for anything not
12
+ * wrapped.
13
+ *
14
+ * ```ts
15
+ * const unfazed = new Unfazed(); // reads UNFZ_API_TOKEN
16
+ * const ws = await unfazed.createWorkspace("hello");
17
+ * await unfazed.writeFiles(ws.id, { "server.ts": code });
18
+ * const app = await unfazed.deployService({ workspaceId: ws.id, alias: "hello", wait: true });
19
+ * console.log(app.url);
20
+ * ```
21
+ */
22
+ export class Unfazed {
23
+ /** The underlying typed GraphQL client. Use it for un-wrapped operations. */
24
+ client;
25
+ constructor(options = {}) {
26
+ const { client, ...clientOptions } = options;
27
+ this.client = client ?? new UnfazedClient(clientOptions);
28
+ }
29
+ /* ---------------------------------------------------------------- identity */
30
+ /** Who this token authenticates as, plus usage and resource limits. */
31
+ async whoami(options) {
32
+ const data = await this.client.query(ops.WhoamiDocument, {}, options);
33
+ return data.whoami;
34
+ }
35
+ /* -------------------------------------------------------------- workspaces */
36
+ /** Creates a source workspace — the container for files, env and deployments. */
37
+ async createWorkspace(name, options) {
38
+ const data = await this.client.mutate(ops.CreateWorkspaceDocument, { name }, options);
39
+ return data.createWorkspace.workspace;
40
+ }
41
+ /** Workspaces visible to this token. */
42
+ async listWorkspaces(options) {
43
+ const data = await this.client.query(ops.ListWorkspacesDocument, {}, options);
44
+ return data.workspaces;
45
+ }
46
+ /**
47
+ * Deletes a workspace and everything anchored to it — deployments, env, and
48
+ * a BOX's persistent data disk. Not recoverable.
49
+ *
50
+ * **The cascade is opt-out, not opt-in.** The server refuses to delete a
51
+ * workspace that has ANY deployment history — including FAILED records, and
52
+ * including deployments whose alias was long since taken over by something
53
+ * else — unless the mutation carries `withDeployments`. Since almost every
54
+ * workspace an agent creates gets deployed at least once, defaulting to
55
+ * `false` would make this method fail on nearly every real workspace, so it
56
+ * defaults to **`true`**: the behaviour this docstring has always promised.
57
+ *
58
+ * Pass `withDeployments: false` for the strict variant, which refuses rather
59
+ * than cascading and is the safer choice when you are deleting a workspace
60
+ * you did not create:
61
+ *
62
+ * ```ts
63
+ * await unfazed.deleteWorkspace(ws.id); // cascade
64
+ * await unfazed.deleteWorkspace(ws.id, { withDeployments: false }); // refuse if deployed
65
+ * await unfazed.deleteWorkspace(id, { ignoreNotFound: true }); // false, not a throw
66
+ * ```
67
+ *
68
+ * With `ignoreNotFound` a workspace that is absent (or belongs to someone
69
+ * else — the server returns one indistinguishable sentinel for both, on
70
+ * purpose) resolves to `false` instead of throwing, which makes teardown in
71
+ * a `finally` block idempotent.
72
+ */
73
+ async deleteWorkspace(workspaceId, options = {}) {
74
+ const withDeployments = options.withDeployments ?? true;
75
+ try {
76
+ const data = await this.client.mutate(ops.DeleteWorkspaceDocument, { workspaceID: workspaceId, withDeployments }, options);
77
+ return data.deleteWorkspace.ok;
78
+ }
79
+ catch (e) {
80
+ if (options.ignoreNotFound && isNotFound(e, WORKSPACE_NOT_FOUND))
81
+ return false;
82
+ throw e;
83
+ }
84
+ }
85
+ /**
86
+ * Returns the workspace named `name`, creating it only if it does not exist.
87
+ *
88
+ * Workspace names are unique per owner, case-insensitively — a second
89
+ * `createWorkspace("Hello")` after a `createWorkspace("hello")` is an error,
90
+ * not a second workspace. That makes the bare create a poor fit for any
91
+ * script that might run twice; this is the re-runnable form.
92
+ *
93
+ * ```ts
94
+ * const ws = await unfazed.ensureWorkspace("greeter"); // safe to re-run
95
+ * ```
96
+ *
97
+ * Costs one list, plus one create only on a miss. The create is still
98
+ * guarded: if a concurrent caller wins the race, the duplicate-name error is
99
+ * caught and the now-existing workspace is returned instead of thrown.
100
+ */
101
+ async ensureWorkspace(name, options) {
102
+ const existing = await this.#findWorkspaceByName(name, options);
103
+ if (existing)
104
+ return existing;
105
+ try {
106
+ return await this.createWorkspace(name, options);
107
+ }
108
+ catch (e) {
109
+ // Lost a create/create race, or the server's case folding is stricter
110
+ // than ours. Either way the workspace exists now — re-read rather than
111
+ // failing a script whose intent was "make sure this exists".
112
+ if (!isDuplicateWorkspaceName(e))
113
+ throw e;
114
+ const raced = await this.#findWorkspaceByName(name, options);
115
+ if (raced)
116
+ return raced;
117
+ // The name is taken by something we cannot see. Surface the real error.
118
+ throw e;
119
+ }
120
+ }
121
+ /* ------------------------------------------------------------------- files */
122
+ /**
123
+ * Writes many files in as few requests as possible.
124
+ *
125
+ * The API is one-file-per-mutation, so writing a 12-file app naively costs 12
126
+ * round trips. This batches them into a single GraphQL document with one
127
+ * ALIASED root field per file (`f0: writeWorkspaceTextFile(...)`,
128
+ * `f1: ...`), which the server resolves in one request.
129
+ *
130
+ * ```ts
131
+ * await unfazed.writeFiles(ws.id, {
132
+ * "server.ts": serverCode,
133
+ * "unfazed.json": JSON.stringify({ entry: "server.ts" }),
134
+ * "public/logo.png": { bytes: pngBytes },
135
+ * });
136
+ * ```
137
+ *
138
+ * Batches are NOT atomic: GraphQL resolves each aliased field independently,
139
+ * so a partial failure leaves earlier writes committed. The thrown
140
+ * {@link UnfazedGraphQLError} carries `data` with whichever aliases
141
+ * succeeded, and `error.path` identifies the ones that did not.
142
+ */
143
+ async writeFiles(workspaceId, files, options = {}) {
144
+ const entries = Object.entries(files).map(([path, content]) => normalizeFile(path, content));
145
+ if (entries.length === 0)
146
+ return [];
147
+ const batchSize = options.batchSize ?? 20;
148
+ const maxBatchBytes = options.maxBatchBytes ?? 4 * 1024 * 1024;
149
+ const written = [];
150
+ for (const batch of chunkFiles(entries, batchSize, maxBatchBytes)) {
151
+ written.push(...(await this.#writeBatch(workspaceId, batch, options.signal)));
152
+ }
153
+ return written;
154
+ }
155
+ /** Writes one text file. Prefer {@link writeFiles} for more than one. */
156
+ async writeFile(workspaceId, path, text, options) {
157
+ const data = await this.client.mutate(ops.WriteTextFileDocument, { workspaceID: workspaceId, path, text }, options);
158
+ return data.writeWorkspaceTextFile.file;
159
+ }
160
+ /** Writes one binary file. Accepts raw bytes or a base64 string. */
161
+ async writeBinaryFile(workspaceId, path, content, options) {
162
+ const contentBase64 = "base64" in content ? content.base64 : toBase64(content);
163
+ const data = await this.client.mutate(ops.WriteBase64FileDocument, { workspaceID: workspaceId, path, contentBase64 }, options);
164
+ return data.writeWorkspaceBase64File.file;
165
+ }
166
+ /** Lists workspace files (paginated). */
167
+ async listFiles(workspaceId, input = {}, options) {
168
+ const data = await this.client.query(ops.ListFilesDocument, { input: { workspaceID: workspaceId, ...input } }, options);
169
+ return data.workspaceFilesPage;
170
+ }
171
+ /** Reads a text file, optionally a byte range of it. Null when absent. */
172
+ async readFile(workspaceId, path, input = {}, options) {
173
+ const data = await this.client.query(ops.ReadFileDocument, { input: { workspaceID: workspaceId, path, ...input } }, options);
174
+ return data.readWorkspaceFile;
175
+ }
176
+ /**
177
+ * Deletes a workspace file.
178
+ *
179
+ * Returns `false` when there was nothing to delete — an absent path is not
180
+ * an error. See the `ok: false` convention on {@link deleteEnv}.
181
+ */
182
+ async deleteFile(workspaceId, path, options) {
183
+ const data = await this.client.mutate(ops.DeleteFileDocument, { workspaceID: workspaceId, path }, options);
184
+ return data.deleteWorkspaceFile.ok;
185
+ }
186
+ /* ----------------------------------------------------------------- deploys
187
+ *
188
+ * Every deploy method here MINTS A NEW RELEASE on every call. There is no
189
+ * content dedupe: deploying byte-identical files twice produces two distinct
190
+ * releases with two ids, both real, both counting against retention (which
191
+ * keeps only the most recent few per alias and prunes the rest). Deploying
192
+ * in a retry loop is therefore not free — it churns the release history and
193
+ * can push a release you still wanted to roll back to out of retention.
194
+ * Check {@link getDeployment} or {@link listReleases} before redeploying if
195
+ * you only meant to converge.
196
+ */
197
+ /**
198
+ * Deploys the workspace as a SERVICE (an HTTP server).
199
+ *
200
+ * With `wait: true` this resolves only once the build, VM boot and health
201
+ * probe have all passed.
202
+ *
203
+ * Passing the same `alias` again redeploys that alias — a new release that
204
+ * takes over the alias when it goes READY. Omitting `alias` lets the server
205
+ * generate one, which means a different app on every call.
206
+ */
207
+ deployService(options) {
208
+ const { workspaceId, alias, runtime, serviceMode, healthPath, cronSchedule, cronPath } = options;
209
+ return this.#deploy({
210
+ workspaceID: workspaceId,
211
+ kind: "SERVICE",
212
+ ...(alias === undefined ? {} : { alias }),
213
+ ...(runtime === undefined ? {} : { runtime }),
214
+ ...(serviceMode === undefined ? {} : { serviceMode }),
215
+ ...(healthPath === undefined ? {} : { healthPath }),
216
+ ...(cronSchedule === undefined ? {} : { cronSchedule }),
217
+ ...(cronPath === undefined ? {} : { cronPath }),
218
+ }, options);
219
+ }
220
+ /** Deploys the workspace as a STATIC site. */
221
+ deployStatic(options) {
222
+ const { workspaceId, alias, spaMode } = options;
223
+ return this.#deploy({
224
+ workspaceID: workspaceId,
225
+ kind: "STATIC",
226
+ ...(alias === undefined ? {} : { alias }),
227
+ ...(spaMode === undefined ? {} : { spaMode }),
228
+ }, options);
229
+ }
230
+ /**
231
+ * Deploys a BOX: a persistent always-on Linux VM with a data disk that
232
+ * survives stops and redeploys. A dev machine, not an HTTP service. The
233
+ * result's `sshCommand` is how you get in.
234
+ *
235
+ * ⚠️ **Omitting `alias` creates a NEW BOX every single call.** There is no
236
+ * "the workspace's box" to update: with no alias the server generates a
237
+ * fresh random one, so a script run twice leaves you with two box records,
238
+ * not one redeployed box.
239
+ *
240
+ * The data disk, meanwhile, is keyed by WORKSPACE — one disk, shared by
241
+ * every box in the workspace, and it is the box's real identity. Since only
242
+ * one VM can hold that disk read-write, the second box cannot even start
243
+ * while the first is running (`box data disk for workspace ... is attached
244
+ * to VM ...; stop it first`). The result is a pile of dead box records
245
+ * fighting over one disk.
246
+ *
247
+ * **Always pass an explicit `alias` in anything re-runnable.** Redeploying
248
+ * the same alias is the in-place update you actually want.
249
+ *
250
+ * ```ts
251
+ * await unfazed.deployBox({ workspaceId: ws.id, alias: "dev" }); // re-runnable
252
+ * ```
253
+ */
254
+ deployBox(options) {
255
+ const { workspaceId, alias, resources } = options;
256
+ return this.#deploy({
257
+ workspaceID: workspaceId,
258
+ kind: "BOX",
259
+ ...(alias === undefined ? {} : { alias }),
260
+ ...(resources === undefined ? {} : { boxResources: resources }),
261
+ }, options);
262
+ }
263
+ /** Escape hatch: deploy with a raw CreateDeploymentInput. */
264
+ deploy(input, options = {}) {
265
+ return this.#deploy(input, options);
266
+ }
267
+ async #deploy(input, options) {
268
+ const requestOptions = options.signal ? { signal: options.signal } : {};
269
+ const data = await this.client.mutate(ops.CreateDeploymentDocument, { input }, requestOptions);
270
+ const deployment = data.createDeployment.deployment;
271
+ if (!options.wait)
272
+ return deployment;
273
+ return this.waitForDeployment(deployment.id, {
274
+ ...options.waitOptions,
275
+ ...(options.signal ? { signal: options.signal } : {}),
276
+ });
277
+ }
278
+ /**
279
+ * Polls a deployment until it is READY, throwing on FAILED or timeout.
280
+ *
281
+ * BUILDING is the only non-terminal status; READY and FAILED are terminal.
282
+ * The poll query selects six fields rather than the full deployment, because
283
+ * this runs every few seconds for potentially minutes — then the READY
284
+ * deployment is re-read in full so callers get the same shape `deployService`
285
+ * returns without `wait`.
286
+ */
287
+ async waitForDeployment(deploymentId, waitOptions = {}) {
288
+ const resolved = resolveWaitOptions(waitOptions);
289
+ const requestOptions = resolved.signal ? { signal: resolved.signal } : {};
290
+ let last = null;
291
+ await pollWithBackoff(async () => {
292
+ const data = await this.client.query(ops.PollDeploymentDocument, { id: deploymentId }, requestOptions);
293
+ const d = data.deployment;
294
+ if (!d) {
295
+ throw new UnfazedNotFoundError(`unfazed: deployment ${deploymentId} not found`);
296
+ }
297
+ last = d;
298
+ if (d.status === "READY")
299
+ return { done: true, value: true };
300
+ if (d.status === "FAILED") {
301
+ throw new UnfazedDeployError("FAILED", deploymentId, d, `unfazed: deployment ${deploymentId} FAILED${d.error ? `: ${d.error}` : ""}`);
302
+ }
303
+ return { done: false };
304
+ }, resolved, () => new UnfazedDeployError("TIMEOUT", deploymentId, last, `unfazed: deployment ${deploymentId} still ${last?.status ?? "BUILDING"} after ${resolved.timeoutMs}ms`));
305
+ const full = await this.getDeployment(deploymentId, requestOptions);
306
+ if (!full)
307
+ throw new UnfazedNotFoundError(`unfazed: deployment ${deploymentId} not found`);
308
+ return full;
309
+ }
310
+ /** Reads one deployment by id. Null when absent. */
311
+ async getDeployment(deploymentId, options) {
312
+ const data = await this.client.query(ops.GetDeploymentDocument, { id: deploymentId }, options);
313
+ return data.deployment;
314
+ }
315
+ /** Reads the deployment currently serving an alias. Null when absent. */
316
+ async getDeploymentByAlias(alias, options) {
317
+ const data = await this.client.query(ops.GetDeploymentByAliasDocument, { alias }, options);
318
+ return data.deploymentByAlias;
319
+ }
320
+ /** Lists deployments (paginated, filterable by kind/alias/workspace). */
321
+ async listDeployments(input = {}, options) {
322
+ const data = await this.client.query(ops.ListDeploymentsDocument, { input }, options);
323
+ return data.deploymentsPage;
324
+ }
325
+ /* ------------------------------------------------------- runtime & logging */
326
+ /** Live VM status: health, in-flight requests, restarts, RAM ceiling. */
327
+ async getStatus(deploymentId, options) {
328
+ const data = await this.client.query(ops.ServiceStatusDocument, { deploymentID: deploymentId }, options);
329
+ return data.serviceStatus;
330
+ }
331
+ /**
332
+ * Tail of the service's stdout/stderr.
333
+ *
334
+ * The point of doing this from a script rather than through tool calls: you
335
+ * can filter locally. `(await unfazed.getLogs(id)).stderr.split("\n")
336
+ * .filter(l => l.includes("ERROR"))` costs a model zero context, where the
337
+ * same tail through an MCP tool spends all of it.
338
+ */
339
+ async getLogs(deploymentId, input = {}, options) {
340
+ const data = await this.client.query(ops.ServiceLogsDocument, { deploymentID: deploymentId, tailBytes: input.tailBytes ?? null }, options);
341
+ return data.serviceLogs;
342
+ }
343
+ /** Deployment lifecycle events — build, boot, probe, cron, restarts. */
344
+ async getEvents(deploymentId, limit, options) {
345
+ const data = await this.client.query(ops.DeploymentEventsDocument, { deploymentID: deploymentId, limit: limit ?? null }, options);
346
+ return data.deploymentEvents;
347
+ }
348
+ /** Restarts a service's VM. */
349
+ async restartService(deploymentId, options) {
350
+ const data = await this.client.mutate(ops.RestartServiceDocument, { deploymentID: deploymentId }, options);
351
+ return data.restartService;
352
+ }
353
+ /** Stops a service's VM. An on-demand service cold-starts again on request. */
354
+ async stopService(deploymentId, options) {
355
+ const data = await this.client.mutate(ops.StopServiceDocument, { deploymentID: deploymentId }, options);
356
+ return data.stopService;
357
+ }
358
+ /**
359
+ * Deletes a deployment: stops its VM, releases its alias, drops its release.
360
+ *
361
+ * With `ignoreNotFound` a deployment that is absent — or belongs to another
362
+ * tenant, which the server reports identically so ids cannot be probed —
363
+ * resolves to `false` instead of throwing, making cleanup loops idempotent.
364
+ */
365
+ async deleteDeployment(deploymentId, options = {}) {
366
+ try {
367
+ const data = await this.client.mutate(ops.DeleteDeploymentDocument, { deploymentID: deploymentId }, options);
368
+ return data.deleteDeployment.ok;
369
+ }
370
+ catch (e) {
371
+ if (options.ignoreNotFound && isNotFound(e, DEPLOYMENT_NOT_FOUND))
372
+ return false;
373
+ throw e;
374
+ }
375
+ }
376
+ /* ------------------------------------------------------------ env & secrets
377
+ *
378
+ * Workspace values are SERVICE defaults for every app in the source; app
379
+ * values override them for one alias. Both are SNAPSHOTTED into a release at
380
+ * deploy time — changing either does not affect a running app until you
381
+ * redeploy that alias. Old releases are immutable, and STATIC gets no env.
382
+ */
383
+ /**
384
+ * Sets a workspace-default env var. Redeploy the alias to apply it.
385
+ *
386
+ * A name is either plain or secret, never both: this DELETES a workspace
387
+ * secret of the same name. {@link setSecret} displaces a plain var the same
388
+ * way. Last write wins, and the kind flips silently — so re-running a setup
389
+ * script that calls `setSecret("API_KEY", ...)` after one that called
390
+ * `setEnv("API_KEY", ...)` quietly converts it, and vice versa.
391
+ */
392
+ async setEnv(workspaceId, name, value, options) {
393
+ const data = await this.client.mutate(ops.SetWorkspaceEnvDocument, { workspaceID: workspaceId, name, value }, options);
394
+ return data.setWorkspaceEnv.env;
395
+ }
396
+ /**
397
+ * Sets a workspace-default secret. The value is never readable again.
398
+ *
399
+ * Mutually exclusive with {@link setEnv}: this DELETES a plain workspace var
400
+ * of the same name. See {@link setEnv} for the displacement rule.
401
+ */
402
+ async setSecret(workspaceId, name, value, options) {
403
+ const data = await this.client.mutate(ops.SetWorkspaceSecretDocument, { workspaceID: workspaceId, name, value }, options);
404
+ return data.setWorkspaceSecret.env;
405
+ }
406
+ /**
407
+ * Sets many workspace env vars in one request, via aliased mutations —
408
+ * the same batching trick as {@link writeFiles}.
409
+ *
410
+ * Pass `{ secret: true }` to route them all to `setWorkspaceSecret`.
411
+ *
412
+ * It inherits {@link writeFiles}' failure semantics too: the batch is NOT
413
+ * atomic. GraphQL resolves each aliased field independently, so a rejected
414
+ * name (over the limit, malformed, whatever) leaves the vars before it
415
+ * already committed. The thrown {@link UnfazedGraphQLError} carries `data`
416
+ * with the aliases that succeeded and `errors[].path` naming those that did
417
+ * not — do not assume "it threw" means "nothing was written".
418
+ *
419
+ * Each name still displaces its opposite kind, exactly as {@link setEnv} and
420
+ * {@link setSecret} do one at a time.
421
+ */
422
+ async setEnvMany(workspaceId, vars, options = {}) {
423
+ const entries = Object.entries(vars);
424
+ if (entries.length === 0)
425
+ return [];
426
+ const field = options.secret ? "setWorkspaceSecret" : "setWorkspaceEnv";
427
+ const varDefs = ["$workspaceID: ID!"];
428
+ const fields = [];
429
+ const variables = { workspaceID: workspaceId };
430
+ entries.forEach(([name, value], i) => {
431
+ varDefs.push(`$n${i}: String!`, `$v${i}: String!`);
432
+ variables[`n${i}`] = name;
433
+ variables[`v${i}`] = value;
434
+ fields.push(` e${i}: ${field}(input: { workspaceID: $workspaceID, name: $n${i}, value: $v${i} }) { env { ${ENV_SELECTION} } }`);
435
+ });
436
+ const document = `mutation SdkSetEnvBatch(${varDefs.join(", ")}) {\n${fields.join("\n")}\n}`;
437
+ const data = await this.client.mutate(document, variables, options.signal ? { signal: options.signal } : {});
438
+ return entries.map((_, i) => data[`e${i}`].env);
439
+ }
440
+ /**
441
+ * Deletes a workspace-default env var (plain or secret).
442
+ *
443
+ * **The `ok: false` convention.** A `false` here does NOT mean failure — it
444
+ * means "nothing to do, the world is already in the state you asked for".
445
+ * The var did not exist. Every `ok`-returning mutation in this SDK follows
446
+ * the rule ({@link deleteFile}, {@link inheritAppEnv}, {@link removeAppEnv}),
447
+ * so the idempotent-cleanup pattern is simply to ignore the boolean; a real
448
+ * failure throws.
449
+ */
450
+ async deleteEnv(workspaceId, name, options) {
451
+ const data = await this.client.mutate(ops.DeleteWorkspaceEnvDocument, { workspaceID: workspaceId, name }, options);
452
+ return data.deleteWorkspaceEnv.ok;
453
+ }
454
+ /** Workspace-default env vars. Secret values are redacted. */
455
+ async listEnv(workspaceId, options) {
456
+ const data = await this.client.query(ops.ListWorkspaceEnvDocument, { workspaceID: workspaceId }, options);
457
+ return data.workspaceEnv;
458
+ }
459
+ /**
460
+ * Sets an env var for ONE alias, overriding the workspace default.
461
+ *
462
+ * Displaces both of the other states this name could be in for the app: it
463
+ * deletes an app SECRET of the same name, and it CLEARS a REMOVE mask left
464
+ * by {@link removeAppEnv}. So setting a value is also the way to un-block a
465
+ * masked name, and a name is only ever one of plain / secret / masked.
466
+ */
467
+ async setAppEnv(workspaceId, alias, name, value, options) {
468
+ const data = await this.client.mutate(ops.SetAppEnvDocument, { workspaceID: workspaceId, alias, name, value }, options);
469
+ return data.setAppEnv.env;
470
+ }
471
+ /**
472
+ * Sets a secret for ONE alias, overriding the workspace default.
473
+ *
474
+ * Like {@link setAppEnv}, this deletes a plain app var of the same name and
475
+ * clears a REMOVE mask for it.
476
+ */
477
+ async setAppSecret(workspaceId, alias, name, value, options) {
478
+ const data = await this.client.mutate(ops.SetAppSecretDocument, { workspaceID: workspaceId, alias, name, value }, options);
479
+ return data.setAppSecret.env;
480
+ }
481
+ /**
482
+ * REMOVE: blocks this name for the app entirely — the app override, the
483
+ * workspace default, and integration enrichment. Not the same as deleting an
484
+ * override; use {@link inheritAppEnv} for that.
485
+ *
486
+ * This WRITES A MASK, and the mask is a real, persistent row. Two things
487
+ * follow that surprise people:
488
+ *
489
+ * - It is written even when nothing was inherited. Masking a name that no
490
+ * workspace default and no integration ever provided is not a no-op; it
491
+ * leaves a tombstone that keeps blocking the name if a default appears
492
+ * later. Clear it with {@link inheritAppEnv}.
493
+ * - It COSTS A SLOT. A workspace gets 128 env entries total — that budget
494
+ * is shared across the workspace defaults AND every app scope combined,
495
+ * not 128 per scope — and masks count toward it just like values do.
496
+ * Masking names in a loop can exhaust the workspace's env budget.
497
+ *
498
+ * Returns `false` when the exact mask was already present (a second call for
499
+ * the same name), per the {@link deleteEnv} `ok: false` convention. It
500
+ * returns `true` when it had something to change — including converting an
501
+ * existing override into a mask.
502
+ */
503
+ async removeAppEnv(workspaceId, alias, name, options) {
504
+ const data = await this.client.mutate(ops.RemoveAppEnvDocument, { workspaceID: workspaceId, alias, name }, options);
505
+ return data.removeAppEnv.ok;
506
+ }
507
+ /**
508
+ * INHERIT: clears the app override/mask so workspace and integration values
509
+ * apply again. This is the undo for both {@link setAppEnv} and
510
+ * {@link removeAppEnv}.
511
+ *
512
+ * Returns `false` when there was no override and no mask to clear — nothing
513
+ * to do, not a failure. See {@link deleteEnv}.
514
+ */
515
+ async inheritAppEnv(workspaceId, alias, name, options) {
516
+ const data = await this.client.mutate(ops.InheritAppEnvDocument, { workspaceID: workspaceId, alias, name }, options);
517
+ return data.inheritAppEnv.ok;
518
+ }
519
+ /** The effective env view for one alias: overrides, inherited and masked. */
520
+ async listAppEnv(workspaceId, alias, options) {
521
+ const data = await this.client.query(ops.ListAppEnvDocument, { workspaceID: workspaceId, alias }, options);
522
+ return data.appEnv;
523
+ }
524
+ /* -------------------------------------------------- releases & rollback */
525
+ /**
526
+ * An alias's terminal release history, newest first.
527
+ *
528
+ * Exactly one entry has `aliasHeld: true` — the live release. FAILED entries
529
+ * appear on purpose (they are rejected promotions, so a kept-live previous
530
+ * release is never mistaken for a silent fallback) and cannot be rolled back
531
+ * to. Retention keeps only the most recent few per alias, default 5.
532
+ */
533
+ async listReleases(alias, options) {
534
+ const data = await this.client.query(ops.ListReleasesDocument, { alias }, options);
535
+ return data.deploymentReleases;
536
+ }
537
+ /**
538
+ * Rolls an alias back to a prior release, handling the whole compare-and-swap
539
+ * protocol in one call.
540
+ *
541
+ * The server requires the caller to prove it observed the current state: you
542
+ * must pass the live release's id AND its opaque `aliasRevision`, and the
543
+ * swap fails if either changed since you listed — including same-id ABA. So
544
+ * this method does the full dance: list releases, find the `aliasHeld` entry,
545
+ * pick the target, and submit both guard values.
546
+ *
547
+ * On a rejected guard it re-lists and retries (default once). The TARGET is
548
+ * pinned across retries while the guard is refreshed, so a concurrent deploy
549
+ * can never redirect the rollback to a different release than the one chosen.
550
+ *
551
+ * ```ts
552
+ * await unfazed.rollback({ alias: "my-app" }); // undo last deploy
553
+ * await unfazed.rollback({ alias: "my-app", to: relId }); // to a specific release
554
+ * await unfazed.rollback({ alias: "my-app", to: relId, expectedCurrentId: liveId });
555
+ * ```
556
+ *
557
+ * ⚠️ **A bare `rollback({ alias })` is a TOGGLE, not an idempotent step.**
558
+ * It means "restore the most recent READY release that is not the live one",
559
+ * which is a different release each time the alias moves. Run the same
560
+ * script twice and the second run rolls back the rollback — A → B → A → B,
561
+ * forever, with each hop a real alias swap. Nothing errors, because every
562
+ * individual call did exactly what it was asked.
563
+ *
564
+ * In anything re-runnable — a retry loop, a CI job, an agent that might redo
565
+ * a step — pin the outcome instead:
566
+ *
567
+ * - `to:` names the release you want live, so re-running is a no-op-ish
568
+ * convergence rather than a flip (a second run then reports the target
569
+ * already holds the alias instead of moving it);
570
+ * - `expectedCurrentId:` states what you expect to be live now, so a second
571
+ * run fails loudly instead of silently undoing the first.
572
+ */
573
+ async rollback(options) {
574
+ const { alias, signal, expectedCurrentId } = options;
575
+ // A caller-supplied precondition and the CAS retry are mutually exclusive:
576
+ // retrying re-guards against whatever holds the alias NOW, which is the
577
+ // one thing `expectedCurrentId` exists to refuse.
578
+ const retries = expectedCurrentId === undefined ? (options.retries ?? 1) : 0;
579
+ const requestOptions = signal ? { signal } : {};
580
+ let targetId = options.to;
581
+ for (let attempt = 0;; attempt++) {
582
+ const releases = await this.listReleases(alias, requestOptions);
583
+ if (releases.length === 0) {
584
+ throw new UnfazedNotFoundError(`unfazed: alias "${alias}" has no release history`);
585
+ }
586
+ const current = releases.find((r) => r.aliasHeld);
587
+ if (!current) {
588
+ throw new UnfazedNotFoundError(`unfazed: alias "${alias}" has no current release holding the alias`);
589
+ }
590
+ // The caller's precondition, checked before anything is sent. Failing
591
+ // here rather than at the server keeps a violated expectation from
592
+ // costing an alias swap, and reports the holder we actually observed.
593
+ if (expectedCurrentId !== undefined && current.id !== expectedCurrentId) {
594
+ throw new UnfazedConflictError(`unfazed: alias "${alias}" is held by ${current.id}, not the expected ` +
595
+ `${expectedCurrentId} — it moved since you read it; re-read and decide again`, []);
596
+ }
597
+ // Pin the target on the first pass so a retry refreshes only the guard.
598
+ if (targetId === undefined) {
599
+ const previous = releases.find((r) => r.id !== current.id && r.status === "READY");
600
+ if (!previous) {
601
+ throw new UnfazedNotFoundError(`unfazed: alias "${alias}" has no prior READY release to roll back to ` +
602
+ `(history: ${releases.map((r) => `${r.id}:${r.status}`).join(", ")})`);
603
+ }
604
+ targetId = previous.id;
605
+ }
606
+ const target = releases.find((r) => r.id === targetId);
607
+ if (!target) {
608
+ throw new UnfazedNotFoundError(`unfazed: release ${targetId} is not in alias "${alias}"'s history ` +
609
+ `(it may have been pruned; retention keeps only the most recent few)`);
610
+ }
611
+ if (target.id === current.id) {
612
+ throw new UnfazedConflictError(`unfazed: release ${targetId} already holds alias "${alias}"`, []);
613
+ }
614
+ if (target.status !== "READY") {
615
+ throw new UnfazedConflictError(`unfazed: release ${targetId} is ${target.status}, only READY releases can be restored`, []);
616
+ }
617
+ try {
618
+ const data = await this.client.mutate(ops.RollbackDocument, {
619
+ deploymentID: target.id,
620
+ expectedCurrentDeploymentID: current.id,
621
+ expectedCurrentAliasRevision: current.aliasRevision,
622
+ }, requestOptions);
623
+ return data.rollbackDeployment;
624
+ }
625
+ catch (e) {
626
+ const retryable = e instanceof UnfazedGraphQLError && looksLikeCASConflict(e.errors) && attempt < retries;
627
+ if (!retryable) {
628
+ if (e instanceof UnfazedGraphQLError && looksLikeCASConflict(e.errors)) {
629
+ throw new UnfazedConflictError(`unfazed: rollback of "${alias}" lost the compare-and-swap after ${attempt + 1} attempt(s) — the alias is being deployed concurrently. ${e.message}`, e.errors);
630
+ }
631
+ throw e;
632
+ }
633
+ // Loop: re-list, rebuild the guard, keep the same target.
634
+ }
635
+ }
636
+ }
637
+ /* -------------------------------------------------------------- internals */
638
+ /**
639
+ * Finds a visible workspace by name, the way the server compares names.
640
+ *
641
+ * The server rejects duplicates with Go's `strings.EqualFold`, so matching
642
+ * must be case-insensitive here too or `ensureWorkspace` would try to create
643
+ * a "new" workspace the server considers a duplicate. An exact-case hit wins
644
+ * over a folded one, which only matters if a name ever slipped past the
645
+ * uniqueness check.
646
+ */
647
+ async #findWorkspaceByName(name, options) {
648
+ const workspaces = await this.listWorkspaces(options);
649
+ const folded = name.toLowerCase();
650
+ return (workspaces.find((w) => w.name === name) ??
651
+ workspaces.find((w) => w.name.toLowerCase() === folded));
652
+ }
653
+ async #writeBatch(workspaceId, batch, signal) {
654
+ const varDefs = ["$workspaceID: ID!"];
655
+ const fields = [];
656
+ const variables = { workspaceID: workspaceId };
657
+ batch.forEach((file, i) => {
658
+ variables[`p${i}`] = file.path;
659
+ variables[`c${i}`] = file.content;
660
+ varDefs.push(`$p${i}: String!`, `$c${i}: String!`);
661
+ fields.push(file.kind === "text"
662
+ ? ` f${i}: writeWorkspaceTextFile(input: { workspaceID: $workspaceID, path: $p${i}, text: $c${i} }) { file { ${FILE_SELECTION} } }`
663
+ : ` f${i}: writeWorkspaceBase64File(input: { workspaceID: $workspaceID, path: $p${i}, contentBase64: $c${i} }) { file { ${FILE_SELECTION} } }`);
664
+ });
665
+ // Built at runtime rather than codegen'd: the field COUNT varies per call,
666
+ // so no static document can express it. The field shapes are still fixed
667
+ // and typed below, and each individual mutation is codegen-validated by its
668
+ // single-file twin in operations.ts.
669
+ const document = `mutation SdkWriteFilesBatch(${varDefs.join(", ")}) {\n${fields.join("\n")}\n}`;
670
+ const data = await this.client.mutate(document, variables, signal ? { signal } : {});
671
+ return batch.map((_, i) => data[`f${i}`].file);
672
+ }
673
+ }
674
+ const FILE_SELECTION = "path sizeBytes size sha256 updatedAt";
675
+ const ENV_SELECTION = "name value secret alias inherited masked updatedAt";
676
+ function normalizeFile(path, content) {
677
+ if (typeof content === "string")
678
+ return { path, kind: "text", content };
679
+ if ("text" in content)
680
+ return { path, kind: "text", content: content.text };
681
+ if ("base64" in content)
682
+ return { path, kind: "base64", content: content.base64 };
683
+ return { path, kind: "base64", content: toBase64(content.bytes) };
684
+ }
685
+ function toBase64(input) {
686
+ const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
687
+ // Node/Bun have Buffer; browsers and workers do not.
688
+ const maybeBuffer = globalThis
689
+ .Buffer;
690
+ if (maybeBuffer)
691
+ return maybeBuffer.from(bytes).toString("base64");
692
+ let binary = "";
693
+ const CHUNK = 0x8000; // avoid blowing the argument limit on large files
694
+ for (let i = 0; i < bytes.length; i += CHUNK) {
695
+ binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
696
+ }
697
+ return btoa(binary);
698
+ }
699
+ const utf8 = new TextEncoder();
700
+ /**
701
+ * UTF-8 byte length, which is what the wire actually costs.
702
+ *
703
+ * `String.length` counts UTF-16 code units and undercounts by up to 3x on
704
+ * non-ASCII text — a CJK or emoji-heavy payload would sail past a budget it
705
+ * had already blown.
706
+ */
707
+ function utf8Bytes(s) {
708
+ return utf8.encode(s).length;
709
+ }
710
+ /**
711
+ * Splits files into request-sized batches.
712
+ *
713
+ * Closes a batch on whichever limit trips first — count or bytes — but always
714
+ * emits at least one file per batch, so a single file larger than
715
+ * `maxBatchBytes` still gets sent (and fails loudly at the server's limit)
716
+ * rather than silently vanishing into an empty batch.
717
+ */
718
+ function chunkFiles(files, batchSize, maxBatchBytes) {
719
+ const batches = [];
720
+ let current = [];
721
+ let bytes = 0;
722
+ for (const file of files) {
723
+ // Measured once per file, so the encode cost is linear in the payload the
724
+ // request was going to carry anyway.
725
+ const size = utf8Bytes(file.content) + utf8Bytes(file.path);
726
+ if (current.length > 0 && (current.length >= batchSize || bytes + size > maxBatchBytes)) {
727
+ batches.push(current);
728
+ current = [];
729
+ bytes = 0;
730
+ }
731
+ current.push(file);
732
+ bytes += size;
733
+ }
734
+ if (current.length > 0)
735
+ batches.push(current);
736
+ return batches;
737
+ }
738
+ //# sourceMappingURL=unfazed.js.map