@hygraph/cli 0.0.12 → 0.0.13

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
@@ -30,6 +30,10 @@ The CLI needs a permanent auth token from your project's settings in Studio:
30
30
  - a **permanent auth token** **(PAT)**
31
31
  - Create one in **Project Settings > Permanent Auth Tokens > Add token**
32
32
  - Then enable all management permissions for it
33
+ - Or use **Generate CLI PAT** on the same page. It creates a token with the
34
+ management permissions the CLI needs and no content access. The button
35
+ is not on for every project yet. Ask Hygraph support to turn it on for
36
+ your project.
33
37
  - Put the token in the `HYGRAPH_TOKEN` environment variable. The config
34
38
  reads it from there, so the token never ends up in a file you commit.
35
39
 
@@ -37,23 +41,41 @@ The CLI needs a permanent auth token from your project's settings in Studio:
37
41
  export HYGRAPH_TOKEN="…"
38
42
  ```
39
43
 
44
+ If it is not set and you run `export` in a terminal, `export` asks for
45
+ the token in a hidden prompt. Without a terminal, such as in CI, set the
46
+ variable. `plan`, `apply`, `pull` and `whoami` always need it.
47
+
40
48
  ## Start from your project
41
49
 
42
50
  `export` writes your project's current schema as a config file:
43
51
 
44
52
  ```bash
45
- npx hygraph export --project <project-id> --endpoint <endpoint> --out hygraph.config.ts
53
+ npx hygraph export
46
54
  ```
47
55
 
48
- To run the `export` command, you need to provide the project ID and endpoint.
49
-
50
- - Find the **project ID** in **Project Settings > Project**
51
- - The project's **Management API endpoint**
52
- - Find it in **Project Settings > Endpoints > Management API**, such as
53
- `https://management-eu-central-1.hygraph.com/graphql`
54
-
55
- After running the `export` command, you can check the exported `master`
56
- environment in the `hygraph.config.ts` file.
56
+ `export` reads the project's Management API endpoint, the project and the
57
+ environment from the token, and prints what it found. A flag takes
58
+ precedence over the token:
59
+
60
+ - `--endpoint`: the project's **Management API endpoint**, from **Project
61
+ Settings > Endpoints > Management API**, such as
62
+ `https://management-eu-central-1.hygraph.com/graphql`. Give it when
63
+ `export` says that the token does not name its endpoint, for example for an
64
+ older token or a local stack.
65
+ - `--project`: the **project ID**, from **Project Settings > Project**.
66
+ - `--environment`: the environment to export. Without it and without one in
67
+ the token, `export` exports `master`.
68
+
69
+ In a terminal, `export` asks for each value that no flag or the token gives,
70
+ and shows the default in brackets.
71
+
72
+ `--out` names the file to write. Without it, `export` asks for the file in a
73
+ terminal, with `hygraph.config.ts` as the default. When stdout is not a
74
+ terminal, such as `npx hygraph export > hygraph.config.ts`, it prints the
75
+ config to stdout.
76
+
77
+ After running the `export` command, you can check the exported environment in
78
+ the `hygraph.config.ts` file.
57
79
 
58
80
  Then run the `plan` command. It should show no changes, because the current
59
81
  config matches your project:
package/dist/cli.js CHANGED
@@ -10,6 +10,7 @@ import { stripVTControlCharacters } from "node:util";
10
10
  import { createInterface } from "node:readline/promises";
11
11
  import { createHash } from "node:crypto";
12
12
  import { createJiti } from "jiti";
13
+ import { Writable } from "node:stream";
13
14
  import { structuredPatch } from "diff";
14
15
  //#region node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
15
16
  /**
@@ -15475,7 +15476,7 @@ var LiveSchemaFailure = class extends Failure {};
15475
15476
  * `models`. Whether Segment exists comes from its system models.
15476
15477
  */
