@theholocron/cli 5.0.0-alpha.411 → 5.0.0-alpha.413

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/dist/cli.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  import { createRequire } from "node:module";
3
3
  import { homedir, tmpdir } from "node:os";
4
4
  import path, { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
- import { PREFIX, createEnvLookup, firstEnv, holocronEnv } from "@theholocron/env-utils/lookup";
5
+ import { PREFIX, createEnvLookup, detectEnvironment, firstEnv, holocronEnv } from "@theholocron/env-utils/lookup";
6
6
  import { ProviderApiError, ProviderApiError as ProviderApiError$1, createRestClient, onRetry } from "@theholocron/http-client";
7
7
  import { addGlobalOptions, groupMenu, tokenContext } from "@theholocron/kyber/flags";
8
8
  import { checkForUpdates } from "@theholocron/kyber/notifier";
@@ -40,6 +40,13 @@ import { ADR_DIR, ADR_STATUSES, CLOSED_STATUSES, SPEC_DIRS, SPEC_STATUSES, WITHD
40
40
  import { loadConfigPath } from "@theholocron/datapad";
41
41
  import { fetchLatestFromNpm, runUpgradeNode } from "@theholocron/astromech/upgrade";
42
42
  import { lintCommitMsgFile } from "@theholocron/astromech/lint";
43
+ // src/credentials-environments/derives-environment/derives-environment.ts
44
+ /** The providers whose `credentials` entry may leave `environment` out and have it derived (#2063). */
45
+ const DERIVING = /* @__PURE__ */ new Set(["1password"]);
46
+ /** Whether a `credentials` provider with no `environment` option derives its Environment names. */
47
+ function derivesEnvironment(provider) {
48
+ return DERIVING.has(provider);
49
+ }
43
50
  // src/plugin/capabilities/capabilities.ts
44
51
  /** How many providers each capability resolves to: one (`"single"`) or several active at once (`"many"`). */
45
52
  const CARDINALITY = {
@@ -316,7 +323,7 @@ function resolveConfig(raw) {
316
323
  if (credentialsEntry?.cardinality === "many") for (const tuple of credentialsEntry.tuples) {
317
324
  const own = tuple.options.environment;
318
325
  if (own !== void 0 && (typeof own !== "string" || own.trim() === "")) throw new ConfigError$1(`the \`environment\` option of the \`${tuple.provider}\` credentials provider must be the name of an environment, got an empty value`);
319
- if (credentialsEnvironment(tuple, raw) === void 0) throw new ConfigError$1(`the \`${tuple.provider}\` credentials provider has no environment to read: give it an \`environment\` option or set \`credentials.environment\``);
326
+ if (credentialsEnvironment(tuple, raw) === void 0 && !derivesEnvironment(tuple.provider)) throw new ConfigError$1(`the \`${tuple.provider}\` credentials provider has no environment to read: give it an \`environment\` option or set \`credentials.environment\``);
320
327
  }
321
328
  const homepage = raw.homepage ?? (docs?.domain ? `https://${docs.domain}/` : void 0);
322
329
  return {
@@ -1006,6 +1013,103 @@ function applyResolvedConfig(argv, resolved) {
1006
1013
  buildCliLogger(argv, cliLoggerOpts(argv, resolved));
1007
1014
  applyConfig(resolved.telemetry);
1008
1015
  }
1016
+ // src/credentials-environments/environment-layers/environment-layers.ts
1017
+ /** The suffix each layer's Environment carries: `<org/repo> - <suffix>`. `test` has none. */
1018
+ const SUFFIX = {
1019
+ local: "local",
1020
+ development: "dev",
1021
+ ci: "ci",
1022
+ production: "prod"
1023
+ };
1024
+ /**
1025
+ * The Environments a layer reads, in the order they are tried (#2063, #2058). A machine (`local`) reads
1026
+ * `<slug> - local` and then `<slug> - dev`: that is the only fallback there is. `development` reads `- dev`, `ci`
1027
+ * reads `- ci` and `production` reads `- prod`; a missing name is a missing name. `test` reads none. Only `- local`
1028
+ * is optional.
1029
+ */
1030
+ function environmentLayers(slug, layer) {
1031
+ if (layer === "test") return [];
1032
+ const candidate = (suffix, optional) => ({
1033
+ name: `${slug} - ${suffix}`,
1034
+ optional,
1035
+ legacy: false
1036
+ });
1037
+ return layer === "local" ? [candidate(SUFFIX.local, true), candidate(SUFFIX.development, false)] : [candidate(SUFFIX[layer], false)];
1038
+ }
1039
+ // src/credentials-environments/repo-slug/repo-slug.ts
1040
+ /**
1041
+ * The `<org>/<repo>` of the repository at `cwd`, from its `origin` remote. A remote that is missing or cannot be
1042
+ * parsed is a `ConfigError` that names the `environment` option as the fix.
1043
+ */
1044
+ async function repoSlug(cwd, exec) {
1045
+ const remote = await readGitRemote(cwd, exec ? { exec } : {});
1046
+ if (!remote) throw new ConfigError(`cannot derive the 1Password Environment name: the \`origin\` remote of ${cwd} is missing or not an owner/repo URL. Give the \`credentials\` provider an \`environment\` option to name it.`);
1047
+ return remote.slug;
1048
+ }
1049
+ // src/credentials-environments/legacy-environments/legacy-environments.ts
1050
+ const OLD_NAMES = ["Holocron", "Holocron - GitHub Actions variables"];
1051
+ /** The old Environment names, as candidates that are never reported when absent. */
1052
+ function legacyEnvironments() {
1053
+ return OLD_NAMES.map((name) => ({
1054
+ name,
1055
+ optional: true,
1056
+ legacy: true
1057
+ }));
1058
+ }
1059
+ // src/credentials-environments/resolve-environments/resolve-environments.ts
1060
+ /**
1061
+ * The Environments one `credentials` entry reads. An explicit name (the entry's `environment` option, else the shared
1062
+ * `credentials.environment`) is the only candidate and wins. Otherwise a deriving provider gets the names of its layer
1063
+ * (`environmentLayers()`) from the repo's `origin` and `detectEnvironment()`, followed by the migration fallback.
1064
+ * Nothing is read from a provider here. An empty list means there is nothing to read (the `test` layer).
1065
+ */
1066
+ async function resolveEnvironments(provider, explicit, input) {
1067
+ if (explicit !== void 0) return [{
1068
+ name: explicit,
1069
+ optional: false,
1070
+ legacy: false
1071
+ }];
1072
+ if (!derivesEnvironment(provider)) return [];
1073
+ const layer = detectEnvironment(input.env);
1074
+ if (layer === "test") return [];
1075
+ return [...environmentLayers(await repoSlug(input.repoRoot, input.gitExec), layer), ...legacyEnvironments()];
1076
+ }
1077
+ // src/credentials-environments/try-environments/try-environments.ts
1078
+ /** A provider's "no such Environment": its API error with status 404 (`ProviderApiError`, matched by shape). */
1079
+ function isNotFound(err) {
1080
+ return typeof err === "object" && err !== null && err.status === 404;
1081
+ }
1082
+ /**
1083
+ * Calls `attempt` for each candidate and sorts the answers into found and missing. A 404 is a miss; any other error
1084
+ * is thrown. A missing optional Environment is silent. When a required one is missing, the legacy candidates
1085
+ * (migration only, #2063) are tried too, and if one exists the miss is forgiven.
1086
+ */
1087
+ async function tryEnvironments(candidates, attempt) {
1088
+ const found = [];
1089
+ const missing = [];
1090
+ const ask = async (candidate) => {
1091
+ try {
1092
+ found.push({
1093
+ name: candidate.name,
1094
+ legacy: candidate.legacy,
1095
+ result: await attempt(candidate.name)
1096
+ });
1097
+ } catch (err) {
1098
+ if (!isNotFound(err)) throw err;
1099
+ if (!candidate.optional) missing.push(candidate.name);
1100
+ }
1101
+ };
1102
+ for (const candidate of candidates.filter((c) => !c.legacy)) await ask(candidate);
1103
+ if (missing.length > 0) {
1104
+ const before = found.length;
1105
+ for (const candidate of candidates.filter((c) => c.legacy)) await ask(candidate);
1106
+ if (found.length > before) missing.length = 0;
1107
+ }
1108
+ return {
1109
+ found,
1110
+ missing
1111
+ };
1112
+ }
1009
1113
  // src/plugin/workspace/workspace.ts
1010
1114
  /**
1011
1115
  * The `workspace`-context guard.
@@ -1103,12 +1207,20 @@ const system = createPluginSystem({
1103
1207
  if (!entry || entry.cardinality !== "many") return;
1104
1208
  const impls = [];
1105
1209
  for (const tuple of entry.tuples) try {
1106
- const environment = credentialsEnvironment(tuple, config);
1107
- if (!environment) throw new LoaderError(`the ${tuple.provider} credentials provider has no \`environment\` option and \`credentials.environment\` is not set`);
1210
+ const explicit = credentialsEnvironment(tuple, config);
1211
+ if (explicit === void 0 && !derivesEnvironment(tuple.provider)) throw new LoaderError(`the ${tuple.provider} credentials provider has no \`environment\` option and \`credentials.environment\` is not set`);
1108
1212
  const impl = await api.loadOne("credentials", tuple);
1109
1213
  impls.push(impl);
1110
- const sourceName = `${tuple.provider}:${environment}`;
1111
- if (options?.readCredentials !== false && !hasCredentials(sourceName)) setCredentials(sourceName, await impl.read(environment));
1214
+ if (options?.readCredentials === false) continue;
1215
+ const { missing } = await tryEnvironments(await resolveEnvironments(tuple.provider, explicit, {
1216
+ repoRoot: context.repoRoot,
1217
+ ...options?.env ? { env: options.env } : {},
1218
+ ...options?.gitExec ? { gitExec: options.gitExec } : {}
1219
+ }), async (name) => {
1220
+ const sourceName = `${tuple.provider}:${name}`;
1221
+ if (!hasCredentials(sourceName)) setCredentials(sourceName, await impl.read(name));
1222
+ });
1223
+ if (missing.length > 0) throw new LoaderError(`${tuple.provider} has no Environment named ${missing.map((n) => `"${n}"`).join(", ")}`);
1112
1224
  } catch (err) {
1113
1225
  api.fail("credentials", tuple, err);
1114
1226
  }
@@ -5086,23 +5198,49 @@ async function checkCredentials(input, loader) {
5086
5198
  const { tuples } = resolved.providers.credentials;
5087
5199
  for (const impl of loader.get("credentials")) {
5088
5200
  const tuple = tuples.find((t) => t.provider === impl.providerName);
5089
- const environment = tuple && credentialsEnvironment(tuple, resolved);
5090
- rows.push(...environment ? await checkProvider(impl, environment, expected) : [row$10(impl.providerName, "skip", "no `environment` option and `credentials.environment` is not set")]);
5201
+ const explicit = tuple && credentialsEnvironment(tuple, resolved);
5202
+ if (!explicit && !derivesEnvironment(impl.providerName)) {
5203
+ rows.push(row$10(impl.providerName, "skip", "no `environment` option and `credentials.environment` is not set"));
5204
+ continue;
5205
+ }
5206
+ try {
5207
+ const candidates = await resolveEnvironments(impl.providerName, explicit, {
5208
+ repoRoot: input.context.repoRoot,
5209
+ ...input.env ? { env: input.env } : {},
5210
+ ...input.gitExec ? { gitExec: input.gitExec } : {}
5211
+ });
5212
+ rows.push(...await checkProvider(impl, candidates, expected));
5213
+ } catch (err) {
5214
+ rows.push(row$10(impl.providerName, "fail", errorMessage(err)));
5215
+ }
5091
5216
  }
5092
5217
  return rows;
5093
5218
  }
5094
- async function checkProvider(impl, environment, expected) {
5219
+ /**
5220
+ * One row per expected variable, against the Environments the layer reads. A variable counts as present when any
5221
+ * Environment found holds it (the first found wins, as in the credential store). A required Environment that does not
5222
+ * exist is a failing row of its own, by name; a missing `- local` is not mentioned; an old name in use is a skipped row.
5223
+ */
5224
+ async function checkProvider(impl, candidates, expected) {
5095
5225
  const provider = impl.providerName;
5096
5226
  if (!impl.inspect) return [row$10(provider, "skip", "cannot list the variables without reading their values")];
5097
5227
  if (expected.length === 0) return [row$10(provider, "skip", "no configured plugin lists the tokens it takes")];
5228
+ if (candidates.length === 0) return [row$10(provider, "skip", "the `test` layer reads no Environment")];
5229
+ const inspect = impl.inspect.bind(impl);
5098
5230
  try {
5099
- const found = await impl.inspect(environment);
5100
- const held = new Set(found.names);
5101
- const where = found.environment === environment ? `"${found.environment}"` : `"${found.environment}" (the config writes "${environment}")`;
5102
- return expected.map(({ name, optional }) => {
5103
- if (held.has(name)) return row$10(provider, "ok", `present in ${where}`, name);
5104
- return optional ? row$10(provider, "skip", `optional, not set in ${where}`, name) : row$10(provider, "fail", `missing from ${where}`, name);
5105
- });
5231
+ const { found, missing } = await tryEnvironments(candidates, inspect);
5232
+ const rows = missing.map((name) => row$10(provider, "fail", `${provider} has no Environment named "${name}"`));
5233
+ const labels = found.map(({ name, result }) => result.environment === name ? `"${name}"` : `"${result.environment}" (the config writes "${name}")`);
5234
+ const where = labels.join(", ");
5235
+ for (const { name, legacy } of found) if (legacy) rows.push(row$10(provider, "skip", `read from the old Environment name "${name}"; rename it`));
5236
+ if (found.length === 0) return rows;
5237
+ for (const { name, optional } of expected) {
5238
+ const at = found.findIndex((f) => f.result.names.includes(name));
5239
+ if (at >= 0) rows.push(row$10(provider, "ok", `present in ${labels[at]}`, name));
5240
+ else if (optional) rows.push(row$10(provider, "skip", `optional, not set in ${where}`, name));
5241
+ else rows.push(row$10(provider, "fail", `missing from ${where}`, name));
5242
+ }
5243
+ return rows;
5106
5244
  } catch (err) {
5107
5245
  return [row$10(provider, "fail", errorMessage(err))];
5108
5246
  }
@@ -10802,7 +10940,10 @@ function githubEnvironments(config, feeds) {
10802
10940
  function ownerEnvironments(config) {
10803
10941
  const names = /* @__PURE__ */ new Set();
10804
10942
  const entry = config.providers.credentials;
10805
- for (const tuple of entry?.tuples ?? []) names.add(credentialsEnvironment(tuple, config));
10943
+ for (const tuple of entry?.tuples ?? []) {
10944
+ const named = credentialsEnvironment(tuple, config);
10945
+ if (named !== void 0) names.add(named);
10946
+ }
10806
10947
  const instances = new Set((config.githubApps ?? []).map((app) => app.environment));
10807
10948
  for (const environment of instances) names.add(environment);
10808
10949
  if (config.dev?.environment) names.add(config.dev.environment);