@fluid-app/fluid-cli 0.1.120 → 0.1.121

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,6 +8,34 @@ The Fluid Commerce CLI. Provides authentication, profile management, and a plugi
8
8
  npm install -g @fluid-app/fluid-cli
9
9
  ```
10
10
 
11
+ ## Sign up
12
+
13
+ `fluid signup` creates a company with Fluid's public signup, before any
14
+ sign-in:
15
+
16
+ ```bash
17
+ fluid signup --email maya@acme.test --first-name Maya --last-name Lee \
18
+ --company-name "Acme" --subdomain acme --yes --json
19
+ ```
20
+
21
+ It sends the subdomain in the form the server stores (lowercase letters,
22
+ digits and hyphens, at most 63), prints the company's `fluidShop`, and the
23
+ two `fluid login` steps below that sign in to it. The second step saves the
24
+ sign-in under a profile named after the subdomain (`--name`), so it never
25
+ silently replaces a profile you already have. Fluid emails the address a link to
26
+ confirm the signup; signing in with the emailed code confirms it too.
27
+
28
+ It sends one request and never retries it: every attempt, failed or not,
29
+ counts toward the signup limits (per IP address and per email), and a
30
+ failure can come after the company was saved. Errors say which case
31
+ applies: `SUBDOMAIN_TAKEN`, `SIGNUP_MAY_EXIST` (run the same command once
32
+ more; a taken subdomain then means it exists), `RATE_LIMITED` (with
33
+ `retryAfter` in seconds), `SIGNUP_FORBIDDEN` or `SIGNUP_OUTCOME_UNKNOWN`.
34
+ A second signup for the same email within an hour normally sends no new
35
+ email. Without `--yes` it asks at a terminal, and refuses when there is no
36
+ terminal or with `--json`, which prints one object (`status` is
37
+ `signed_up` or `error`).
38
+
11
39
  ## Authentication
12
40
 
13
41
  ```bash
