@vltpkg/cli-sdk 1.0.0-rc.23 → 1.0.0-rc.24

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.
Files changed (103) hide show
  1. package/dist/commands/bugs.d.ts +17 -0
  2. package/dist/commands/bugs.js +163 -0
  3. package/dist/commands/build.d.ts +24 -0
  4. package/dist/commands/build.js +101 -0
  5. package/dist/commands/cache.d.ts +64 -0
  6. package/dist/commands/cache.js +256 -0
  7. package/dist/commands/ci.d.ts +10 -0
  8. package/dist/commands/ci.js +40 -0
  9. package/dist/commands/config.d.ts +5 -0
  10. package/dist/commands/config.js +429 -0
  11. package/dist/commands/create.d.ts +8 -0
  12. package/dist/commands/create.js +102 -0
  13. package/dist/commands/docs.d.ts +17 -0
  14. package/dist/commands/docs.js +153 -0
  15. package/dist/commands/exec-cache.d.ts +48 -0
  16. package/dist/commands/exec-cache.js +145 -0
  17. package/dist/commands/exec-local.d.ts +5 -0
  18. package/dist/commands/exec-local.js +46 -0
  19. package/dist/commands/exec.d.ts +8 -0
  20. package/dist/commands/exec.js +161 -0
  21. package/dist/commands/help.d.ts +3 -0
  22. package/dist/commands/help.js +43 -0
  23. package/dist/commands/init.d.ts +7 -0
  24. package/dist/commands/init.js +116 -0
  25. package/dist/commands/install/reporter.d.ts +10 -0
  26. package/dist/commands/install/reporter.js +93 -0
  27. package/dist/commands/install.d.ts +27 -0
  28. package/dist/commands/install.js +80 -0
  29. package/dist/commands/list.d.ts +17 -0
  30. package/dist/commands/list.js +197 -0
  31. package/dist/commands/login.d.ts +3 -0
  32. package/dist/commands/login.js +22 -0
  33. package/dist/commands/logout.d.ts +3 -0
  34. package/dist/commands/logout.js +22 -0
  35. package/dist/commands/pack.d.ts +31 -0
  36. package/dist/commands/pack.js +205 -0
  37. package/dist/commands/ping.d.ts +17 -0
  38. package/dist/commands/ping.js +114 -0
  39. package/dist/commands/pkg.d.ts +6 -0
  40. package/dist/commands/pkg.js +232 -0
  41. package/dist/commands/publish.d.ts +21 -0
  42. package/dist/commands/publish.js +282 -0
  43. package/dist/commands/query.d.ts +18 -0
  44. package/dist/commands/query.js +216 -0
  45. package/dist/commands/repo.d.ts +17 -0
  46. package/dist/commands/repo.js +157 -0
  47. package/dist/commands/run-exec.d.ts +5 -0
  48. package/dist/commands/run-exec.js +40 -0
  49. package/dist/commands/run.d.ts +5 -0
  50. package/dist/commands/run.js +62 -0
  51. package/dist/commands/token.d.ts +3 -0
  52. package/dist/commands/token.js +39 -0
  53. package/dist/commands/uninstall.d.ts +15 -0
  54. package/dist/commands/uninstall.js +39 -0
  55. package/dist/commands/update.d.ts +13 -0
  56. package/dist/commands/update.js +46 -0
  57. package/dist/commands/version.d.ts +25 -0
  58. package/dist/commands/version.js +252 -0
  59. package/dist/commands/view.d.ts +22 -0
  60. package/dist/commands/view.js +334 -0
  61. package/dist/commands/whoami.d.ts +12 -0
  62. package/dist/commands/whoami.js +28 -0
  63. package/dist/config/definition.d.ts +407 -0
  64. package/dist/config/definition.js +684 -0
  65. package/dist/config/index.d.ts +218 -0
  66. package/dist/config/index.js +488 -0
  67. package/dist/config/merge.d.ts +3 -0
  68. package/dist/config/merge.js +27 -0
  69. package/dist/config/usage.d.ts +18 -0
  70. package/dist/config/usage.js +39 -0
  71. package/dist/custom-help.d.ts +8 -0
  72. package/dist/custom-help.js +419 -0
  73. package/dist/exec-command.d.ts +52 -0
  74. package/dist/exec-command.js +313 -0
  75. package/dist/index.d.ts +3 -0
  76. package/dist/index.js +72 -0
  77. package/dist/load-command.d.ts +15 -0
  78. package/dist/load-command.js +20 -0
  79. package/dist/mermaid-image-view.d.ts +18 -0
  80. package/dist/mermaid-image-view.js +36 -0
  81. package/dist/output.d.ts +20 -0
  82. package/dist/output.js +125 -0
  83. package/dist/pack-tarball.d.ts +23 -0
  84. package/dist/pack-tarball.js +256 -0
  85. package/dist/parse-add-remove-args.d.ts +28 -0
  86. package/dist/parse-add-remove-args.js +103 -0
  87. package/dist/print-err.d.ts +13 -0
  88. package/dist/print-err.js +193 -0
  89. package/dist/query-diff-files.d.ts +17 -0
  90. package/dist/query-diff-files.js +63 -0
  91. package/dist/query-host-contexts.d.ts +15 -0
  92. package/dist/query-host-contexts.js +136 -0
  93. package/dist/read-password.d.ts +7 -0
  94. package/dist/read-password.js +32 -0
  95. package/dist/read-project-folders.d.ts +17 -0
  96. package/dist/read-project-folders.js +100 -0
  97. package/dist/reload-config.d.ts +2 -0
  98. package/dist/reload-config.js +11 -0
  99. package/dist/render-mermaid.d.ts +22 -0
  100. package/dist/render-mermaid.js +68 -0
  101. package/dist/view.d.ts +29 -0
  102. package/dist/view.js +30 -0
  103. package/package.json +25 -25
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Module that handles all vlt configuration needs
3
+ *
4
+ * Project-level configs are set in a `vlt.json` file in the local project
5
+ * if present. This will override the user-level configs in the appropriate
6
+ * XDG config path.
7
+ *
8
+ * Command-specific configuration can be specified by putting options in a
9
+ * field in the `command` object. For example:
10
+ *
11
+ * ```json
12
+ * {
13
+ * "registry": "https://registry.npmjs.org/",
14
+ * "command": {
15
+ * "publish": {
16
+ * "registry": "http://registry.internal"
17
+ * }
18
+ * }
19
+ * }
20
+ * ```
21
+ * @module
22
+ */
23
+ import { PackageInfoClient } from '@vltpkg/package-info';
24
+ import { PackageJson } from '@vltpkg/package-json';
25
+ import type { SpecOptions } from '@vltpkg/spec';
26
+ import type { WhichConfig } from '@vltpkg/vlt-json';
27
+ import { Monorepo } from '@vltpkg/workspaces';
28
+ import type { Jack, OptionsResults, Unwrap } from 'jackspeak';
29
+ import { PathScurry } from 'path-scurry';
30
+ import type { Commands, RecordField } from './definition.ts';
31
+ import { commands, definition, isRecordField, recordFields } from './definition.ts';
32
+ export { commands, definition, isRecordField, recordFields, type Commands, };
33
+ export declare const kCustomInspect: unique symbol;
34
+ export type RecordPairs = Record<string, unknown>;
35
+ export type RecordString = Record<string, string>;
36
+ export type PairsAsRecords = ConfigOptionsNoExtras & {
37
+ command?: {
38
+ [k in keyof Commands]?: ConfigOptionsNoExtras;
39
+ };
40
+ };
41
+ export declare const pairsToRecords: (obj: NonNullable<ConfigFileData> | OptionsResults<ConfigDefinitions>) => PairsAsRecords;
42
+ export declare const recordsToPairs: (obj: RecordPairs) => RecordPairs;
43
+ export type ConfigDataNoCommand = {
44
+ [k in keyof OptionsResults<ConfigDefinitions>]?: OptionsResults<ConfigDefinitions>[k];
45
+ };
46
+ /**
47
+ * Config data can be any options, and also a 'command' field which
48
+ * contains command names and override options for that command.
49
+ */
50
+ export type ConfigData = ConfigDataNoCommand & {
51
+ command?: {
52
+ [k in keyof Commands]?: ConfigDataNoCommand;
53
+ };
54
+ };
55
+ export type ConfigFileDataNoCommand = {
56
+ [k in keyof ConfigDataNoCommand]: k extends (OptListKeys<ConfigDataNoCommand>) ? RecordString | string[] : ConfigDataNoCommand[k];
57
+ };
58
+ /**
59
+ * Config data as it appears in the config field of the vlt.json, with kv pair
60
+ * lists stored as `Record<string, string>` and
61
+ */
62
+ export type ConfigFileData = ConfigFileDataNoCommand & {
63
+ command?: {
64
+ [k in keyof Commands]?: ConfigFileDataNoCommand;
65
+ };
66
+ };
67
+ export type ConfigOptionsNoExtras = {
68
+ [k in keyof OptionsResults<ConfigDefinitions>]: k extends (RecordField) ? RecordString : k extends 'command' ? never : OptionsResults<ConfigDefinitions>[k];
69
+ };
70
+ export type ConfigOptions = ConfigOptionsNoExtras & Pick<SpecOptions, 'catalog' | 'catalogs'> & {
71
+ packageJson: PackageJson;
72
+ scurry: PathScurry;
73
+ projectRoot: string;
74
+ monorepo?: Monorepo;
75
+ packageInfo: PackageInfoClient;
76
+ };
77
+ /**
78
+ * The base config definition set as a type
79
+ */
80
+ export type ConfigDefinitions = Unwrap<typeof definition>;
81
+ export type StringListKeys<O> = {
82
+ [k in keyof O]: O[k] extends string[] | undefined ? k : never;
83
+ };
84
+ export type OptListKeys<O> = Exclude<StringListKeys<O>[keyof StringListKeys<O>], undefined>;
85
+ /**
86
+ * Class that handles configuration for vlt.
87
+ *
88
+ * Call {@link Config.load} to get one of these.
89
+ */
90
+ export declare class Config {
91
+ #private;
92
+ /**
93
+ * The {@link https://npmjs.com/jackspeak | JackSpeak} object
94
+ * representing vlt's configuration
95
+ */
96
+ jack: Jack<ConfigDefinitions>;
97
+ /**
98
+ * Parsed values in effect
99
+ */
100
+ values?: OptionsResults<ConfigDefinitions>;
101
+ /**
102
+ * Command-specific config values
103
+ */
104
+ commandValues: {
105
+ [cmd in Commands[keyof Commands]]?: ConfigData;
106
+ };
107
+ /**
108
+ * A flattened object of the parsed configuration
109
+ */
110
+ get options(): ConfigOptions;
111
+ /**
112
+ * Reset the options value, optionally setting a new project root
113
+ * to recalculate the options.
114
+ */
115
+ resetOptions(projectRoot?: string): void;
116
+ /**
117
+ * positional arguments to the vlt process
118
+ */
119
+ positionals?: string[];
120
+ /**
121
+ * The root of the project where a vlt.json, vlt.json,
122
+ * package.json, or .git was found. Not necessarily the `process.cwd()`,
123
+ * though that is the default location.
124
+ *
125
+ * Never walks up as far as `$HOME`. So for example, if a project is in
126
+ * `~/projects/xyz`, then the highest dir it will check is `~/projects`
127
+ */
128
+ projectRoot: string;
129
+ /**
130
+ * `Record<alias, canonical name>` to dereference command aliases.
131
+ */
132
+ commands: Commands;
133
+ /**
134
+ * Which command name to use for overriding with command-specific values,
135
+ * determined from the argv when parse() is called.
136
+ */
137
+ command?: Commands[keyof Commands];
138
+ constructor(jack?: Jack<ConfigDefinitions>, projectRoot?: string);
139
+ /**
140
+ * Parse the arguments and set configuration and positionals accordingly.
141
+ */
142
+ parse(args?: string[]): this & ParsedConfig;
143
+ /**
144
+ * Get a `key=value` list option value as an object.
145
+ *
146
+ * For example, a list option with a vlaue of `['key=value', 'xyz=as=df' ]`
147
+ * would be returned as `{key: 'value', xyz: 'as=df'}`
148
+ *
149
+ * Results are memoized, so subsequent calls for the same key will return the
150
+ * same object. If new strings are added to the list, then the memoized value
151
+ * is *not* updated, so only use once configurations have been fully loaded.
152
+ *
153
+ * If the config value is not set at all, an empty object is returned.
154
+ */
155
+ getRecord(k: OptListKeys<ConfigData>): RecordString;
156
+ /**
157
+ * Get a configuration value.
158
+ *
159
+ * Note: `key=value` pair configs are returned as a string array. To get them
160
+ * as an object, use {@link Config#getRecord}.
161
+ */
162
+ get<K extends keyof OptionsResults<ConfigDefinitions>>(k: K): OptionsResults<ConfigDefinitions>[K];
163
+ /**
164
+ * Write the config values to the user or project config file.
165
+ */
166
+ writeConfigFile(this: LoadedConfig, which: WhichConfig, values: NonNullable<ConfigFileData>): Promise<void>;
167
+ /**
168
+ * Fold in the provided fields with the existing properties
169
+ * in the config file.
170
+ */
171
+ addConfigToFile(this: LoadedConfig, which: WhichConfig, values: NonNullable<ConfigFileData>): Promise<void>;
172
+ /**
173
+ * Deletes the specified config fields from the named file
174
+ * Returns `true` if anything was changed.
175
+ */
176
+ deleteConfigKeys(this: LoadedConfig, which: WhichConfig, fields: string[]): Promise<boolean>;
177
+ /**
178
+ * Edit the user or project configuration file.
179
+ *
180
+ * If the file isn't present, then it starts with `{}` so the user has
181
+ * something to work with.
182
+ *
183
+ * If the result is not valid, or no config settings are contained in the
184
+ * file after editing, then it's restored to what it was before, which might
185
+ * mean deleting the file.
186
+ */
187
+ editConfigFile(this: LoadedConfig, which: WhichConfig, edit: (file: string) => Promise<void> | void): Promise<void>;
188
+ /**
189
+ * Find the local config file and load both it and the user-level config in
190
+ * the XDG config home.
191
+ */
192
+ loadConfigFile(): Promise<this>;
193
+ /**
194
+ * Force a complete reload of config files from disk.
195
+ * This clears all caches and re-reads config files.
196
+ * Useful for long-running processes that need to pick up config changes.
197
+ */
198
+ reloadFromDisk(): Promise<void>;
199
+ /**
200
+ * Load the configuration and return a Promise to a
201
+ * {@link Config} object
202
+ */
203
+ static load(projectRoot?: string, argv?: string[],
204
+ /**
205
+ * only used in tests, resets the memoization
206
+ * @internal
207
+ */
208
+ reload?: boolean): Promise<LoadedConfig>;
209
+ }
210
+ export type ParsedConfig = Config & {
211
+ command: NonNullable<Config['command']>;
212
+ values: OptionsResults<ConfigDefinitions>;
213
+ positionals: string[];
214
+ };
215
+ /**
216
+ * A fully loaded {@link Config} object
217
+ */
218
+ export type LoadedConfig = ParsedConfig;
@@ -0,0 +1,488 @@
1
+ /**
2
+ * Module that handles all vlt configuration needs
3
+ *
4
+ * Project-level configs are set in a `vlt.json` file in the local project
5
+ * if present. This will override the user-level configs in the appropriate
6
+ * XDG config path.
7
+ *
8
+ * Command-specific configuration can be specified by putting options in a
9
+ * field in the `command` object. For example:
10
+ *
11
+ * ```json
12
+ * {
13
+ * "registry": "https://registry.npmjs.org/",
14
+ * "command": {
15
+ * "publish": {
16
+ * "registry": "http://registry.internal"
17
+ * }
18
+ * }
19
+ * }
20
+ * ```
21
+ * @module
22
+ */
23
+ import { error } from '@vltpkg/error-cause';
24
+ import { PackageInfoClient } from '@vltpkg/package-info';
25
+ import { PackageJson } from '@vltpkg/package-json';
26
+ import { resetCaches } from '@vltpkg/dep-id';
27
+ import { getOptions } from '@vltpkg/spec';
28
+ import { assertRecordStringString, assertRecordStringT, isRecordStringString, } from '@vltpkg/types';
29
+ import { find, load, reload, save } from '@vltpkg/vlt-json';
30
+ import { Monorepo } from '@vltpkg/workspaces';
31
+ import { readFile, rm, writeFile } from 'node:fs/promises';
32
+ import { dirname } from 'node:path';
33
+ import { PathScurry } from 'path-scurry';
34
+ import { commands, definition, getCommand, isRecordField, recordFields, } from "./definition.js";
35
+ import { merge } from "./merge.js";
36
+ export { commands, definition, isRecordField, recordFields, };
37
+ export const kCustomInspect = Symbol.for('nodejs.util.inspect.custom');
38
+ // turn a set of pairs into a Record object.
39
+ // if a kv pair doesn't have a = character, set to `''`
40
+ const reducePairs = (pairs) => {
41
+ const record = {};
42
+ for (const kv of pairs) {
43
+ const eq = kv.indexOf('=');
44
+ if (eq === -1)
45
+ record[kv] = '';
46
+ else {
47
+ const key = kv.substring(0, eq);
48
+ const val = kv.substring(eq + 1);
49
+ record[key] = val;
50
+ }
51
+ }
52
+ return record;
53
+ };
54
+ const isRecordFieldValue = (k, v) => Array.isArray(v) &&
55
+ recordFields.includes(k);
56
+ export const pairsToRecords = (obj) => {
57
+ return Object.fromEntries(Object.entries(obj).map(([k, v]) => [
58
+ k,
59
+ k === 'command' && v && typeof v === 'object' ?
60
+ Object.fromEntries(Object.entries(v).map(([k, v]) => [
61
+ k,
62
+ pairsToRecords(v),
63
+ ]))
64
+ : isRecordFieldValue(k, v) ? reducePairs(v)
65
+ : v,
66
+ ]));
67
+ };
68
+ export const recordsToPairs = (obj) => {
69
+ return Object.fromEntries(Object.entries(obj)
70
+ .filter(([k]) => !(k === 'scurry' ||
71
+ k === 'packageJson' ||
72
+ k === 'monorepo' ||
73
+ k === 'projectRoot' ||
74
+ k === 'packageInfo'))
75
+ .map(([k, v]) => [
76
+ k,
77
+ k === 'command' && v && typeof v === 'object' ?
78
+ recordsToPairs(v)
79
+ : (!v ||
80
+ typeof v !== 'object' ||
81
+ Array.isArray(v) ||
82
+ !isRecordField(k)) ?
83
+ v
84
+ : Object.entries(v).map(([k, v]) => `${k}=${v}`),
85
+ ]));
86
+ };
87
+ const kRecord = Symbol('parsed key=value record');
88
+ /**
89
+ * Class that handles configuration for vlt.
90
+ *
91
+ * Call {@link Config.load} to get one of these.
92
+ */
93
+ export class Config {
94
+ /**
95
+ * The {@link https://npmjs.com/jackspeak | JackSpeak} object
96
+ * representing vlt's configuration
97
+ */
98
+ jack;
99
+ /**
100
+ * Parsed values in effect
101
+ */
102
+ values;
103
+ /**
104
+ * Command-specific config values
105
+ */
106
+ commandValues = {};
107
+ /**
108
+ * A flattened object of the parsed configuration
109
+ */
110
+ get options() {
111
+ if (this.#options)
112
+ return this.#options;
113
+ const scurry = new PathScurry(this.projectRoot);
114
+ const packageJson = new PackageJson();
115
+ const asRecords = pairsToRecords(this.parse().values);
116
+ const extras = {
117
+ projectRoot: this.projectRoot,
118
+ scurry,
119
+ packageJson,
120
+ monorepo: Monorepo.maybeLoad(this.projectRoot, {
121
+ scurry,
122
+ packageJson,
123
+ load: {
124
+ paths: asRecords.workspace,
125
+ groups: asRecords['workspace-group'],
126
+ },
127
+ }),
128
+ catalog: load('catalog', assertRecordStringString),
129
+ catalogs: load('catalogs', o => assertRecordStringT(o, isRecordStringString, 'Record<string, Record<string, string>>')),
130
+ };
131
+ const options = Object.assign(asRecords, extras);
132
+ // Ensure spec-related options (registries, jsr-registries, git hosts, etc.)
133
+ // are always filled with defaults. Some downstream libraries (eg. @vltpkg/dep-id)
134
+ // expect these defaults to be present even when the user didn't configure them.
135
+ Object.assign(options, getOptions(options));
136
+ this.#options = Object.assign(options, {
137
+ packageInfo: new PackageInfoClient(options),
138
+ [kCustomInspect]() {
139
+ return Object.fromEntries(Object.entries(options).filter(([k]) => k !== 'monorepo' &&
140
+ k !== 'scurry' &&
141
+ k !== 'packageJson' &&
142
+ k !== 'packageInfo'));
143
+ },
144
+ });
145
+ return this.#options;
146
+ }
147
+ /**
148
+ * Reset the options value, optionally setting a new project root
149
+ * to recalculate the options.
150
+ */
151
+ resetOptions(projectRoot = process.cwd()) {
152
+ this.projectRoot = projectRoot;
153
+ this.#options = undefined;
154
+ resetCaches();
155
+ }
156
+ // memoized options() getter value
157
+ #options;
158
+ /**
159
+ * positional arguments to the vlt process
160
+ */
161
+ positionals;
162
+ /**
163
+ * Original arguments used for parsing (stored for reload purposes)
164
+ * @internal
165
+ */
166
+ #originalArgs;
167
+ /**
168
+ * The root of the project where a vlt.json, vlt.json,
169
+ * package.json, or .git was found. Not necessarily the `process.cwd()`,
170
+ * though that is the default location.
171
+ *
172
+ * Never walks up as far as `$HOME`. So for example, if a project is in
173
+ * `~/projects/xyz`, then the highest dir it will check is `~/projects`
174
+ */
175
+ projectRoot;
176
+ /**
177
+ * `Record<alias, canonical name>` to dereference command aliases.
178
+ */
179
+ commands;
180
+ /**
181
+ * Which command name to use for overriding with command-specific values,
182
+ * determined from the argv when parse() is called.
183
+ */
184
+ command;
185
+ constructor(jack = definition, projectRoot = process.cwd()) {
186
+ this.projectRoot = projectRoot;
187
+ this.commands = commands;
188
+ this.jack = jack;
189
+ }
190
+ /**
191
+ * Parse the arguments and set configuration and positionals accordingly.
192
+ */
193
+ parse(args = process.argv) {
194
+ if (isParsed(this))
195
+ return this;
196
+ // Store the original args for potential reload
197
+ this.#originalArgs = [...args];
198
+ this.jack.loadEnvDefaults();
199
+ const p = this.jack.parseRaw(args);
200
+ const fallback = getCommand(p.values['fallback-command']);
201
+ this.command = getCommand(p.positionals[0]);
202
+ const cmdOrFallback = this.command ?? fallback;
203
+ const cmdSpecific = cmdOrFallback && this.commandValues[cmdOrFallback];
204
+ if (cmdSpecific) {
205
+ this.jack.setConfigValues(recordsToPairs(cmdSpecific));
206
+ }
207
+ // ok, applied cmd-specific defaults, do rest of the parse
208
+ this.jack.applyDefaults(p);
209
+ this.jack.writeEnv(p);
210
+ if (this.command)
211
+ p.positionals.shift();
212
+ else
213
+ this.command = getCommand(p.values['fallback-command']);
214
+ Object.assign(this, p);
215
+ /* c8 ignore start - unpossible */
216
+ if (!isParsed(this))
217
+ throw error('failed to parse config');
218
+ /* c8 ignore stop */
219
+ return this;
220
+ }
221
+ /**
222
+ * Get a `key=value` list option value as an object.
223
+ *
224
+ * For example, a list option with a vlaue of `['key=value', 'xyz=as=df' ]`
225
+ * would be returned as `{key: 'value', xyz: 'as=df'}`
226
+ *
227
+ * Results are memoized, so subsequent calls for the same key will return the
228
+ * same object. If new strings are added to the list, then the memoized value
229
+ * is *not* updated, so only use once configurations have been fully loaded.
230
+ *
231
+ * If the config value is not set at all, an empty object is returned.
232
+ */
233
+ getRecord(k) {
234
+ const pairs = this.get(k);
235
+ if (!pairs)
236
+ return {};
237
+ if (pairs[kRecord])
238
+ return pairs[kRecord];
239
+ const kv = pairs.reduce((kv, pair) => {
240
+ const eq = pair.indexOf('=');
241
+ if (eq === -1)
242
+ return kv;
243
+ const key = pair.substring(0, eq);
244
+ const val = pair.substring(eq + 1);
245
+ kv[key] = val;
246
+ return kv;
247
+ }, {});
248
+ Object.assign(pairs, { [kRecord]: kv });
249
+ return kv;
250
+ }
251
+ /**
252
+ * Get a configuration value.
253
+ *
254
+ * Note: `key=value` pair configs are returned as a string array. To get them
255
+ * as an object, use {@link Config#getRecord}.
256
+ */
257
+ get(k) {
258
+ /* c8 ignore next -- impossible but TS doesn't know that */
259
+ return (this.values ?? this.parse().values)[k];
260
+ }
261
+ /**
262
+ * Write the config values to the user or project config file.
263
+ */
264
+ async writeConfigFile(which, values) {
265
+ save('config', pairsToRecords(values), which);
266
+ await this.#reloadConfig();
267
+ }
268
+ /**
269
+ * Fold in the provided fields with the existing properties
270
+ * in the config file.
271
+ */
272
+ async addConfigToFile(which, values) {
273
+ return this.writeConfigFile(which, merge((await this.#maybeLoadConfigFile(which)) ?? {}, values));
274
+ }
275
+ // called in this weird bound way so that it can be used by the
276
+ // vlt-json config loading module.
277
+ #validator = function (c, file) {
278
+ this.#validateConfig(c, file);
279
+ }.bind(this);
280
+ #validateConfig(c, file) {
281
+ if (!c || typeof c !== 'object' || Array.isArray(c)) {
282
+ throw error('invalid config, expected object', {
283
+ path: file,
284
+ found: c,
285
+ wanted: 'ConfigFileData',
286
+ });
287
+ }
288
+ const { command, ...values } = recordsToPairs(c);
289
+ // Validate registries keys don't contain reserved ~ character
290
+ const registries = c.registries;
291
+ if (registries && typeof registries === 'object') {
292
+ const registriesObj = Array.isArray(registries) ?
293
+ reducePairs(registries)
294
+ : registries;
295
+ for (const key of Object.keys(registriesObj)) {
296
+ if (key === '' || key.includes('~')) {
297
+ throw error('Reserved character found in registries name', {
298
+ path: file,
299
+ found: key,
300
+ });
301
+ }
302
+ }
303
+ }
304
+ if (command) {
305
+ for (const [c, opts] of Object.entries(command)) {
306
+ const cmd = getCommand(c);
307
+ if (cmd && opts && typeof opts === 'object') {
308
+ // Validate registries in command-specific config
309
+ const cmdRegistries = opts.registries;
310
+ if (cmdRegistries && typeof cmdRegistries === 'object') {
311
+ const cmdRegistriesObj = Array.isArray(cmdRegistries) ?
312
+ reducePairs(cmdRegistries)
313
+ : cmdRegistries;
314
+ for (const key of Object.keys(cmdRegistriesObj)) {
315
+ if (key === '' || key.includes('~')) {
316
+ throw error('Reserved character found in registries name', {
317
+ path: file,
318
+ found: key,
319
+ });
320
+ }
321
+ }
322
+ }
323
+ this.commandValues[cmd] = merge(this.commandValues[cmd] ?? {}, opts);
324
+ }
325
+ }
326
+ }
327
+ this.jack.setConfigValues(values, file);
328
+ }
329
+ /**
330
+ * if the file exists, parse and load it. returns object if data was
331
+ * loaded, or undefined if not.
332
+ */
333
+ async #maybeLoadConfigFile(whichConfig) {
334
+ return load('config', this.#validator, whichConfig);
335
+ }
336
+ /**
337
+ * Deletes the specified config fields from the named file
338
+ * Returns `true` if anything was changed.
339
+ */
340
+ async deleteConfigKeys(which, fields) {
341
+ const data = await this.#maybeLoadConfigFile(which);
342
+ if (!data)
343
+ return false;
344
+ let didSomething = false;
345
+ for (const f of fields) {
346
+ const [key, ...sk] = f.split('.');
347
+ const subs = sk.join('.');
348
+ const k = key;
349
+ const v = data[k];
350
+ if (v === undefined)
351
+ continue;
352
+ if (subs && v && typeof v === 'object') {
353
+ if (Array.isArray(v)) {
354
+ const i = v.findIndex(subvalue => subvalue.startsWith(`${subs}=`));
355
+ if (i !== -1) {
356
+ if (v.length === 1)
357
+ delete data[k];
358
+ else
359
+ v.splice(i, 1);
360
+ didSomething = true;
361
+ }
362
+ }
363
+ else {
364
+ if (v[subs] !== undefined) {
365
+ delete v[subs];
366
+ if (Object.keys(v).length === 0)
367
+ delete data[k];
368
+ didSomething = true;
369
+ }
370
+ }
371
+ }
372
+ else {
373
+ didSomething = true;
374
+ delete data[k];
375
+ }
376
+ }
377
+ if (didSomething)
378
+ await this.writeConfigFile(which, data);
379
+ return didSomething;
380
+ }
381
+ /**
382
+ * Edit the user or project configuration file.
383
+ *
384
+ * If the file isn't present, then it starts with `{}` so the user has
385
+ * something to work with.
386
+ *
387
+ * If the result is not valid, or no config settings are contained in the
388
+ * file after editing, then it's restored to what it was before, which might
389
+ * mean deleting the file.
390
+ */
391
+ async editConfigFile(which, edit) {
392
+ // load the file as a backup
393
+ // call the edit function
394
+ // reload it
395
+ const file = find(which);
396
+ const backup = await readFile(file, 'utf8').catch(() => undefined);
397
+ if (!backup) {
398
+ await writeFile(file, JSON.stringify({ config: {} }, null, 2) + '\n');
399
+ }
400
+ let valid = false;
401
+ try {
402
+ await edit(file);
403
+ // force it to reload the file and validate it again
404
+ // if this fails, we roll back.
405
+ const result = reload('config', which);
406
+ save('config', result ?? {}, which);
407
+ valid = true;
408
+ }
409
+ finally {
410
+ if (!valid) {
411
+ // TODO: maybe write the file to a re-edit backup location?
412
+ // then you could do `vlt config edit retry` or something.
413
+ if (backup) {
414
+ await writeFile(file, backup);
415
+ reload(which);
416
+ }
417
+ else {
418
+ await rm(file, { force: true });
419
+ }
420
+ }
421
+ }
422
+ }
423
+ /**
424
+ * Find the local config file and load both it and the user-level config in
425
+ * the XDG config home.
426
+ */
427
+ async loadConfigFile() {
428
+ await this.#maybeLoadConfigFile('user');
429
+ this.projectRoot = dirname(find('project', this.projectRoot));
430
+ await this.#maybeLoadConfigFile('project');
431
+ return this;
432
+ }
433
+ /**
434
+ * Clear cached config values to force re-reading from updated files.
435
+ * @internal
436
+ */
437
+ async #reloadConfig() {
438
+ // Clear the memoized options to force recalculation
439
+ this.#options = undefined;
440
+ }
441
+ /**
442
+ * Force a complete reload of config files from disk.
443
+ * This clears all caches and re-reads config files.
444
+ * Useful for long-running processes that need to pick up config changes.
445
+ */
446
+ async reloadFromDisk() {
447
+ // Clear the memoized options to force recalculation
448
+ this.#options = undefined;
449
+ // Clear the parsed state to force re-parsing
450
+ // This is crucial because parse() returns early if already parsed
451
+ this.values = undefined;
452
+ this.positionals = undefined;
453
+ this.command = undefined;
454
+ // Clear vlt-json caches for both user and project configs
455
+ // This ensures that the next time config files are read, they'll be re-read from disk
456
+ const { unload } = await import('@vltpkg/vlt-json');
457
+ unload('user');
458
+ unload('project');
459
+ // Force reload of config files by calling the load methods again
460
+ // This will re-read the files and re-apply them to the jack parser
461
+ await this.#maybeLoadConfigFile('user');
462
+ await this.#maybeLoadConfigFile('project');
463
+ // Re-parse to pick up the updated config values using the original arguments
464
+ this.parse(this.#originalArgs);
465
+ }
466
+ /**
467
+ * cache of the loaded config
468
+ */
469
+ static #loaded;
470
+ /**
471
+ * Load the configuration and return a Promise to a
472
+ * {@link Config} object
473
+ */
474
+ static async load(projectRoot = process.cwd(), argv = process.argv,
475
+ /**
476
+ * only used in tests, resets the memoization
477
+ * @internal
478
+ */
479
+ reload = false) {
480
+ if (this.#loaded && !reload)
481
+ return this.#loaded;
482
+ const a = new Config(definition, projectRoot);
483
+ const b = await a.loadConfigFile();
484
+ this.#loaded = b.parse(argv);
485
+ return this.#loaded;
486
+ }
487
+ }
488
+ const isParsed = (c) => !!(c.values && c.positionals && c.command);