15477
15478
  async function readLiveEnvironment(target, fetch) {
15478
- if (isEmpty(target.token)) throw new LiveSchemaFailure(`target "${target.name}" has no token`);
15479
+ if (isEmpty(target.token)) throw new LiveSchemaFailure(`target "${target.name}" has no token. An exported config reads it from HYGRAPH_TOKEN.`);
15479
15480
  const client = createManagementClient({
15480
15481
  endpoint: target.endpoint,
15481
15482
  token: target.token,
@@ -23320,26 +23321,121 @@ function printTarget(target) {
23320
23321
  ])});`;
23321
23322
  }
23322
23323
  //#endregion
23324
+ //#region src/export/token.ts
23325
+ /** Export sends the token to the endpoint, so only these hosts are taken. */
23326
+ const HYGRAPH_DOMAINS = [".hygraph.com", ".hygraph.dev"];
23327
+ function readTokenHints(token) {
23328
+ const claims = decodeClaims(token);
23329
+ if (claims === void 0) return {};
23330
+ return {
23331
+ endpoint: endpointFrom(claims.iss),
23332
+ environment: environmentFrom(claims.aud)
23333
+ };
23334
+ }
23335
+ function decodeClaims(token) {
23336
+ const payload = token.split(".")[1];
23337
+ if (payload === void 0) return;
23338
+ try {
23339
+ const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
23340
+ return typeof claims === "object" && claims !== null ? claims : void 0;
23341
+ } catch {
23342
+ return;
23343
+ }
23344
+ }
23345
+ /**
23346
+ * An https issuer on a Hygraph domain. Tokens copied before management
23347
+ * server signed with its regional URL carry `https://management.graphcms.com/`,
23348
+ * which names no region.
23349
+ */
23350
+ function endpointFrom(iss) {
23351
+ const url = parseUrl(iss);
23352
+ if (url === void 0 || url.protocol !== "https:" || !HYGRAPH_DOMAINS.some((domain) => url.hostname.endsWith(domain))) return;
23353
+ url.pathname = url.pathname.replace(/\/?$/, "/graphql");
23354
+ return url.href;
23355
+ }
23356
+ /** The last path segment of the audience that is a content API URL. */
23357
+ function environmentFrom(aud) {
23358
+ const audiences = Array.isArray(aud) ? aud : [aud];
23359
+ for (const audience of audiences) {
23360
+ const segments = parseUrl(audience)?.pathname.split("/").filter(Boolean);
23361
+ if (segments !== void 0 && segments.length >= 2) return segments.at(-1);
23362
+ }
23363
+ }
23364
+ function parseUrl(value) {
23365
+ if (typeof value !== "string") return;
23366
+ try {
23367
+ return new URL(value);
23368
+ } catch {
23369
+ return;
23370
+ }
23371
+ }
23372
+ //#endregion
23373
+ //#region src/utils/ask.ts
23374
+ /**
23375
+ * Asks once on the terminal and echoes the answer as it is typed.
23376
+ * Undefined when the user stops with Ctrl+C or Ctrl+D.
23377
+ */
23378
+ function ask(question, { input, write }) {
23379
+ return readLine(question, input, writable(write));
23380
+ }
23381
+ /**
23382
+ * Asks once on the terminal and shows nothing of the answer, not even `*`.
23383
+ * Readline puts a terminal into raw mode and echoes into an output that
23384
+ * discards everything. Undefined when the user stops with Ctrl+C or Ctrl+D.
23385
+ */
23386
+ async function askSecret(question, { input, write }) {
23387
+ write(question);
23388
+ try {
23389
+ return await readLine("", input, writable(() => {}));
23390
+ } finally {
23391
+ write("\n");
23392
+ }
23393
+ }
23394
+ async function readLine(question, input, output) {
23395
+ const readline = createInterface({
23396
+ input,
23397
+ output,
23398
+ terminal: true
23399
+ });
23400
+ const stop = new AbortController();
23401
+ readline.on("SIGINT", () => stop.abort());
23402
+ readline.on("close", () => stop.abort());
23403
+ try {
23404
+ return await readline.question(question, { signal: stop.signal });
23405
+ } catch {
23406
+ return;
23407
+ } finally {
23408
+ readline.close();
23409
+ }
23410
+ }
23411
+ function writable(write) {
23412
+ return new Writable({ write(chunk, _encoding, callback) {
23413
+ write(chunk.toString());
23414
+ callback();
23415
+ } });
23416
+ }
23417
+ //#endregion
23323
23418
  //#region src/commands/export.ts
23324
23419
  /** What only export can find out is wrong. The command prints it and exits 1. */
23325
23420
  var ExportFailure = class extends Failure {};
