@fluid-app/fluid-cli 0.1.692 → 0.1.694

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.
@@ -1,662 +1,9 @@
1
- import { closeSync, constants, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
2
- import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
3
- import { dirname, isAbsolute, join, sep } from "node:path";
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
3
+ import { dirname, join } from "node:path";
4
4
  import { homedir } from "node:os";
5
5
  import { execFile } from "node:child_process";
6
6
  import { createServer } from "node:http";
7
- import { AsyncLocalStorage } from "node:async_hooks";
8
- //#region src/catalog/annotations.ts
9
- const ANNOTATION = Symbol.for("@fluid-app/fluid-cli.command-annotation");
10
- /**
11
- * Record the endpoints a command calls and whether it writes, so
12
- * `fluid commands --json` can list them. Returns the command for chaining.
13
- */
14
- function describeCommand(command, annotation) {
15
- const target = command;
16
- target[ANNOTATION] = {
17
- ...target[ANNOTATION],
18
- ...annotation
19
- };
20
- return command;
21
- }
22
- function readAnnotation(command) {
23
- return command[ANNOTATION] ?? null;
24
- }
25
- //#endregion
26
- //#region src/catalog/walk.ts
27
- function isHidden(command) {
28
- return command._hidden === true;
29
- }
30
- function isRunnable(command) {
31
- return command._actionHandler != null;
32
- }
33
- function visibleSubcommands(command) {
34
- return command.commands.filter((sub) => !isHidden(sub));
35
- }
36
- function visibleOptions(command) {
37
- return command.options.filter((option) => !option.hidden);
38
- }
39
- function describeOption(option) {
40
- return {
41
- flags: option.flags,
42
- long: option.long ?? null,
43
- short: option.short ?? null,
44
- description: option.description,
45
- takesValue: option.required,
46
- optionalValue: option.optional,
47
- required: option.mandatory,
48
- defaultValue: option.defaultValue
49
- };
50
- }
51
- function describeArgument(argument) {
52
- return {
53
- name: argument.name(),
54
- description: argument.description,
55
- required: argument.required,
56
- variadic: argument.variadic
57
- };
58
- }
59
- function inferWrites(command, declared) {
60
- if (declared !== void 0) return declared;
61
- return command.options.some((option) => option.long === "--yes") ? true : null;
62
- }
63
- function walkCommands(root) {
64
- const entries = [];
65
- function visit(command, path, ancestors) {
66
- const annotation = readAnnotation(command);
67
- const subcommands = visibleSubcommands(command);
68
- entries.push({
69
- command: path.join(" "),
70
- path,
71
- description: command.description(),
72
- aliases: command.aliases(),
73
- arguments: command.registeredArguments.map(describeArgument),
74
- options: visibleOptions(command).map(describeOption),
75
- inheritsOptionsFrom: ancestors.filter((ancestor) => visibleOptions(ancestor).some((option) => option.long !== "--version")).map((ancestor) => commandPath$1(ancestor).join(" ")),
76
- subcommands: subcommands.map((sub) => sub.name()),
77
- runnable: isRunnable(command),
78
- writes: inferWrites(command, annotation?.writes),
79
- endpoints: annotation?.endpoints ?? null
80
- });
81
- for (const sub of subcommands) visit(sub, [...path, sub.name()], [...ancestors, command]);
82
- }
83
- visit(root, [root.name()], []);
84
- return entries;
85
- }
86
- function rootCommand(command) {
87
- let root = command;
88
- while (root.parent) root = root.parent;
89
- return root;
90
- }
91
- function commandPath$1(command) {
92
- const path = [];
93
- for (let c = command; c; c = c.parent) path.unshift(c.name());
94
- return path;
95
- }
96
- /** Keep the entries at or under `prefix`, matching names or aliases. */
97
- function filterCatalog(entries, root, prefix) {
98
- let target = root;
99
- for (const word of prefix) {
100
- const next = visibleSubcommands(target).find((sub) => sub.name() === word || sub.aliases().includes(word));
101
- if (!next) return [];
102
- target = next;
103
- }
104
- const base = commandPath$1(target);
105
- return entries.filter((entry) => base.every((word, index) => entry.path[index] === word));
106
- }
107
- //#endregion
108
- //#region package.json
109
- var version = "0.1.692";
110
- //#endregion
111
- //#region src/auth/client-headers.ts
112
- const CLIENT_HEADERS = {
113
- "X-Fluid-Client": "cli",
114
- "X-Fluid-Client-Version": version
115
- };
116
- //#endregion
117
- //#region src/utils/result.ts
118
- function success(value) {
119
- return {
120
- success: true,
121
- value
122
- };
123
- }
124
- function failure(error) {
125
- return {
126
- success: false,
127
- error
128
- };
129
- }
130
- function isSuccess(result) {
131
- return result.success === true;
132
- }
133
- function isFailure(result) {
134
- return result.success === false;
135
- }
136
- function tryCatch(fn) {
137
- try {
138
- return success(fn());
139
- } catch (error) {
140
- return failure(error instanceof Error ? error : new Error(String(error)));
141
- }
142
- }
143
- async function tryCatchAsync(fn) {
144
- try {
145
- return success(await fn());
146
- } catch (error) {
147
- return failure(error instanceof Error ? error : new Error(String(error)));
148
- }
149
- }
150
- function unwrap(result) {
151
- if (isSuccess(result)) return result.value;
152
- if (result.error instanceof Error) throw result.error;
153
- throw new Error(typeof result.error === "object" && result.error !== null ? JSON.stringify(result.error) : String(result.error));
154
- }
155
- function unwrapOr(result, defaultValue) {
156
- if (isSuccess(result)) return result.value;
157
- return defaultValue;
158
- }
159
- function mapResult(result, fn) {
160
- if (isSuccess(result)) return success(fn(result.value));
161
- return result;
162
- }
163
- function mapError(result, fn) {
164
- if (isFailure(result)) return failure(fn(result.error));
165
- return result;
166
- }
167
- function isError(value) {
168
- return value instanceof Error;
169
- }
170
- function isNodeError(value) {
171
- return value instanceof Error && "code" in value;
172
- }
173
- function getErrorMessage$1(error) {
174
- if (error instanceof Error) return error.message;
175
- if (typeof error === "string") return error;
176
- return String(error);
177
- }
178
- //#endregion
179
- //#region src/auth/fluid-api.ts
180
- /**
181
- * Fluid API client for authentication operations, and the public signup
182
- * that comes before any of them
183
- */
184
- const API_TIMEOUT_MS = 1e4;
185
- const SIGNUP_TIMEOUT_MS = 6e4;
186
- function getFluidApiBase() {
187
- return process.env["FLUID_API_BASE"] ?? "https://api.fluid.app";
188
- }
189
- function makeSignal(timeoutMs = API_TIMEOUT_MS) {
190
- const controller = new AbortController();
191
- const timer = setTimeout(() => controller.abort(), timeoutMs);
192
- return {
193
- signal: controller.signal,
194
- cleanup: () => clearTimeout(timer)
195
- };
196
- }
197
- const FLUID_API_ERROR = {
198
- INVALID_TOKEN: {
199
- code: "INVALID_TOKEN",
200
- message: "Token is invalid or expired"
201
- },
202
- API_UNREACHABLE: {
203
- code: "API_UNREACHABLE",
204
- message: "Could not reach the Fluid API"
205
- },
206
- SIGN_IN_UNFINISHED: {
207
- code: "SIGN_IN_UNFINISHED",
208
- message: "This sign-in can't be finished. Check the shop and the address, then request a new code"
209
- },
210
- CODE_EXPIRED: {
211
- code: "CODE_EXPIRED",
212
- message: "Verification code has expired, was already used, or is locked after too many attempts — please request a new one"
213
- },
214
- RATE_LIMITED: {
215
- code: "RATE_LIMITED",
216
- message: "Too many sign-in requests — wait a minute and try again"
217
- },
218
- INVALID_CODE: {
219
- code: "INVALID_CODE",
220
- message: "Verification code is invalid, expired, already used, or locked after too many attempts"
221
- },
222
- CONTACT_MISSING: {
223
- code: "CONTACT_MISSING",
224
- message: "The code is right, but the email or phone it was sent to is no longer on this account. Ask the company's admin to restore it"
225
- },
226
- COMPANY_NOT_FOUND: {
227
- code: "COMPANY_NOT_FOUND",
228
- message: "Company not found"
229
- },
230
- SWITCH_FAILED: {
231
- code: "SWITCH_FAILED",
232
- message: "Failed to switch company"
233
- },
234
- LINK_GONE: {
235
- code: "LINK_GONE",
236
- message: "This sign-in link has expired or was already used — run `fluid login` for a new one"
237
- }
238
- };
239
- function createApiError(template, details) {
240
- return {
241
- code: template.code,
242
- message: template.message,
243
- details
244
- };
245
- }
246
- /**
247
- * Validate a token against the Fluid API and return company info.
248
- * `baseUrl` is the API the token belongs to; it defaults to the CLI's.
249
- */
250
- async function validateToken(token, options = {}) {
251
- const { signal, cleanup } = makeSignal();
252
- const apiBase = options.baseUrl ?? getFluidApiBase();
253
- try {
254
- const response = await fetch(`${apiBase}/api/company/v1/companies/me`, {
255
- method: "GET",
256
- headers: {
257
- ...CLIENT_HEADERS,
258
- Authorization: `Bearer ${token}`
259
- },
260
- signal
261
- });
262
- if (response.ok) {
263
- const name = (await response.json())?.data?.company?.name;
264
- if (!name) return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, "Unexpected response shape from /companies/me"));
265
- return success({ name });
266
- }
267
- if (response.status === 403) return await staffCompanyFromMe(token, apiBase, signal);
268
- if (response.status === 401) return failure(createApiError(FLUID_API_ERROR.INVALID_TOKEN, `HTTP ${response.status}: Check that your token is valid and non-expired.`));
269
- const body = await response.text();
270
- return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, `HTTP ${response.status}: ${body}`));
271
- } catch (err) {
272
- const message = err instanceof Error ? err.message : String(err);
273
- return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));
274
- } finally {
275
- cleanup();
276
- }
277
- }
278
- /** The roles a CLI login may hold, as `/api/me` names them. */
279
- const STAFF_ROLES = new Set(["admin", "rep"]);
280
- /**
281
- * The company of an admin's or a rep's login, from `/api/me`. A token it
282
- * refuses, or one that belongs to a customer, is invalid for the CLI; any
283
- * other failure, or an answer with no company name, leaves the API
284
- * unreachable, as `/companies/me` does.
285
- */
286
- async function staffCompanyFromMe(token, apiBase, signal) {
287
- const response = await fetch(`${apiBase}/api/me`, {
288
- method: "GET",
289
- headers: {
290
- ...CLIENT_HEADERS,
291
- Authorization: `Bearer ${token}`
292
- },
293
- signal
294
- });
295
- if (response.status === 401 || response.status === 403) return failure(createApiError(FLUID_API_ERROR.INVALID_TOKEN, `HTTP ${response.status}: Check that your token is valid and non-expired.`));
296
- if (!response.ok) {
297
- const body = await response.text();
298
- return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, `HTTP ${response.status} from /api/me: ${body}`));
299
- }
300
- const data = await response.json();
301
- if (typeof data?.role !== "string" || !STAFF_ROLES.has(data.role)) return failure(createApiError(FLUID_API_ERROR.INVALID_TOKEN, "This login is not an admin's or a rep's, so it cannot be used with the CLI."));
302
- const name = data.company?.name;
303
- if (typeof name !== "string" || name === "") return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, "Unexpected response shape from /api/me"));
304
- return success({ name });
305
- }
306
- /**
307
- * Send a multi-factor authentication code to the given email address.
308
- * The API answers 201 whether or not the address can sign in
309
- * (anti-enumeration).
310
- *
311
- * With `fluidShop`, the server ties the code to the person's membership in
312
- * that company, so redeeming it signs in to that company alone and, for an
313
- * admin's emailed code, confirms a new signup.
314
- */
315
- async function sendMfa(email, options = {}) {
316
- const { signal, cleanup } = makeSignal();
317
- try {
318
- const response = await fetch(`${getFluidApiBase()}/api/authentication/send_mfa`, {
319
- method: "POST",
320
- headers: {
321
- ...CLIENT_HEADERS,
322
- "Content-Type": "application/json"
323
- },
324
- body: JSON.stringify(options.fluidShop ? {
325
- email,
326
- fluid_shop: options.fluidShop
327
- } : { email }),
328
- signal
329
- });
330
- if (response.status === 201) {
331
- const data = await response.json();
332
- const uuid = data.multi_factor_authentication?.uuid;
333
- const expiresAt = data.multi_factor_authentication?.verification_code_expires_at;
334
- if (!uuid || !expiresAt) return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, "Unexpected response shape from /send_mfa"));
335
- return success({
336
- uuid,
337
- expiresAt
338
- });
339
- }
340
- const body = await response.text();
341
- if (response.status === 429) return failure(createApiError(FLUID_API_ERROR.RATE_LIMITED, `HTTP 429: ${body}`));
342
- return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, `HTTP ${response.status}: ${body}`));
343
- } catch (err) {
344
- const message = err instanceof Error ? err.message : String(err);
345
- return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));
346
- } finally {
347
- cleanup();
348
- }
349
- }
350
- /**
351
- * Confirm a multi-factor authentication code and retrieve company JWTs.
352
- *
353
- * `baseUrl` is the API the code was sent from; a sign-in finished in a
354
- * later process passes the one it saved, not the current environment's.
355
- */
356
- async function confirmMfa(uuid, code, options = {}) {
357
- const { signal, cleanup } = makeSignal();
358
- const apiBase = options.baseUrl ?? getFluidApiBase();
359
- try {
360
- const response = await fetch(`${apiBase}/api/authentication/confirm_mfa`, {
361
- method: "POST",
362
- headers: {
363
- ...CLIENT_HEADERS,
364
- "Content-Type": "application/json"
365
- },
366
- body: JSON.stringify({
367
- uuid,
368
- multi_factor_authentication: { verification_code: code },
369
- ...options.fluidShop ? { fluid_shop: options.fluidShop } : {}
370
- }),
371
- signal
372
- });
373
- if (response.ok) {
374
- const data = await response.json();
375
- if (!data.authenticated) return failure(createApiError(FLUID_API_ERROR.INVALID_CODE, "Authentication was not confirmed by the server"));
376
- const companies = Array.isArray(data.companies) ? data.companies : [];
377
- return success({
378
- authType: data.auth_type ?? "",
379
- companies: companies.map((c) => ({
380
- id: c.id,
381
- name: c.name,
382
- shopName: c.shop_name,
383
- jwt: c.jwt,
384
- ...c.auth_type ? { authType: c.auth_type } : {}
385
- })),
386
- signInPath: data.sign_in_path === "identity" ? "identity" : "legacy"
387
- });
388
- }
389
- if (response.status === 404) return failure(createApiError(FLUID_API_ERROR.SIGN_IN_UNFINISHED));
390
- if (response.status === 410) return failure(createApiError(FLUID_API_ERROR.CODE_EXPIRED));
391
- const body = await response.text();
392
- if (response.status === 422) return failure(createApiError(namesVerificationChannel(body) ? FLUID_API_ERROR.CONTACT_MISSING : FLUID_API_ERROR.INVALID_CODE));
393
- if (response.status === 429) return failure(createApiError(FLUID_API_ERROR.RATE_LIMITED, `HTTP 429: ${body}`));
394
- return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, `HTTP ${response.status}: ${body}`));
395
- } catch (err) {
396
- const message = err instanceof Error ? err.message : String(err);
397
- return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));
398
- } finally {
399
- cleanup();
400
- }
401
- }
402
- /**
403
- * Redeem the single-use token in an identity sign-in email, the email a
404
- * person whose company signs in through the identity service receives
405
- * instead of a code. Rails answers 410 for a forged, expired, or used link.
406
- */
407
- async function redeemIdentityLink(token, options = {}) {
408
- const { signal, cleanup } = makeSignal();
409
- try {
410
- const response = await fetch(`${options.baseUrl ?? getFluidApiBase()}/api/v2026-10/single-sign-ons/identity-link-redemptions`, {
411
- method: "POST",
412
- headers: {
413
- ...CLIENT_HEADERS,
414
- "Content-Type": "application/json"
415
- },
416
- body: JSON.stringify({ token }),
417
- signal
418
- });
419
- if (response.ok) {
420
- const data = await response.json();
421
- if (data.sign_in_path !== "identity" || !data.fluid_shop) return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, "Unexpected response shape from /identity-link-redemptions"));
422
- return success({
423
- signInPath: "identity",
424
- fluidShop: data.fluid_shop
425
- });
426
- }
427
- if (response.status === 410 || response.status === 404) return failure(createApiError(FLUID_API_ERROR.LINK_GONE));
428
- const body = await response.text();
429
- return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, `HTTP ${response.status}: ${body}`));
430
- } catch (err) {
431
- const message = err instanceof Error ? err.message : String(err);
432
- return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));
433
- } finally {
434
- cleanup();
435
- }
436
- }
437
- /**
438
- * Fetch all companies the authenticated user has access to.
439
- */
440
- async function fetchUserCompanies(token, baseUrl) {
441
- const { signal, cleanup } = makeSignal();
442
- const apiBase = baseUrl ?? getFluidApiBase();
443
- try {
444
- const response = await fetch(`${apiBase}/api/me`, {
445
- method: "GET",
446
- headers: {
447
- ...CLIENT_HEADERS,
448
- Authorization: `Bearer ${token}`
449
- },
450
- signal
451
- });
452
- if (response.ok) {
453
- const data = await response.json();
454
- return success((Array.isArray(data.companies) ? data.companies : []).map((c) => ({
455
- id: c.id,
456
- name: c.name,
457
- ...typeof c.uuid_v7 === "string" ? { uuidV7: c.uuid_v7 } : {}
458
- })));
459
- }
460
- if (response.status === 401 || response.status === 403) return failure(createApiError(FLUID_API_ERROR.INVALID_TOKEN, `HTTP ${response.status}`));
461
- const body = await response.text();
462
- return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, `HTTP ${response.status}: ${body}`));
463
- } catch (err) {
464
- const message = err instanceof Error ? err.message : String(err);
465
- return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));
466
- } finally {
467
- cleanup();
468
- }
469
- }
470
- /**
471
- * Switch to a different company and receive a new JWT.
472
- *
473
- * Response shape (from @fluid-app/auth SwitchCompanyResponse):
474
- * { company: { id, name, fluid_shop, jwt }, meta: { request_id, timestamp } }
475
- */
476
- async function switchCompany(token, companyId, baseUrl) {
477
- const { signal, cleanup } = makeSignal();
478
- const apiBase = baseUrl ?? getFluidApiBase();
479
- try {
480
- const response = await fetch(`${apiBase}/api/authentication/company/${companyId}/switch`, {
481
- method: "PUT",
482
- headers: {
483
- ...CLIENT_HEADERS,
484
- Authorization: `Bearer ${token}`,
485
- "Content-Type": "application/json"
486
- },
487
- signal
488
- });
489
- if (response.ok) {
490
- const company = (await response.json()).company;
491
- if (!company?.jwt) return failure(createApiError(FLUID_API_ERROR.SWITCH_FAILED, "Unexpected response shape from /switch"));
492
- return success({
493
- companyId: company.id,
494
- companyName: company.name,
495
- fluidShop: company.fluid_shop,
496
- jwt: company.jwt
497
- });
498
- }
499
- if (response.status === 404) return failure(createApiError(FLUID_API_ERROR.COMPANY_NOT_FOUND, `Company ${companyId} not found`));
500
- if (response.status === 401 || response.status === 403) return failure(createApiError(FLUID_API_ERROR.INVALID_TOKEN, `HTTP ${response.status}`));
501
- const body = await response.text();
502
- return failure(createApiError(FLUID_API_ERROR.SWITCH_FAILED, `HTTP ${response.status}: ${body}`));
503
- } catch (err) {
504
- const message = err instanceof Error ? err.message : String(err);
505
- return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));
506
- } finally {
507
- cleanup();
508
- }
509
- }
510
- const SIGNUP_ERROR = {
511
- SUBDOMAIN_TAKEN: {
512
- code: "SUBDOMAIN_TAKEN",
513
- message: "That subdomain belongs to another company. Pick another, unless an earlier signup of yours sent it: then the company exists, so sign in instead."
514
- },
515
- SIGNUP_MAY_EXIST: {
516
- code: "SIGNUP_MAY_EXIST",
517
- message: "The signup failed, and the company may still have been created. Run the same command once more with the same subdomain: if it then says the subdomain is taken, the company exists, so sign in instead."
518
- },
519
- SIGNUP_INVALID: {
520
- code: "SIGNUP_INVALID",
521
- message: "Fluid rejected the signup. See errors for each field."
522
- },
523
- RATE_LIMITED: {
524
- code: "RATE_LIMITED",
525
- message: "Too many signups from this address or for this email. Failed attempts count too, so wait out the retry time before trying again."
526
- },
527
- SIGNUP_FORBIDDEN: {
528
- code: "SIGNUP_FORBIDDEN",
529
- message: "Fluid refused this signup. Don't retry; contact Fluid support."
530
- },
531
- SIGNUP_OUTCOME_UNKNOWN: {
532
- code: "SIGNUP_OUTCOME_UNKNOWN",
533
- message: "No usable answer from Fluid, so the company may or may not have been created. Check before retrying: sign in, or run the same command once more and read a 'subdomain is taken' as created."
534
- }
535
- };
536
- function signupError(template, extra = {}) {
537
- return {
538
- code: template.code,
539
- message: template.message,
540
- ...extra
541
- };
542
- }
543
- function asRecord(value) {
544
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
545
- }
546
- /** Whether a confirm 422 body names the verification channel. */
547
- function namesVerificationChannel(body) {
548
- try {
549
- const errors = asRecord(asRecord(JSON.parse(body))?.errors);
550
- return errors !== void 0 && fieldMessages(errors, "multi_factor_authentication", "verification_channel").length > 0;
551
- } catch {
552
- return false;
553
- }
554
- }
555
- function fieldMessages(errors, record, field) {
556
- const messages = asRecord(errors[record])?.[field];
557
- return Array.isArray(messages) ? messages.filter((m) => typeof m === "string") : [];
558
- }
559
- function signupRejection(body) {
560
- const errors = asRecord(asRecord(body)?.["errors"]) ?? {};
561
- if (fieldMessages(errors, "company", "subdomain").some((m) => m.includes("taken"))) return signupError(SIGNUP_ERROR.SUBDOMAIN_TAKEN, {
562
- status: 422,
563
- errors
564
- });
565
- if (fieldMessages(errors, "company", "base").length > 0) return signupError(SIGNUP_ERROR.SIGNUP_MAY_EXIST, {
566
- status: 422,
567
- errors
568
- });
569
- return signupError(SIGNUP_ERROR.SIGNUP_INVALID, {
570
- status: 422,
571
- errors
572
- });
573
- }
574
- function readSignup(body) {
575
- const root = asRecord(body);
576
- const company = asRecord(root?.["company"]);
577
- const userCompany = asRecord(root?.["user_company"]);
578
- const due = asRecord(root?.["requirements"])?.["currently_due"];
579
- if (typeof company?.["id"] !== "number" || typeof company["fluid_shop"] !== "string" || typeof userCompany?.["id"] !== "number") return;
580
- return {
581
- company: {
582
- id: company["id"],
583
- name: String(company["name"] ?? ""),
584
- subdomain: String(company["subdomain"] ?? ""),
585
- fluidShop: company["fluid_shop"]
586
- },
587
- userCompany: {
588
- id: userCompany["id"],
589
- email: String(userCompany["email"] ?? "")
590
- },
591
- currentlyDue: Array.isArray(due) ? due.filter((d) => typeof d === "string") : []
592
- };
593
- }
594
- async function readJson(response) {
595
- try {
596
- return await response.json();
597
- } catch {
598
- return;
599
- }
600
- }
601
- /**
602
- * Sign up a new company with the public, unauthenticated `POST /api/company`.
603
- *
604
- * Sends exactly one request and never retries it: a 422 can follow a saved
605
- * company, and every attempt, failed or not, counts toward the per-IP and
606
- * per-email signup limits.
607
- */
608
- async function signup(request) {
609
- const { signal, cleanup } = makeSignal(SIGNUP_TIMEOUT_MS);
610
- try {
611
- const response = await fetch(`${getFluidApiBase()}/api/company`, {
612
- method: "POST",
613
- headers: {
614
- ...CLIENT_HEADERS,
615
- "Content-Type": "application/json"
616
- },
617
- body: JSON.stringify({
618
- user: {
619
- first_name: request.firstName,
620
- last_name: request.lastName,
621
- email: request.email
622
- },
623
- company: {
624
- name: request.companyName,
625
- subdomain: request.subdomain,
626
- ...request.color ? { color: request.color } : {}
627
- }
628
- }),
629
- signal
630
- });
631
- const body = await readJson(response);
632
- if (response.status === 200) {
633
- const created = readSignup(body);
634
- return created ? success(created) : failure(signupError(SIGNUP_ERROR.SIGNUP_OUTCOME_UNKNOWN, {
635
- status: 200,
636
- details: "Unexpected response shape from POST /api/company"
637
- }));
638
- }
639
- if (response.status === 422) return failure(signupRejection(body));
640
- if (response.status === 429) {
641
- const retryAfter = asRecord(body)?.["retry_after"];
642
- return failure(signupError(SIGNUP_ERROR.RATE_LIMITED, {
643
- status: 429,
644
- ...typeof retryAfter === "number" ? { retryAfter } : {}
645
- }));
646
- }
647
- if (response.status === 403) return failure(signupError(SIGNUP_ERROR.SIGNUP_FORBIDDEN, { status: 403 }));
648
- return failure(signupError(SIGNUP_ERROR.SIGNUP_OUTCOME_UNKNOWN, {
649
- status: response.status,
650
- details: `HTTP ${response.status}`
651
- }));
652
- } catch (err) {
653
- const message = err instanceof Error ? err.message : String(err);
654
- return failure(signupError(SIGNUP_ERROR.SIGNUP_OUTCOME_UNKNOWN, { details: message }));
655
- } finally {
656
- cleanup();
657
- }
658
- }
659
- //#endregion
660
7
  //#region src/config/types.ts