@@ -46,8 +74,8 @@ echo 123456 | fluid login --code - --email maya@acme.test --yes
46
74
  ```
47
75
 
48
76
  Step 1 needs `--shop`: the code is tied to that company, and only such a
49
- code confirms a new signup (the signup response names the shop as
50
- `fluid_shop`). Step 2 signs in to the same company; a `--shop` given there
77
+ code confirms a new signup (`fluid signup` prints the shop as
78
+ `fluidShop`; the API's signup response names it `fluid_shop`). Step 2 signs in to the same company; a `--shop` given there
51
79
  must match it.
52
80
 
53
81
  The code expires after 30 minutes, and five wrong codes lock it. Step 1
@@ -95,6 +123,7 @@ Install plugins alongside the core CLI to add commands:
95
123
  | `@fluid-app/fluid-cli-themes` | `fluid themes *` | Theme management API commands |
96
124
  | `@fluid-app/fluid-cli-assets` | `fluid assets *` | Digital asset management commands |
97
125
  | `@fluid-app/fluid-cli-droplets` | `fluid droplets *` | Droplet management commands, including `install`, `uninstall` and `installed` |
126
+ | `@fluid-app/fluid-cli-products` | `fluid products *` | Create a priced catalog product |
98
127
 
99
128
  Example:
100
129
 
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { A as validateToken, C as FLUID_API_ERROR, D as redeemIdentityLink, E as getFluidApiBase, G as rootCommand, J as walkCommands, K as visibleOptions, O as sendMfa, S as isIdentityProfile, T as fetchUserCompanies, W as filterCatalog, _ as signInWithBrowser, a as resolveCredentialSource, c as updateConfig, f as describeIdentityError, g as sessionFacts, k as switchCompany, l as writeConfig, m as primeIdentityProfile, n as getAuthToken, p as identityToken, q as visibleSubcommands, s as readConfig, t as getActiveProfile, u as getConfigDir, v as signOutIdentity, w as confirmMfa, y as resolveIdentityUrl } from "../token-iab-DgX4.mjs";
2
+ import { A as signup, C as FLUID_API_ERROR, D as getFluidApiBase, E as fetchUserCompanies, J as visibleOptions, K as filterCatalog, M as validateToken, O as redeemIdentityLink, S as isIdentityProfile, T as confirmMfa, X as walkCommands, Y as visibleSubcommands, _ as signInWithBrowser, a as resolveCredentialSource, c as updateConfig, f as describeIdentityError, g as sessionFacts, j as switchCompany, k as sendMfa, l as writeConfig, m as primeIdentityProfile, n as getAuthToken, p as identityToken, q as rootCommand, s as readConfig, t as getActiveProfile, u as getConfigDir, v as signOutIdentity, y as resolveIdentityUrl } from "../token-C0rW9D-J.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -402,6 +402,16 @@ function createIdentityProfile({ name, companyName, baseUrl, auth, storedAt }) {
402
402
  };
403
403
  }
404
404
  //#endregion
405
+ //#region src/utils/shell.ts
406
+ const SHELL_SAFE = /^[\w@+][\w.@+-]*$/;
407
+ /**
408
+ * The value for a printed command, or the placeholder when it holds
409
+ * characters a shell would act on.
410
+ */
411
+ function shellSafe(value, placeholder) {
412
+ return SHELL_SAFE.test(value) ? value : placeholder;
413
+ }
414
+ //#endregion
405
415
  //#region src/commands/login-identity.ts
406
416
  /**
407
417
  * `fluid login` for a company on the identity sign-in path: the browser,
@@ -815,14 +825,12 @@ function expiryNote(expiresAtIso) {
815
825
  const expiresInMin = Math.round(expiresInMs / 1e3 / 60);
816
826
  return expiresInMin > 0 ? `expires in ~${expiresInMin} min` : "code may expire soon — check your email quickly";
817
827
  }
818
- const SHELL_SAFE = /^[\w.@+-]+$/;
819
828
  /**
820
829
  * The command that finishes this sign-in, for a person or agent to run.
821
830
  * Values with characters a shell would act on are left as placeholders.
822
831
  */
823
832
  function finishCommand(email, shop) {
824
- const safe = (value, placeholder) => SHELL_SAFE.test(value) ? value : placeholder;
825
- return `fluid login --code --email ${safe(email, "<email>")} --shop ${safe(shop, "<shop>")}`;
833
+ return `fluid login --code --email ${shellSafe(email, "<email>")} --shop ${shellSafe(shop, "<shop>")}`;
826
834
  }
827
835
  /** `fluid login --send-code`: email a code, save the sign-in, exit. */
828
836
  async function sendCodeStep(opts, ui, deps) {
@@ -832,7 +840,7 @@ async function sendCodeStep(opts, ui, deps) {
832
840
  });
833
841
  if (!opts.shop) return ui.fail({
834
842
  code: "SHOP_REQUIRED",
835
- message: "--send-code needs --shop <shop>, the company to sign in to (acme or acme.fluid.app). A new signup's response names it as fluid_shop."
843
+ message: "--send-code needs --shop <shop>, the company to sign in to (acme or acme.fluid.app). For a new signup, `fluid signup` prints it as fluidShop."
836
844
  });
837
845
  const email = normaliseEmail(opts.email);
838
846
  const shop = opts.shop;
@@ -1017,6 +1025,166 @@ function buildLoginCommand(run = (opts) => runLogin(opts)) {
1017
1025
  }
1018
1026
  const loginCommand = buildLoginCommand();
1019
1027
  //#endregion
1028
+ //#region src/commands/signup.ts
1029
+ /**
1030
+ * fluid signup — create a Fluid company with the public signup endpoint
1031
+ *
1032
+ * Runs before any sign-in, so it calls `POST /api/company` directly rather
1033
+ * than through a profile's client. The person behind the email then
1034
+ * confirms the signup, by the emailed link or by signing in with the two
1035
+ * `fluid login` steps this command prints.
1036
+ */
1037
+ const defaultSignupDeps = {
1038
+ api: { signup },
1039
+ prompt: (question) => prompts(question),
1040
+ spinner: (text) => ora(text).start(),
1041
+ log: (line) => console.log(line),
1042
+ isInteractive: () => Boolean(process.stdin.isTTY)
1043
+ };
1044
+ const SUBDOMAIN_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
1045
+ const COLOR_PATTERN = /^(?:[a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/;
1046
+ const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+$/;
1047
+ /**
1048
+ * The subdomain as the server would store it: lowercase, letters, digits
1049
+ * and hyphens only, at most 63 characters, no hyphen at either end. The
1050
+ * server checks "is taken" against the value as sent, before it cleans it
1051
+ * up, so sending the clean form keeps that check meaningful.
1052
+ */
1053
+ function normaliseSubdomain(raw) {
1054
+ const trimmed = (value) => value.replace(/^-+|-+$/g, "");
1055
+ return trimmed(trimmed(raw.toLowerCase()).replace(/[^a-z0-9-]/g, "").slice(0, 63));
1056
+ }
1057
+ /**
1058
+ * The two commands that sign in to the new company and confirm it. The
1059
+ * second names its own profile rather than passing `--yes`, which would
1060
+ * replace an existing profile that happens to share the company's name.
1061
+ * If a profile with that name exists, login refuses `--name` before the code
1062
+ * is spent when there is no terminal, and asks first at one.
1063
+ */
1064
+ function nextCommands(email, fluidShop, subdomain) {
1065
+ const safeEmail = shellSafe(email, "<email>");
1066
+ const safeShop = shellSafe(fluidShop, "<shop>");
1067
+ return [`fluid login --send-code --email ${safeEmail} --shop ${safeShop}`, `fluid login --code --email ${safeEmail} --shop ${safeShop} --name ${shellSafe(subdomain, "<profile>")}`];
1068
+ }
1069
+ const REQUIRED_FLAGS = [
1070
+ ["email", "--email"],
1071
+ ["firstName", "--first-name"],
1072
+ ["lastName", "--last-name"],
1073
+ ["companyName", "--company-name"],
1074
+ ["subdomain", "--subdomain"]
1075
+ ];
1076
+ /** The request to send, or why the flags can't make one. */
1077
+ function buildRequest(opts) {
1078
+ const missing = REQUIRED_FLAGS.filter(([key]) => {
1079
+ const value = opts[key];
1080
+ return typeof value !== "string" || value.trim() === "";
1081
+ }).map(([, flag]) => flag);
1082
+ if (missing.length > 0) return { error: {
1083
+ code: "FLAGS_REQUIRED",
1084
+ message: `fluid signup needs ${missing.join(", ")}.`
1085
+ } };
1086
+ const email = normaliseEmail(opts.email ?? "");
1087
+ if (!EMAIL_PATTERN.test(email)) return { error: {
1088
+ code: "INVALID_EMAIL",
1089
+ message: `${email} is not an email address.`
1090
+ } };
1091
+ const subdomain = normaliseSubdomain(opts.subdomain ?? "");
1092
+ if (!SUBDOMAIN_PATTERN.test(subdomain)) return { error: {
1093
+ code: "INVALID_SUBDOMAIN",
1094
+ message: "--subdomain needs at least one letter or digit; it may also hold hyphens, up to 63 characters."
1095
+ } };
1096
+ const color = opts.color?.trim().replace(/^#/, "");
1097
+ if (color !== void 0 && !COLOR_PATTERN.test(color)) return { error: {
1098
+ code: "INVALID_COLOR",
1099
+ message: "--color must be a 3- or 6-digit hex colour, such as 0C7CF6."
1100
+ } };
1101
+ return { request: {
1102
+ email,
1103
+ firstName: (opts.firstName ?? "").trim(),
1104
+ lastName: (opts.lastName ?? "").trim(),
1105
+ companyName: (opts.companyName ?? "").trim(),
1106
+ subdomain,
1107
+ ...color ? { color } : {}
1108
+ } };
1109
+ }
1110
+ function printFailure(error, json, deps) {
1111
+ if (json) {
1112
+ deps.log(JSON.stringify({
1113
+ status: "error",
1114
+ code: error.code,
1115
+ message: error.message,
1116
+ ...error.status !== void 0 ? { httpStatus: error.status } : {},
1117
+ ...error.errors ? { errors: error.errors } : {},
1118
+ ...error.retryAfter !== void 0 ? { retryAfter: error.retryAfter } : {},
1119
+ ...error.details ? { details: error.details } : {}
1120
+ }, null, 2));
1121
+ return 1;
1122
+ }
1123
+ deps.log(chalk.red(error.message));
1124
+ if (error.errors) deps.log(chalk.dim(JSON.stringify(error.errors)));
1125
+ if (error.retryAfter !== void 0) deps.log(chalk.dim(`Retry after ${error.retryAfter} seconds.`));
1126
+ if (error.details) deps.log(chalk.dim(error.details));
1127
+ return 1;
1128
+ }
1129
+ /**
1130
+ * Run `fluid signup` and return its exit code.
1131
+ */
1132
+ async function runSignup(opts, deps = defaultSignupDeps) {
1133
+ const json = Boolean(opts.json);
1134
+ const built = buildRequest(opts);
1135
+ if ("error" in built) return printFailure(built.error, json, deps);
1136
+ const { request } = built;
1137
+ if (!opts.yes) {
1138
+ const question = `Create ${request.companyName} at subdomain ${request.subdomain}, and email ${request.email} to confirm it?`;
1139
+ if (json || !deps.isInteractive()) return printFailure({
1140
+ code: "CONFIRM_REQUIRED",
1141
+ message: `${question} Pass --yes to confirm.`
1142
+ }, json, deps);
1143
+ if (!(await deps.prompt({
1144
+ type: "confirm",
1145
+ name: "ok",
1146
+ message: question,
1147
+ initial: false
1148
+ }))["ok"]) return printFailure({
1149
+ code: "CANCELLED",
1150
+ message: "Cancelled."
1151
+ }, json, deps);
1152
+ }
1153
+ const spinner = json ? void 0 : deps.spinner("Signing up...");
1154
+ const result = await deps.api.signup(request);
1155
+ spinner?.stop();
1156
+ if (!result.success) return printFailure(result.error, json, deps);
1157
+ const created = result.value;
1158
+ const next = nextCommands(request.email, created.company.fluidShop, created.company.subdomain);
1159
+ if (json) {
1160
+ deps.log(JSON.stringify({
1161
+ status: "signed_up",
1162
+ company: created.company,
1163
+ userCompany: created.userCompany,
1164
+ currentlyDue: created.currentlyDue,
1165
+ next
1166
+ }, null, 2));
1167
+ return 0;
1168
+ }
1169
+ deps.log(chalk.green(`Signed up ${created.company.name} as ${created.company.fluidShop} (company ${created.company.id}).`));
1170
+ if (request.subdomain !== (opts.subdomain ?? "").trim()) deps.log(chalk.dim(`Subdomain sent as ${request.subdomain}.`));
1171
+ deps.log(`${request.email} confirms it from the emailed link, or by signing in with the emailed code:`);
1172
+ for (const command of next) deps.log(` ${command}`);
1173
+ deps.log(chalk.dim("A repeat signup for the same email within an hour normally sends no new email."));
1174
+ return 0;
1175
+ }
1176
+ /**
1177
+ * The `signup` command, running `run` with the parsed options. Built by a
1178
+ * function so a test can check the flag parsing without signing up.
1179
+ */
1180
+ function buildSignupCommand(run = (opts) => runSignup(opts)) {
1181
+ return new Command("signup").description("Create a Fluid company with the public signup; the person behind --email confirms it").option("-e, --email <email>", "The person's email address; Fluid emails it to confirm the signup").option("--first-name <name>", "The person's first name").option("--last-name <name>", "The person's last name").option("--company-name <name>", "The company's name").option("--subdomain <subdomain>", "The store's subdomain (acme gives acme.fluid.app); sent lowercase, letters, digits and hyphens only").option("--color <hex>", "Brand colour as 3 or 6 hex digits, such as 0C7CF6").option("-y, --yes", "Sign up without asking").option("--json", "Print the result as JSON").action(async (opts) => {
1182
+ const exitCode = await run(opts);
1183
+ if (exitCode !== 0) process.exitCode = exitCode;
1184
+ });
1185
+ }
1186
+ const signupCommand = buildSignupCommand();
1187
+ //#endregion
1020
1188
  //#region src/commands/logout.ts
1021
1189
  /**
1022
1190
  * fluid logout — remove stored auth profile(s)
@@ -1824,6 +1992,7 @@ if (process.argv[2] === "__refresh-update-check") {
1824
1992
  const packageRoot = process.cwd();
1825
1993
  const program = new Command();
1826
1994
  program.name("fluid").description("Fluid Commerce CLI").version(version);
1995
+ program.addCommand(signupCommand);
1827
1996
  program.addCommand(loginCommand);
1828
1997
  program.addCommand(logoutCommand);
1829
1998
  program.addCommand(whoamiCommand);
@@ -1832,6 +2001,7 @@ program.addCommand(commandsCommand);
1832
2001
  program.addCommand(completionCommand);
1833
2002
  program.addCommand(completeCommand, { hidden: true });
1834
2003
  const selfAuthenticating = new Set([
2004
+ signupCommand,
1835
2005
  loginCommand,
1836
2006
  logoutCommand,
1837
2007
  whoamiCommand,