23326
23421
  function registerExport(program) {
23327
- program.command("export").description("write a live environment out as TypeScript").requiredOption("--project <id>", "project to export").requiredOption("--endpoint <url>", "the project's management API endpoint").option("--environment <name>", "environment to export", "master").option("--name <name>", "target name in the config (default: the environment)").option("--out <file>", "write to a file instead of stdout").option("--no-color", "print without colours").action(async function(options) {
23422
+ program.command("export").description("write a live environment out as TypeScript").option("--project <id>", "project to export (default: the token's)").option("--endpoint <url>", "the project's management API endpoint (default: the token's)").option("--environment <name>", "environment to export (default: the token's, else master)").option("--name <name>", "target name in the config (default: the environment)").option("--out <file>", "write to a file instead of stdout").option("--no-color", "print without colours").action(async function(options) {
23328
23423
  const write = (text) => this.configureOutput().writeOut?.(text);
23329
23424
  const writeErr = (text) => this.configureOutput().writeErr?.(text);
23330
23425
  try {
23331
- const { config, environment } = await exportEnvironment(options);
23426
+ const input = await readInput(options, writeErr);
23427
+ const { config, environment } = await exportEnvironment(input);
23332
23428
  const headers = renderHeaderNote(remoteHeaderEnvNames(environment)) + renderSecretNote(oAuthSecretEnvNames(environment));
23333
- if (options.out === void 0) {
23429
+ if (input.out === void 0) {
23334
23430
  write(config);
23335
- writeErr(headers);
23431
+ writeErr(headers + (input.tokenTyped ? "\nThe config reads the token from HYGRAPH_TOKEN. Set it before you run plan.\n" : ""));
23336
23432
  return;
23337
23433
  }
23338
- writeConfigFile(config, options.out);
23434
+ writeConfigFile(config, input.out);
23339
23435
  const colors = import_picocolors.default.createColors(options.color && import_picocolors.default.isColorSupported);
23340
- write(renderCheck(`wrote ${options.out}`, count(environment), colors));
23436
+ write(renderCheck(`wrote ${input.out}`, count(environment), colors));
23341
23437
  write(headers);
23342
- write(`\nRun \`hygraph plan ${options.out}\` next. It should show no changes.\n`);
23438
+ write(input.tokenTyped ? `\nSet HYGRAPH_TOKEN to the token, then run \`hygraph plan ${input.out}\`. It should show no changes.\n` : `\nRun \`hygraph plan ${input.out}\` next. It should show no changes.\n`);
23343
23439
  } catch (error) {
23344
23440
  if (error instanceof Failure) this.error(`error: ${error.message}`, {
23345
23441
  exitCode: 1,
@@ -23347,21 +23443,107 @@ function registerExport(program) {
23347
23443
  });
23348
23444
  throw error;
23349
23445
  }
23350
- }).addHelpText("after", examples([["hygraph export --project 19330edb... --endpoint https://...", "print to stdout"], ["hygraph export --project 19330edb... --endpoint https://... --out hygraph.config.ts"]]));
23446
+ }).addHelpText("after", examples([
23447
+ ["hygraph export", "read the endpoint, project and environment from HYGRAPH_TOKEN"],
23448
+ ["hygraph export --out hygraph.config.ts"],
23449
+ ["hygraph export --project 19330edb... --endpoint https://...", "for a token that does not name its endpoint"]
23450
+ ]));
23351
23451
  }
23352
23452
  /**
23353
- * Reads the environment with the token in HYGRAPH_TOKEN and prints it as
23354
- * the config that would plan no changes against it.
23453
+ * The flags first, then what the token says, then on a terminal an answer
23454
+ * for each value still missing, with the default in brackets. The token
23455
+ * comes first because it names the endpoint and the environment, and the
23456
+ * endpoint names the project. A value found this way goes to stderr. A
23457
+ * typed token is used for this run only, and the config goes to a file
23458
+ * only when stdout is a terminal too.
23355
23459
  */
23356
- async function exportEnvironment(options) {
23357
- const token = process.env.HYGRAPH_TOKEN;
23358
- if (isEmpty(token)) throw new ExportFailure(`HYGRAPH_TOKEN is not set. Set it to a permanent auth token of project ${options.project}.`);
23359
- const target$1 = target({
23360
- name: options.name ?? options.environment,
23361
- project: options.project,
23362
- environment: options.environment,
23363
- endpoint: options.endpoint,
23460
+ async function readInput(options, writeErr) {
23461
+ const variable = process.env.HYGRAPH_TOKEN;
23462
+ const terminal = process.stdin.isTTY === true ? {
23463
+ input: process.stdin,
23464
+ write: writeErr
23465
+ } : void 0;
23466
+ let token = variable;
23467
+ if (isEmpty(token)) {
23468
+ if (terminal === void 0) throw new ExportFailure("HYGRAPH_TOKEN is not set. Set it to a permanent auth token of the project.");
23469
+ token = await askRequired("HYGRAPH_TOKEN is not set. Enter a permanent auth token (the input is hidden): ", "no token entered. Set HYGRAPH_TOKEN or enter a permanent auth token.", terminal, askSecret);
23470
+ }
23471
+ const hints = readTokenHints(token);
23472
+ let endpoint = options.endpoint;
23473
+ if (endpoint === void 0 && hints.endpoint !== void 0) {
23474
+ endpoint = hints.endpoint;
23475
+ writeErr(`Endpoint: ${endpoint} (from the token)\n`);
23476
+ }
23477
+ if (endpoint === void 0) {
23478
+ if (terminal === void 0) throw new ExportFailure("the token does not name its management API endpoint. Pass --endpoint <url> (Project Settings > Endpoints).");
23479
+ endpoint = await askRequired("Management API endpoint (Project Settings > Endpoints): ", "no endpoint entered", terminal);
23480
+ }
23481
+ let project = options.project;
23482
+ if (project === void 0) {
23483
+ const found = await tokenProject(endpoint, token);
23484
+ project = found.id;
23485
+ writeErr(`Project: ${found.id} (${found.name})\n`);
23486
+ }
23487
+ let environment = options.environment;
23488
+ if (environment === void 0 && hints.environment !== void 0) {
23489
+ environment = hints.environment;
23490
+ writeErr(`Environment: ${environment} (from the token)\n`);
23491
+ }
23492
+ environment ??= terminal === void 0 ? "master" : await askWithDefault("Environment", "master", terminal);
23493
+ const name = options.name ?? (terminal === void 0 ? environment : await askWithDefault("Target name in the config", environment, terminal));
23494
+ const out = options.out ?? (terminal !== void 0 && process.stdout.isTTY === true ? await askWithDefault("Write the config to", "hygraph.config.ts", terminal) : void 0);
23495
+ return {
23496
+ project,
23497
+ endpoint,
23498
+ environment,
23499
+ name,
23500
+ out,
23364
23501
  token,
23502
+ tokenTyped: isEmpty(variable)
23503
+ };
23504
+ }
23505
+ /** The project the token belongs to, as the management API answers. */
23506
+ async function tokenProject(endpoint, token) {
23507
+ let result;
23508
+ try {
23509
+ result = await createManagementClient({
23510
+ endpoint,
23511
+ token
23512
+ }).request(WhoamiDocument);
23513
+ } catch (error) {
23514
+ throw new ExportFailure(describeManagementError(error, endpoint));
23515
+ }
23516
+ const { viewer } = result;
23517
+ if (viewer.__typename !== "TokenViewer") throw new ExportFailure(`the token is a ${viewer.__typename}, not a permanent auth token`);
23518
+ if (!viewer.project) throw new ExportFailure("the token's project could not be read");
23519
+ return viewer.project;
23520
+ }
23521
+ async function askRequired(question, whenEmpty, terminal, prompt = ask) {
23522
+ const answer = await answerTo(question, terminal, prompt);
23523
+ if (answer === "") throw new ExportFailure(whenEmpty);
23524
+ return answer;
23525
+ }
23526
+ async function askWithDefault(question, fallback, terminal) {
23527
+ const answer = await answerTo(`${question} [${fallback}]: `, terminal, ask);
23528
+ return answer === "" ? fallback : answer;
23529
+ }
23530
+ /** The trimmed answer; Ctrl+C or Ctrl+D stops the command. */
23531
+ async function answerTo(question, terminal, prompt) {
23532
+ const answer = await prompt(question, terminal);
23533
+ if (answer === void 0) throw new ExportFailure("stopped, nothing was exported");
23534
+ return answer.trim();
23535
+ }
23536
+ /**
23537
+ * Reads the environment with the token and prints it as the config that
23538
+ * would plan no changes against it.
23539
+ */
23540
+ async function exportEnvironment(input) {
23541
+ const target$1 = target({
23542
+ name: input.name,
23543
+ project: input.project,
23544
+ environment: input.environment,
23545
+ endpoint: input.endpoint,
23546
+ token: input.token,
23365
23547
  apply: environment({
23366
23548
  locales: [],
23367
23549
  stages: [stage.draft(), stage.published()],
@@ -23645,7 +23827,7 @@ async function whoamiEach(targets, { write, writeErr }, fetch) {
23645
23827
  }
23646
23828
  /** Resolves the target's token against its management API and describes it. */
23647
23829
  async function whoami(target, fetch) {
23648
- if (isEmpty(target.token)) throw new WhoamiFailure(`target "${target.name}" has no token`);
23830
+ if (isEmpty(target.token)) throw new WhoamiFailure(`target "${target.name}" has no token. An exported config reads it from HYGRAPH_TOKEN.`);
23649
23831
  const client = createManagementClient({
23650
23832
  endpoint: target.endpoint,
23651
23833
  token: target.token,
package/dist/version.js CHANGED
@@ -1,4 +1,4 @@
1
1
  //#region src/version.ts
2
- const VERSION = "0.0.12";
2
+ const VERSION = "0.0.13";
3
3
  //#endregion
4
4
  export { VERSION as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hygraph/cli",
3
- "version": "0.0.12",
3
+ "version": "0.0.13",
4
4
  "description": "Manage your Hygraph schema as code",
5
5
  "license": "MIT",
6
6
  "author": "Hygraph GmbH",