661
8
  /** Whether a profile signs in through the identity service. */
662
9
  function isIdentityProfile(profile) {
@@ -1305,7 +652,7 @@ function getValidRequestBody(options) {
1305
652
  }
1306
653
  //#endregion
1307
654
  //#region ../../api-clients/hey-api-fetch-runtime/src/generated/core/auth.gen.ts
1308
- const getAuthToken$1 = async (auth, callback) => {
655
+ const getAuthToken = async (auth, callback) => {
1309
656
  const token = typeof callback === "function" ? await callback(auth) : callback;
1310
657
  if (!token) return;
1311
658
  if (auth.scheme === "bearer") return `Bearer ${token}`;
@@ -1379,7 +726,7 @@ const checkForExistence = (options, name) => {
1379
726
  async function setAuthParams(options) {
1380
727
  for (const auth of options.security ?? []) {
1381
728
  if (checkForExistence(options, auth.name)) continue;
1382
- const token = await getAuthToken$1(auth, options.auth);
729
+ const token = await getAuthToken(auth, options.auth);
1383
730
  if (!token) continue;
1384
731
  const name = auth.name ?? "Authorization";
1385
732
  switch (auth.in) {
@@ -2740,6 +2087,7 @@ function readConfig() {
2740
2087
  profiles: {}
2741
2088
  } : config;
2742
2089
  }
2090
+ /** The config file as stored, including the profiles strict config hides from `readConfig`. */
2743
2091
  function readStoredConfig() {
2744
2092
  const configPath = getConfigFilePath();
2745
2093
  if (!existsSync(configPath)) return createDefaultConfig();
@@ -2904,6 +2252,9 @@ function invalidateClientToken(profile, sent) {
2904
2252
  if (sent !== void 0 && held.get(key)?.token !== sent) return;
2905
2253
  held.delete(key);
2906
2254
  }
2255
+ async function isSlowDown(response) {
2256
+ return (await response.clone().json().catch(() => null))?.error === "slow_down";
2257
+ }
2907
2258
  async function requestToken(auth) {
2908
2259
  const secret = await (await deps$1.storage()).get(auth.storageKey);
2909
2260
  if (!secret) throw new SessionError("not_signed_in", "The client secret for this profile is not in the credential store.");
@@ -2922,7 +2273,7 @@ async function requestToken(auth) {
2922
2273
  }).catch(() => {
2923
2274
  throw new SessionError("temporarily_unavailable", "The identity service could not be reached.");
2924
2275
  });
2925
- if (response.status >= 500 || response.status === 429) throw new SessionError("temporarily_unavailable", "The identity service is unavailable.");
2276
+ if (response.status >= 500 || response.status === 429 || response.status === 408 || response.status === 400 && await isSlowDown(response)) throw new SessionError("temporarily_unavailable", "The identity service is unavailable.");
2926
2277
  if (!response.ok) throw new SessionError("access_denied", "The identity service refused this client's credentials.");
2927
2278
  const body = await response.json().catch(() => null);
2928
2279
  if (typeof body?.access_token !== "string" || !body.access_token) throw new SessionError("temporarily_unavailable", "The identity service answered with no access token.");
@@ -2994,6 +2345,78 @@ function peekClientToken(profile) {
2994
2345
  if (!existing || deps$1.now() >= existing.expiresAt - EXPIRY_MARGIN_MS$1) return null;
2995
2346
  return existing.token;
2996
2347
  }
2348
+ /** A profile with this name exists and the caller asked not to replace it. */
2349
+ var ProfileExistsError = class extends Error {
2350
+ constructor(profileName) {
2351
+ super(`profile "${profileName}" already exists`);
2352
+ this.profileName = profileName;
2353
+ this.name = "ProfileExistsError";
2354
+ }
2355
+ };
2356
+ /**
2357
+ * The secret stored for a profile that could not be written is still in the
2358
+ * credential store under `storageKey`, because deleting it failed too.
2359
+ */
2360
+ var OrphanedClientSecretError = class extends Error {
2361
+ constructor(storageKey, options) {
2362
+ super("The client profile could not be saved and its secret could not be removed from the credential store.", options);
2363
+ this.storageKey = storageKey;
2364
+ this.name = "OrphanedClientSecretError";
2365
+ }
2366
+ };
2367
+ /**
2368
+ * Stores the client secret in the credential store and writes a `client`
2369
+ * profile named `name`, replacing any profile of that name. The profile
2370
+ * becomes active only when none was. `problems` names each replaced
2371
+ * credential that could not be cleaned up. When the profile cannot be
2372
+ * written, the new secret is deleted again and the error is rethrown; if that
2373
+ * delete fails too, an OrphanedClientSecretError names the key left behind.
2374
+ */
2375
+ async function saveClientProfile(name, input, options = {}) {
2376
+ const storage = await deps$1.storage();
2377
+ const storageKey = `client.${randomUUID()}`;
2378
+ await storage.set(storageKey, input.clientSecret);
2379
+ const profile = {
2380
+ name,
2381
+ companyName: input.companyName,
2382
+ storedAt: (/* @__PURE__ */ new Date()).toISOString(),
2383
+ baseUrl: input.baseUrl,
2384
+ auth: {
2385
+ mode: "client",
2386
+ clientId: input.clientId,
2387
+ org: input.org,
2388
+ identityUrl: input.identityUrl,
2389
+ storageKey
2390
+ }
2391
+ };
2392
+ let before;
2393
+ let after;
2394
+ try {
2395
+ before = readConfig();
2396
+ after = updateConfig((config) => {
2397
+ if (options.replace === false && config.profiles[name]) throw new ProfileExistsError(name);
2398
+ return {
2399
+ ...config,
2400
+ activeProfile: config.activeProfile ?? name,
2401
+ profiles: {
2402
+ ...config.profiles,
2403
+ [name]: profile
2404
+ }
2405
+ };
2406
+ });
2407
+ } catch (error) {
2408
+ try {
2409
+ await storage.delete(storageKey);
2410
+ } catch {
2411
+ throw new OrphanedClientSecretError(storageKey, { cause: error });
2412
+ }
2413
+ throw error;
2414
+ }
2415
+ return {
2416
+ profile,
2417
+ problems: await endUnusedSessions(before, after)
2418
+ };
2419
+ }
2997
2420
  /** Deletes a client secret from the credential store. */
2998
2421
  async function deleteClientSecret(auth) {
2999
2422
  held.delete(cacheKey(auth));
@@ -3502,635 +2925,6 @@ async function endUnusedSessions(before, after) {
3502
2925
  return problems;
3503
2926
  }
3504
2927
  //#endregion
3505
- //#region src/config/project-config.ts
3506
- /**
3507
- * Project-level config (.fluidrc) reader.
3508
- *
3509
- * Walks upward from a starting directory to find a `.fluidrc` file.
3510
- * The file is JSON with a `profile` field that maps to a profile name
3511
- * in `~/.fluid/config.json`.
3512
- *
3513
- * This allows portal repos to pin themselves to a specific CLI profile
3514
- * so that `fluid portal pull` / `push` always use the correct company
3515
- * credentials, regardless of which profile is globally active.
3516
- */
3517
- const RC_FILENAME = ".fluidrc";
3518
- /** Cached result keyed by the starting directory. */
3519
- let cachedResult;
3520
- /**
3521
- * Walk upward from `startDir` looking for a `.fluidrc` file.
3522
- *
3523
- * Returns the parsed config when found, or `null` if no valid `.fluidrc`
3524
- * exists in any ancestor directory.
3525
- *
3526
- * The result is cached per starting directory for the lifetime of the
3527
- * process — CLI commands are short-lived so stale-cache is not a concern.
3528
- */
3529
- function findProjectConfig(startDir) {
3530
- if (cachedResult && cachedResult.dir === startDir) return cachedResult.config;
3531
- let dir = startDir;
3532
- while (true) {
3533
- const rcPath = join(dir, RC_FILENAME);
3534
- if (existsSync(rcPath)) {
3535
- try {
3536
- const raw = readFileSync(rcPath, "utf8");
3537
- const parsed = JSON.parse(raw);
3538
- if (typeof parsed.profile === "string" && parsed.profile.length > 0) {
3539
- const config = { profile: parsed.profile };
3540
- cachedResult = {
3541
- dir: startDir,
3542
- config
3543
- };
3544
- return config;
3545
- }
3546
- } catch {}
3547
- cachedResult = {
3548
- dir: startDir,
3549
- config: null
3550
- };
3551
- return null;
3552
- }
3553
- const parent = dirname(dir);
3554
- if (parent === dir) break;
3555
- dir = parent;
3556
- }
3557
- cachedResult = {
3558
- dir: startDir,
3559
- config: null
3560
- };
3561
- return null;
3562
- }
3563
- //#endregion
3564
- //#region src/auth/token.ts
3565
- /**
3566
- * Token storage and retrieval from config
3567
- */
3568
- /**
3569
- * Resolve the credential for a named profile, or for the active one when
3570
- * omitted.
3571
- *
3572
- * Resolution order (when `profileName` is omitted — mirrors
3573
- * `createCommandContext` in domain/context.ts):
3574
- * 1. `FLUID_TOKEN` / `FLUID_API_TOKEN` environment variables
3575
- * 2. Project-level `.fluidrc` profile (walks upward from cwd)
3576
- * 3. Global active profile from `~/.fluid/config.json`
3577
- *
3578
- * When `profileName` is provided explicitly (e.g. via `--profile` flag),
3579
- * it takes precedence over the environment variables, `.fluidrc`, and the
3580
- * active profile.
3581
- */
3582
- function resolveCredentialSource(profileName) {
3583
- const config = readConfig();
3584
- if (profileName) {
3585
- const profile = config.profiles[profileName];
3586
- return profile ? {
3587
- kind: "profile",
3588
- profile
3589
- } : null;
3590
- }
3591
- const envToken = process.env["FLUID_TOKEN"] ?? process.env["FLUID_API_TOKEN"];
3592
- if (envToken) return {
3593
- kind: "token",
3594
- token: envToken
3595
- };
3596
- const projectConfig = findProjectConfig(process.cwd());
3597
- if (projectConfig?.profile) {
3598
- const profile = config.profiles[projectConfig.profile];
3599
- if (profile) return {
3600
- kind: "profile",
3601
- profile
3602
- };
3603
- }
3604
- if (!config.activeProfile) return null;
3605
- const profile = config.profiles[config.activeProfile];
3606
- return profile ? {
3607
- kind: "profile",
3608
- profile
3609
- } : null;
3610
- }
3611
- /**
3612
- * Get the auth token for a named profile, or the active profile when omitted,
3613
- * in the order {@link resolveCredentialSource} describes.
3614
- *
3615
- * An identity-mode profile keeps no token in the config file. Its access
3616
- * token lives in this process's memory once the session has been restored,
3617
- * which the CLI does before running a command; until then, and after its
3618
- * session ends, this returns null. Prefer {@link getAuthTokenAsync}, which
3619
- * restores and refreshes the session itself.
3620
- */
3621
- function getAuthToken(profileName) {
3622
- const source = resolveCredentialSource(profileName);
3623
- if (!source) return null;
3624
- if (source.kind === "token") return source.token;
3625
- if (isIdentityProfile(source.profile)) return peekIdentityToken(source.profile.name);
3626
- if (isClientProfile(source.profile)) return peekClientToken(source.profile);
3627
- return source.profile.token ?? null;
3628
- }
3629
- /**
3630
- * Like {@link getAuthToken}, but restores, refreshes, or exchanges an
3631
- * identity-mode profile's session as needed. Resolves with null when there
3632
- * is no credential; rejects when an identity session has ended.
3633
- */
3634
- async function getAuthTokenAsync(profileName) {
3635
- const source = resolveCredentialSource(profileName);
3636
- if (!source) return null;
3637
- if (source.kind === "token") return source.token;
3638
- if (isIdentityProfile(source.profile)) return profileAccessToken(source.profile);
3639
- if (isClientProfile(source.profile)) return clientAccessToken(source.profile);
3640
- return source.profile.token ?? null;
3641
- }
3642
- /**
3643
- * Like {@link getAuthTokenAsync}, for a token that acts only as `roles`. An
3644
- * admin who is also a rep holds an `admin` token by default, which an API that
3645
- * wants a rep refuses; this asks the identity service to narrow the session to
3646
- * `roles` in the company (RFC 8693), and holds that token apart from the
3647
- * default one, which every other reader keeps getting.
3648
- *
3649
- * Only an identity-mode profile can be narrowed. A literal token
3650
- * (`FLUID_TOKEN`) and a legacy profile come back exactly as
3651
- * {@link getAuthTokenAsync} returns them, because their token already is what
3652
- * it is. Resolves with null when there is no credential. Rejects with an
3653
- * error {@link isRoleNotGrantedError} recognises when the person does not
3654
- * hold `roles` in the company, and when an identity session has ended.
3655
- */
3656
- async function getRoleAuthTokenAsync(roles, profileName) {
3657
- const source = resolveCredentialSource(profileName);
3658
- if (!source) return null;
3659
- if (source.kind === "token") return source.token;
3660
- if (isIdentityProfile(source.profile)) return profileAccessToken(source.profile, roles);
3661
- if (isClientProfile(source.profile)) return clientAccessToken(source.profile);
3662
- return source.profile.token ?? null;
3663
- }
3664
- /**
3665
- * Get the active profile, or null if not logged in
3666
- */
3667
- function getActiveProfile() {
3668
- const config = readConfig();
3669
- if (!config.activeProfile) return null;
3670
- return config.profiles[config.activeProfile] ?? null;
3671
- }
3672
- /**
3673
- * List all stored profile names
3674
- */
3675
- function listProfileNames() {
3676
- const config = readConfig();
3677
- return Object.keys(config.profiles);
3678
- }
3679
- //#endregion
3680
- //#region src/inputs/declare.ts
3681
- const resolvers = /* @__PURE__ */ new WeakMap();
3682
- /**
3683
- * Declares the local inputs a command's action reads.
3684
- *
3685
- * command - the leaf command whose action reads the inputs
3686
- * resolver - maps commander's parsed opts and args to the input specs; it
3687
- * must be a pure function of opts and args and must not touch the filesystem
3688
- *
3689
- * Returns the command.
3690
- */
3691
- function declareInputs(command, resolver) {
3692
- resolvers.set(command, resolver);
3693
- return command;
3694
- }
3695
- function getInputResolver(command) {
3696
- return resolvers.get(command);
3697
- }
3698
- //#endregion
3699
- //#region src/inputs/scope.ts
3700
- let internalDepth = 0;
3701
- const asyncScope = new AsyncLocalStorage();
3702
- /** True while the inputs implementation itself is touching the filesystem. */
3703
- function inInternalRead() {
3704
- return internalDepth > 0 || asyncScope.getStore() === true;
3705
- }
3706
- function withInternalReads(fn) {
3707
- internalDepth++;
3708
- try {
3709
- return fn();
3710
- } finally {
3711
- internalDepth--;
3712
- }
3713
- }
3714
- /**
3715
- * Async form of withInternalReads. The scope follows fn's own async
3716
- * continuations only; unrelated concurrent work stays guarded.
3717
- */
3718
- async function withInternalReadsAsync(fn) {
3719
- return asyncScope.run(true, fn);
3720
- }
3721
- //#endregion
3722
- //#region src/inputs/paths.ts
3723
- function lexicalPath(path, cwd = process.cwd()) {
3724
- return isAbsolute(path) ? path : `${cwd}${sep}${path}`;
3725
- }
3726
- /**
3727
- * The path rule for resolve and expect mode (default mode reads the lexical
3728
- * path so /dev/stdin works): make the path absolute without normalizing, then realpath it natively so `..` after a symlink keeps OS
3729
- * semantics. Throws when the path does not exist.
3730
- */
3731
- function canonicalPath(path, cwd = process.cwd()) {
3732
- const lexical = lexicalPath(path, cwd);
3733
- return {
3734
- lexical,
3735
- canonical: withInternalReads(() => realpathSync.native(lexical))
3736
- };
3737
- }
3738
- //#endregion
3739
- //#region src/inputs/tree.ts
3740
- function normalizeIgnore(ignore) {
3741
- const out = /* @__PURE__ */ new Set();
3742
- for (const pattern of ignore ?? []) {
3743
- const segments = pattern.split("/");
3744
- if (pattern === "" || /[*?[\]{}]/.test(pattern) || segments.some((s) => s === "" || s === "." || s === "..")) throw new Error(`Invalid tree ignore pattern: ${JSON.stringify(pattern)}`);
3745
- out.add(pattern);
3746
- }
3747
- return [...out].sort(compare);
3748
- }
3749
- function ignoreKey(ignore, skipDotNames = false) {
3750
- return skipDotNames ? JSON.stringify({
3751
- ignore,
3752
- skipDotNames: true
3753
- }) : JSON.stringify(ignore);
3754
- }
3755
- function normalizeSkipDotNames(value) {
3756
- if (value === void 0 || typeof value === "boolean") return value === true;
3757
- throw new Error(`Invalid tree skipDotNames: ${JSON.stringify(value) ?? String(value)}`);
3758
- }
3759
- function compare(a, b) {
3760
- return a < b ? -1 : a > b ? 1 : 0;
3761
- }
3762
- /**
3763
- * The single ignore matcher for tree inputs, used by resolve, expect and
3764
- * default mode alike. A pattern without "/" matches an entry's basename at
3765
- * any depth; a pattern with "/" matches a root-relative path. A match on a
3766
- * directory also excludes every descendant.
3767
- *
3768
- * rel - "/"-separated path relative to the tree root
3769
- * ignore - patterns from normalizeIgnore
3770
- *
3771
- * Returns true when rel or any ancestor directory of rel is ignored.
3772
- */
3773
- function isIgnored(rel, ignore) {
3774
- const segments = rel.split("/");
3775
- let prefix = "";
3776
- for (const segment of segments) {
3777
- prefix = prefix === "" ? segment : `${prefix}/${segment}`;
3778
- if (ignore.includes(segment) || ignore.includes(prefix)) return true;
3779
- }
3780
- return false;
3781
- }
3782
- /**
3783
- * Lists the regular files under an already canonical root as sorted
3784
- * "/"-separated relative paths. Symlink entries are skipped at list time in
3785
- * every mode. Throws if a directory being walked is not its own canonical
3786
- * path. With skipDotNames, every entry whose name starts with "." is skipped
3787
- * before its directory is read.
3788
- */
3789
- function listTreeFiles(root, ignore, skipDotNames = false) {
3790
- const out = [];
3791
- const walk = (dir, relDir) => {
3792
- assertCanonicalDir(dir);
3793
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
3794
- const rel = relDir === "" ? entry.name : `${relDir}/${entry.name}`;
3795
- if (skipDotNames && entry.name.startsWith(".")) continue;
3796
- if (isIgnored(rel, ignore)) continue;
3797
- if (entry.isDirectory()) walk(join(dir, entry.name), rel);
3798
- else if (entry.isFile()) out.push(rel);
3799
- }
3800
- };
3801
- withInternalReads(() => walk(root, ""));
3802
- return out.sort(compare);
3803
- }
3804
- function assertCanonicalDir(dir) {
3805
- if (realpathSync.native(dir) !== dir) throw new Error(`Tree directory changed during read: ${dir}`);
3806
- }
3807
- /**
3808
- * Reads one tree member from a canonical root. Rejects a non-canonical parent
3809
- * directory and a symlinked or non-regular final component (O_NOFOLLOW).
3810
- * Known residual: a parent directory swapped between the canonical check and
3811
- * the open is not detected; it needs a local writer to the tree during the
3812
- * command, and Node has no openat2.
3813
- */
3814
- function readTreeFileFromDisk(root, rel) {
3815
- return withInternalReads(() => {
3816
- const path = join(root, rel);
3817
- assertCanonicalDir(join(root, dirname(rel)));
3818
- const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
3819
- try {
3820
- if (!fstatSync(fd).isFile()) throw new Error(`Tree member is not a regular file: ${path}`);
3821
- return readFileSync(fd);
3822
- } finally {
3823
- closeSync(fd);
3824
- }
3825
- });
3826
- }
3827
- //#endregion
3828
- //#region src/inputs/snapshot.ts
3829
- function treeKey(root, ignore, skipDotNames = false) {
3830
- return `${root}\0${ignoreKey(ignore, skipDotNames)}`;
3831
- }
3832
- function sha256(data) {
3833
- return createHash("sha256").update(data).digest("hex");
3834
- }
3835
- function resolveInputs(specs, cwd = process.cwd()) {
3836
- return withInternalReads(() => {
3837
- const snapshot = {
3838
- files: /* @__PURE__ */ new Map(),
3839
- aliases: /* @__PURE__ */ new Map(),
3840
- trees: /* @__PURE__ */ new Map(),
3841
- treeAliases: /* @__PURE__ */ new Map(),
3842
- refs: /* @__PURE__ */ new Map()
3843
- };
3844
- const entries = [];
3845
- for (const spec of specs) if (spec.kind === "ref") {
3846
- snapshot.refs.set(spec.name, spec.value);
3847
- entries.push({
3848
- kind: "ref",
3849
- name: spec.name,
3850
- value: spec.value
3851
- });
3852
- } else if (spec.kind === "file" || spec.kind === "config") {
3853
- const { lexical, canonical: path } = canonicalPath(spec.path, cwd);
3854
- const content = readFileSync(path);
3855
- snapshot.aliases.set(lexical, path);
3856
- snapshot.aliases.set(path, path);
3857
- snapshot.files.set(path, content);
3858
- entries.push({
3859
- kind: spec.kind,
3860
- path,
3861
- sha256: sha256(content),
3862
- size: content.length
3863
- });
3864
- } else {
3865
- if (spec.kind !== "tree" || typeof spec.path !== "string") throw new Error("Invalid tree input spec");
3866
- const { lexical, canonical: root } = canonicalPath(spec.path, cwd);
3867
- const ignore = normalizeIgnore(spec.ignore);
3868
- const skipDot = normalizeSkipDotNames(spec.skipDotNames);
3869
- const members = /* @__PURE__ */ new Map();
3870
- const files = [];
3871
- for (const rel of listTreeFiles(root, ignore, skipDot)) {
3872
- const content = readTreeFileFromDisk(root, rel);
3873
- members.set(rel, content);
3874
- files.push({
3875
- path: rel,
3876
- sha256: sha256(content),
3877
- size: content.length
3878
- });
3879
- }
3880
- snapshot.treeAliases.set(lexical, root);
3881
- snapshot.treeAliases.set(root, root);
3882
- snapshot.trees.set(treeKey(root, ignore, skipDot), members);
3883
- entries.push({
3884
- kind: "tree",
3885
- path: root,
3886
- ignore,
3887
- ...skipDot ? { skipDotNames: true } : {},
3888
- files
3889
- });
3890
- }
3891
- return {
3892
- entries,
3893
- snapshot
3894
- };
3895
- });
3896
- }
3897
- function sortKey(entry) {
3898
- const id = entry.kind === "ref" ? entry.name : entry.kind === "tree" ? `${entry.path}\0${ignoreKey(entry.ignore, entry.skipDotNames === true)}` : entry.path;
3899
- return `${entry.kind}\0${id}`;
3900
- }
3901
- function canonicalEntries(entries) {
3902
- return entries.map((e) => {
3903
- if (e.kind === "ref") return {
3904
- kind: "ref",
3905
- name: e.name,
3906
- value: e.value
3907
- };
3908
- if (e.kind === "tree") return {
3909
- kind: "tree",
3910
- path: e.path,
3911
- ignore: [...e.ignore],
3912
- ...e.skipDotNames === true ? { skipDotNames: true } : {},
3913
- files: e.files.map((f) => ({
3914
- path: f.path,
3915
- sha256: f.sha256,
3916
- size: f.size
3917
- }))
3918
- };
3919
- return {
3920
- kind: e.kind,
3921
- path: e.path,
3922
- sha256: e.sha256,
3923
- size: e.size
3924
- };
3925
- }).sort((a, b) => {
3926
- const ka = sortKey(a);
3927
- const kb = sortKey(b);
3928
- return ka < kb ? -1 : ka > kb ? 1 : 0;
3929
- });
3930
- }
3931
- function manifestJson(command, entries) {
3932
- return JSON.stringify({
3933
- version: 1,
3934
- command,
3935
- inputs: canonicalEntries(entries)
3936
- });
3937
- }
3938
- //#endregion
3939
- //#region src/inputs/reader.ts
3940
- let activeSnapshot = null;
3941
- function setActiveSnapshot(snapshot) {
3942
- activeSnapshot = snapshot;
3943
- }
3944
- var InputsUndeclaredError = class extends Error {
3945
- constructor(path) {
3946
- super(`Undeclared input read: ${path}`);
3947
- this.name = "InputsUndeclaredError";
3948
- }
3949
- };
3950
- function declaredKey(path, snapshot) {
3951
- const lexical = lexicalPath(path);
3952
- const key = snapshot.aliases.get(lexical) ?? lexical;
3953
- return snapshot.files.has(key) ? key : void 0;
3954
- }
3955
- function bytes(content, encoding) {
3956
- return encoding ? content.toString(encoding) : Buffer.from(content);
3957
- }
3958
- function snapshotTree(rootPath, ignore, skipDot, snapshot) {
3959
- const root = snapshot.treeAliases.get(lexicalPath(rootPath)) ?? rootPath;
3960
- const members = snapshot.trees.get(treeKey(root, ignore, skipDot));
3961
- if (!members) throw new InputsUndeclaredError(rootPath);
3962
- return {
3963
- root,
3964
- members
3965
- };
3966
- }
3967
- function openTree(rootPath, options) {
3968
- const ignore = normalizeIgnore(options?.ignore);
3969
- const skipDot = normalizeSkipDotNames(options?.skipDotNames);
3970
- let disk;
3971
- const fromDisk = () => {
3972
- if (!disk) {
3973
- const root = canonicalPath(rootPath).canonical;
3974
- disk = {
3975
- root,
3976
- known: new Set(listTreeFiles(root, ignore, skipDot))
3977
- };
3978
- }
3979
- return disk;
3980
- };
3981
- if (activeSnapshot) snapshotTree(rootPath, ignore, skipDot, activeSnapshot);
3982
- else fromDisk();
3983
- return {
3984
- get root() {
3985
- return activeSnapshot ? snapshotTree(rootPath, ignore, skipDot, activeSnapshot).root : fromDisk().root;
3986
- },
3987
- list() {
3988
- if (activeSnapshot) return [...snapshotTree(rootPath, ignore, skipDot, activeSnapshot).members.keys()];
3989
- return [...fromDisk().known];
3990
- },
3991
- readFile(rel, encoding) {
3992
- const missing = () => new InputsUndeclaredError(`${rootPath}/${rel}`);
3993
- if (activeSnapshot) {
3994
- const content = snapshotTree(rootPath, ignore, skipDot, activeSnapshot).members.get(rel);
3995
- if (!content) throw missing();
3996
- return bytes(content, encoding);
3997
- }
3998
- const { root, known } = fromDisk();
3999
- if (!known.has(rel)) throw missing();
4000
- return bytes(readTreeFileFromDisk(root, rel), encoding);
4001
- }
4002
- };
4003
- }
4004
- /**
4005
- * The reader behind ctx.inputs. Outside expect mode it reads from disk; once
4006
- * an expect-mode snapshot is active it serves only that snapshot and throws
4007
- * for anything undeclared.
4008
- */
4009
- function createInputsReader() {
4010
- return {
4011
- isExpecting: () => activeSnapshot !== null,
4012
- ref(name) {
4013
- const snapshot = activeSnapshot;
4014
- if (!snapshot) return void 0;
4015
- const value = snapshot.refs.get(name);
4016
- if (value === void 0) throw new InputsUndeclaredError(`ref ${name}`);
4017
- return value;
4018
- },
4019
- tree: openTree,
4020
- readFile(path, encoding) {
4021
- const snapshot = activeSnapshot;
4022
- if (!snapshot) {
4023
- const content = withInternalReads(() => readFileSync(lexicalPath(path)));
4024
- return encoding ? content.toString(encoding) : content;
4025
- }
4026
- const key = declaredKey(path, snapshot);
4027
- const content = key === void 0 ? void 0 : snapshot.files.get(key);
4028
- if (!content) throw new InputsUndeclaredError(path);
4029
- return encoding ? content.toString(encoding) : Buffer.from(content);
4030
- }
4031
- };
4032
- }
4033
- //#endregion
4034
- //#region src/inputs/hook.ts
4035
- const INPUTS_MODE_ENV = "FLUID_INPUTS_MODE";
4036
- const INPUTS_EXPECT_ENV = "FLUID_INPUTS_EXPECT";
4037
- const INPUTS_UNDECLARED_CODE = "inputs_undeclared";
4038
- const INPUTS_UNDECLARED_EXIT = 64;
4039
- const INPUTS_MISMATCH_CODE = "inputs_mismatch";
4040
- const INPUTS_MISMATCH_EXIT = 65;
4041
- function writeAll(fd, text) {
4042
- const buffer = Buffer.from(text);
4043
- let offset = 0;
4044
- while (offset < buffer.length) try {
4045
- offset += writeSync(fd, buffer, offset);
4046
- } catch (error) {
4047
- if (error.code !== "EAGAIN") throw error;
4048
- }
4049
- }
4050
- const processIo = {
4051
- env: process.env,
4052
- stdout: (text) => writeAll(1, text),
4053
- stderr: (text) => writeAll(2, text),
4054
- exit: (code) => process.exit(code)
4055
- };
4056
- function inputsModeActive(env) {
4057
- return env["FLUID_INPUTS_MODE"] !== void 0 || env["FLUID_INPUTS_EXPECT"] !== void 0;
4058
- }
4059
- function commandPath(command) {
4060
- const names = [];
4061
- for (let c = command; c; c = c.parent) names.unshift(c.name());
4062
- return names.join(" ");
4063
- }
4064
- function readManifest(path) {
4065
- try {
4066
- const parsed = JSON.parse(withInternalReads(() => readFileSync(path, "utf8")));
4067
- if (!Array.isArray(parsed.inputs)) return null;
4068
- return {
4069
- version: parsed.version,
4070
- command: parsed.command,
4071
- inputs: canonicalEntries(parsed.inputs)
4072
- };
4073
- } catch {
4074
- return null;
4075
- }
4076
- }
4077
- function inputsPreAction(actionCommand, io = processIo) {
4078
- const mode = io.env[INPUTS_MODE_ENV];
4079
- const expectPath = io.env[INPUTS_EXPECT_ENV];
4080
- setActiveSnapshot(null);
4081
- if (mode === void 0 && expectPath === void 0) return;
4082
- const resolveMode = mode === "resolve";
4083
- if (mode !== void 0 && !resolveMode || expectPath === "" || resolveMode && expectPath !== void 0) {
4084
- io.stderr(`${INPUTS_MISMATCH_CODE}\n`);
4085
- return io.exit(65);
4086
- }
4087
- const resolver = getInputResolver(actionCommand);
4088
- if (!resolver) {
4089
- io.stderr(`${INPUTS_UNDECLARED_CODE}\n`);
4090
- return io.exit(64);
4091
- }
4092
- let resolved;
4093
- try {
4094
- resolved = resolveInputs(resolver(actionCommand.optsWithGlobals(), actionCommand.args));
4095
- } catch (error) {
4096
- if (resolveMode) {
4097
- const message = error instanceof Error ? error.message : String(error);
4098
- io.stderr(`${message}\n`);
4099
- return io.exit(1);
4100
- }
4101
- io.stderr(`${INPUTS_MISMATCH_CODE}\n`);
4102
- return io.exit(65);
4103
- }
4104
- if (resolveMode) {
4105
- io.stdout(`${manifestJson(commandPath(actionCommand), resolved.entries)}\n`);
4106
- return io.exit(0);
4107
- }
4108
- const expected = readManifest(expectPath);
4109
- if (!expected || expected.version !== 1 || expected.command !== commandPath(actionCommand) || JSON.stringify(expected.inputs) !== JSON.stringify(canonicalEntries(resolved.entries))) {
4110
- io.stderr(`${INPUTS_MISMATCH_CODE}\n`);
4111
- return io.exit(65);
4112
- }
4113
- setActiveSnapshot(resolved.snapshot);
4114
- }
4115
- /**
4116
- * Registers the inputs preAction hook. Register it before any credential
4117
- * hook.
4118
- */
4119
- function registerInputsHook(program, io = processIo) {
4120
- program.hook("preAction", (_program, actionCommand) => {
4121
- inputsPreAction(actionCommand, io);
4122
- });
4123
- }
4124
- /**
4125
- * Maps an undeclared read in expect mode to the fixed undeclared exit; any
4126
- * other error is returned to the caller untouched.
4127
- */
4128
- function exitOnInputsError(error, io = processIo) {
4129
- if (!(error instanceof InputsUndeclaredError)) return;
4130
- io.stderr(`${INPUTS_UNDECLARED_CODE}\n`);
4131
- io.exit(64);
4132
- }
4133
- //#endregion
4134
- export { sendMfa as $, signInWithBrowser as A, getConfigDir as B, endUnusedSessions as C, primeIdentityProfile as D, isRoleNotGrantedError as E, resolveIdentityUrl as F, isClientProfile as G, ApiError as H, readConfig as I, SIGNUP_ERROR as J, isIdentityProfile as K, updateConfig as L, clientAccessToken as M, invalidateClientToken as N, profileAccessToken as O, primeClientProfile as P, redeemIdentityLink as Q, writeConfig as R, findProjectConfig as S, identityToken as T, createFetchClient as U, getConfigFilePath as V, createDefaultConfig as W, fetchUserCompanies as X, confirmMfa as Y, getFluidApiBase as Z, getAuthToken as _, rootCommand as _t, INPUTS_UNDECLARED_CODE as a, isError as at, listProfileNames as b, walkCommands as bt, inputsModeActive as c, isSuccess as ct, setActiveSnapshot as d, success as dt, signup as et, inInternalRead as f, tryCatch as ft, getActiveProfile as g, filterCatalog as gt, declareInputs as h, unwrapOr as ht, INPUTS_MODE_ENV as i, getErrorMessage$1 as it, signOutIdentity as j, sessionFacts as k, registerInputsHook as l, mapError as lt, withInternalReadsAsync as m, unwrap as mt, INPUTS_MISMATCH_CODE as n, validateToken as nt, INPUTS_UNDECLARED_EXIT as o, isFailure as ot, withInternalReads as p, tryCatchAsync as pt, FLUID_API_ERROR as q, INPUTS_MISMATCH_EXIT as r, failure as rt, exitOnInputsError as s, isNodeError as st, INPUTS_EXPECT_ENV as t, switchCompany as tt, createInputsReader as u, mapResult as ut, getAuthTokenAsync as v, visibleOptions as vt, describeIdentityError as w, resolveCredentialSource as x, describeCommand as xt, getRoleAuthTokenAsync as y, visibleSubcommands as yt, isStrictConfig as z };
2928
+ export { isClientProfile as A, writeConfig as C, ApiError as D, getConfigFilePath as E, createFetchClient as O, updateConfig as S, getConfigDir as T, primeClientProfile as _, peekIdentityToken as a, readConfig as b, sessionFacts as c, OrphanedClientSecretError as d, ProfileExistsError as f, peekClientToken as g, invalidateClientToken as h, isRoleNotGrantedError as i, isIdentityProfile as j, createDefaultConfig as k, signInWithBrowser as l, deleteClientSecret as m, describeIdentityError as n, primeIdentityProfile as o, clientAccessToken as p, identityToken as r, profileAccessToken as s, endUnusedSessions as t, signOutIdentity as u, saveClientProfile as v, isStrictConfig as w, readStoredConfig as x, resolveIdentityUrl as y };
4135
2929
 
4136
- //# sourceMappingURL=hook-CV4vUh4j.mjs.map
2930
+ //# sourceMappingURL=profiles-CpG6O9Zi.mjs.map