@rockcarver/frodo-cli 5.0.0-6 → 5.0.0-7

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.
@@ -0,0 +1,341 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-Ctb5zv51.cjs");
2
+ const require_ColorTheme = require("./ColorTheme-DEHDqYXV.cjs");
3
+ const require_Console = require("./Console--leD9RdR.cjs");
4
+ let fs = require("fs");
5
+ fs = require_rolldown_runtime.__toESM(fs, 1);
6
+ //#region src/ops/RealmOps.ts
7
+ var RealmOps_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
8
+ addCustomDomain: () => addCustomDomain,
9
+ describeRealm: () => describeRealm,
10
+ exportRealmById: () => exportRealmById,
11
+ exportRealmByName: () => exportRealmByName,
12
+ exportRealmsToFile: () => exportRealmsToFile,
13
+ exportRealmsToFiles: () => exportRealmsToFiles,
14
+ importRealmFromFile: () => importRealmFromFile,
15
+ importRealmsFromFile: () => importRealmsFromFile,
16
+ importRealmsFromFiles: () => importRealmsFromFiles,
17
+ listRealms: () => listRealms,
18
+ readRealmsCached: () => readRealmsCached
19
+ });
20
+ const { readRealm, readRealms, readRealmByName, exportRealms, importRealms, updateRealm } = require_ColorTheme.frodo.realm;
21
+ const { getTypedFilename, saveToFile, saveJsonToFile, getFilePath, getWorkingDirectory } = require_ColorTheme.frodo.utils;
22
+ /**
23
+ * Per-invocation cache of the realm list. The realm picker reads
24
+ * realms right after auth, and commands like `frodo realm list` read them
25
+ * again moments later -- two HTTP calls to the same endpoint that would
26
+ * (a) double the latency and (b) break Polly's order-matched replay in e2e
27
+ * recordings, which have one entry for the endpoint. Sharing one memoized
28
+ * read keeps both callers on a single fetch.
29
+ */
30
+ let realmsCache;
31
+ /**
32
+ * Reads all realms, memoized for the remainder of this invocation. Callers
33
+ * that need fresh data (import/export mutations) call frodo.realm
34
+ * .readRealms directly.
35
+ */
36
+ async function readRealmsCached() {
37
+ if (!realmsCache) realmsCache = await readRealms();
38
+ return realmsCache;
39
+ }
40
+ /**
41
+ * List realms
42
+ * @param {boolean} long Long list format with details
43
+ */
44
+ async function listRealms(long = false) {
45
+ try {
46
+ const realms = await readRealmsCached();
47
+ if (long) {
48
+ const table = require_Console.createTable([
49
+ require_ColorTheme.theme.heading("Id"),
50
+ require_ColorTheme.theme.heading("Name"),
51
+ require_ColorTheme.theme.heading("Status"),
52
+ require_ColorTheme.theme.heading("Custom Domains"),
53
+ require_ColorTheme.theme.heading("Parent Path")
54
+ ]);
55
+ realms.forEach((realmConfig) => {
56
+ table.push([
57
+ realmConfig._id,
58
+ realmConfig.name,
59
+ realmConfig.active ? require_ColorTheme.theme.positive("active") : require_ColorTheme.theme.negative("inactive"),
60
+ realmConfig.aliases.join("\n"),
61
+ realmConfig.parentPath
62
+ ]);
63
+ });
64
+ require_Console.printMessage(table.toString(), "data");
65
+ } else realms.forEach((realmConfig) => {
66
+ require_Console.printMessage((realmConfig.parentPath || "") + (realmConfig.parentPath && !realmConfig.parentPath.endsWith("/") ? "/" : "") + realmConfig.name, "data");
67
+ });
68
+ } catch (error) {
69
+ require_Console.printMessage(error, "error");
70
+ require_Console.printMessage(`Error listing realms: ${error.message}`, "error");
71
+ require_Console.printMessage(error.response?.data, "error");
72
+ }
73
+ }
74
+ /**
75
+ * Export realm to file by id
76
+ * @param {string} realmId realm id
77
+ * @param {string} file file name
78
+ * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true
79
+ * @returns {Promise<boolean>} true if successful, false otherwise
80
+ */
81
+ async function exportRealmById(realmId, file, includeMeta = true) {
82
+ const indicatorId = require_Console.createProgressIndicator("determinate", 1, `Exporting ${realmId}...`);
83
+ try {
84
+ const realm = await readRealm(realmId);
85
+ let fileName = getTypedFilename(realmId, `realm`);
86
+ if (file) fileName = file;
87
+ require_Console.updateProgressIndicator(indicatorId, `Saving ${realmId} to ${fileName}...`);
88
+ saveToFile("realm", [realm], "_id", getFilePath(fileName, true), includeMeta);
89
+ require_Console.stopProgressIndicator(indicatorId, `Exported realm ${realmId} to file`, "success");
90
+ return true;
91
+ } catch (error) {
92
+ require_Console.stopProgressIndicator(indicatorId, `Error exporting realm ${realmId} to file`, "fail");
93
+ require_Console.printError(error);
94
+ }
95
+ return false;
96
+ }
97
+ /**
98
+ * Export realm to file by name
99
+ * @param {string} realmName realm name
100
+ * @param {string} file file name
101
+ * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true
102
+ * @returns {Promise<boolean>} true if successful, false otherwise
103
+ */
104
+ async function exportRealmByName(realmName, file, includeMeta = true) {
105
+ const indicatorId = require_Console.createProgressIndicator("determinate", 1, `Exporting ${realmName}...`);
106
+ try {
107
+ const realm = await readRealmByName(realmName);
108
+ let fileName = getTypedFilename(!realmName || realmName === "/" ? "root" : realmName, `realm`);
109
+ if (file) fileName = file;
110
+ require_Console.updateProgressIndicator(indicatorId, `Saving ${realmName} to ${fileName}...`);
111
+ saveToFile("realm", [realm], "_id", getFilePath(fileName, true), includeMeta);
112
+ require_Console.stopProgressIndicator(indicatorId, `Exported realm ${realmName} to file`, "success");
113
+ return true;
114
+ } catch (error) {
115
+ require_Console.stopProgressIndicator(indicatorId, `Error exporting realm ${realmName} to file`, "fail");
116
+ require_Console.printError(error);
117
+ }
118
+ return false;
119
+ }
120
+ /**
121
+ * Export all realms to file
122
+ * @param {string} file file name
123
+ * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true
124
+ * @returns {Promise<boolean>} true if successful, false otherwise
125
+ */
126
+ async function exportRealmsToFile(file, includeMeta = true) {
127
+ try {
128
+ const exportData = await exportRealms();
129
+ let fileName = getTypedFilename(`allRealms`, `realm`);
130
+ if (file) fileName = file;
131
+ saveJsonToFile(exportData, getFilePath(fileName, true), includeMeta);
132
+ return true;
133
+ } catch (error) {
134
+ require_Console.printError(error, `Error exporting realms to file`);
135
+ }
136
+ return false;
137
+ }
138
+ /**
139
+ * Export all realms to separate files
140
+ * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true
141
+ * @returns {Promise<boolean>} true if successful, false otherwise
142
+ */
143
+ async function exportRealmsToFiles(includeMeta = true) {
144
+ try {
145
+ const realms = await readRealms();
146
+ for (const realm of realms) {
147
+ const fileName = getTypedFilename(!realm.name || realm.name === "/" ? "root" : realm.name, "realm");
148
+ saveToFile("realm", realm, "_id", getFilePath(fileName, true), includeMeta);
149
+ }
150
+ return true;
151
+ } catch (error) {
152
+ require_Console.printError(error, `Error exporting realms to files`);
153
+ }
154
+ return false;
155
+ }
156
+ /**
157
+ * Import a realm from file. The first realm from the file will be imported if no id/name is provided.
158
+ * @param {string} realmId realm id
159
+ * @param {string} realmName realm name
160
+ * @param {string} file import file name
161
+ * @returns {Promise<boolean>} true if successful, false otherwise
162
+ */
163
+ async function importRealmFromFile(realmId, realmName, file) {
164
+ const indicatorId = require_Console.createProgressIndicator("determinate", 1, "Importing realm...");
165
+ try {
166
+ const importData = JSON.parse(fs.default.readFileSync(getFilePath(file), "utf8"));
167
+ if (!realmId && !realmName) {
168
+ const firstRealm = Object.values(importData.realm)[0];
169
+ if (!firstRealm) {
170
+ require_Console.stopProgressIndicator(indicatorId, `No realms found!`, "fail");
171
+ return false;
172
+ }
173
+ realmName = firstRealm.name;
174
+ }
175
+ require_Console.updateProgressIndicator(indicatorId, `Importing realm ${realmName ? realmName : realmId}.`);
176
+ await importRealms(importData, realmId, realmName);
177
+ require_Console.stopProgressIndicator(indicatorId, `Successfully imported realm.`);
178
+ return true;
179
+ } catch (error) {
180
+ require_Console.stopProgressIndicator(indicatorId, `Error importing realm`, "fail");
181
+ require_Console.printError(error);
182
+ }
183
+ return false;
184
+ }
185
+ /**
186
+ * Import all realms from file
187
+ * @param {string} file import file name
188
+ * @returns {Promise<boolean>} true if successful, false otherwise
189
+ */
190
+ async function importRealmsFromFile(file) {
191
+ try {
192
+ require_Console.debugMessage(`importRealmsFromFile: start`);
193
+ const filePath = getFilePath(file);
194
+ const data = fs.default.readFileSync(filePath, "utf8");
195
+ require_Console.debugMessage(`importRealmsFromFile: importing ${filePath}`);
196
+ const importData = JSON.parse(data);
197
+ await importRealms(importData);
198
+ require_Console.debugMessage(`importRealmsFromFile: end`);
199
+ return true;
200
+ } catch (error) {
201
+ require_Console.printError(error, `Error importing realms from file`);
202
+ }
203
+ return false;
204
+ }
205
+ /**
206
+ * Import all realms from separate files
207
+ * @returns {Promise<boolean>} true if successful, false otherwise
208
+ */
209
+ async function importRealmsFromFiles() {
210
+ const errors = [];
211
+ try {
212
+ const realmFiles = fs.default.readdirSync(getWorkingDirectory()).filter((name) => name.toLowerCase().endsWith(".realm.json"));
213
+ for (const file of realmFiles) try {
214
+ await importRealmsFromFile(file);
215
+ } catch (error) {
216
+ errors.push(new require_ColorTheme.FrodoError(`Error importing realms from ${file}`, error));
217
+ }
218
+ if (errors.length > 0) throw new require_ColorTheme.FrodoError(`One or more errors importing realms`, errors);
219
+ return true;
220
+ } catch (error) {
221
+ if (errors.length > 0) require_Console.printError(error);
222
+ else require_Console.printError(error, `Error importing realms from files`);
223
+ }
224
+ return false;
225
+ }
226
+ /**
227
+ * Describe realm
228
+ * @param {String} realm realm name
229
+ */
230
+ async function describeRealm(realm) {
231
+ try {
232
+ const realmConfig = await readRealmByName(realm);
233
+ const table = require_Console.createKeyValueTable();
234
+ table.push([require_ColorTheme.theme.heading("Name"), realmConfig.name]);
235
+ table.push([require_ColorTheme.theme.heading("Status"), realmConfig.active ? require_ColorTheme.theme.positive("active") : require_ColorTheme.theme.negative("inactive")]);
236
+ table.push([require_ColorTheme.theme.heading("Custom Domains"), realmConfig.aliases.join("\n")]);
237
+ table.push([require_ColorTheme.theme.heading("Parent"), realmConfig.parentPath]);
238
+ table.push([require_ColorTheme.theme.heading("Id"), realmConfig._id]);
239
+ require_Console.printMessage(table.toString(), "data");
240
+ } catch {
241
+ require_Console.printMessage(`Realm ${realm} not found!`, "error");
242
+ }
243
+ }
244
+ /**
245
+ * Add custom DNS domain name (realm DNS alias)
246
+ * @param {String} realm realm name
247
+ * @param {String} domain domain name
248
+ */
249
+ async function addCustomDomain(realm, domain) {
250
+ try {
251
+ let realmConfig = await readRealmByName(realm);
252
+ let exists = false;
253
+ realmConfig.aliases.forEach((alias) => {
254
+ if (domain.toLowerCase() === alias.toLowerCase()) exists = true;
255
+ });
256
+ if (!exists) try {
257
+ realmConfig.aliases.push(domain.toLowerCase());
258
+ realmConfig = await updateRealm(realmConfig._id, realmConfig);
259
+ const table = require_Console.createKeyValueTable();
260
+ table.push([require_ColorTheme.theme.heading("Name"), realmConfig.name]);
261
+ table.push([require_ColorTheme.theme.heading("Status"), realmConfig.active ? require_ColorTheme.theme.positive("active") : require_ColorTheme.theme.negative("inactive")]);
262
+ table.push([require_ColorTheme.theme.heading("Custom Domains"), realmConfig.aliases.join("\n")]);
263
+ table.push([require_ColorTheme.theme.heading("Parent"), realmConfig.parentPath]);
264
+ table.push([require_ColorTheme.theme.heading("Id"), realmConfig._id]);
265
+ require_Console.printMessage(table.toString());
266
+ } catch (error) {
267
+ require_Console.printMessage(`Error adding custom domain: ${error.message}`, "error");
268
+ }
269
+ } catch (error) {
270
+ require_Console.printMessage(`${error.message}`, "error");
271
+ }
272
+ }
273
+ //#endregion
274
+ Object.defineProperty(exports, "RealmOps_exports", {
275
+ enumerable: true,
276
+ get: function() {
277
+ return RealmOps_exports;
278
+ }
279
+ });
280
+ Object.defineProperty(exports, "addCustomDomain", {
281
+ enumerable: true,
282
+ get: function() {
283
+ return addCustomDomain;
284
+ }
285
+ });
286
+ Object.defineProperty(exports, "describeRealm", {
287
+ enumerable: true,
288
+ get: function() {
289
+ return describeRealm;
290
+ }
291
+ });
292
+ Object.defineProperty(exports, "exportRealmById", {
293
+ enumerable: true,
294
+ get: function() {
295
+ return exportRealmById;
296
+ }
297
+ });
298
+ Object.defineProperty(exports, "exportRealmByName", {
299
+ enumerable: true,
300
+ get: function() {
301
+ return exportRealmByName;
302
+ }
303
+ });
304
+ Object.defineProperty(exports, "exportRealmsToFile", {
305
+ enumerable: true,
306
+ get: function() {
307
+ return exportRealmsToFile;
308
+ }
309
+ });
310
+ Object.defineProperty(exports, "exportRealmsToFiles", {
311
+ enumerable: true,
312
+ get: function() {
313
+ return exportRealmsToFiles;
314
+ }
315
+ });
316
+ Object.defineProperty(exports, "importRealmFromFile", {
317
+ enumerable: true,
318
+ get: function() {
319
+ return importRealmFromFile;
320
+ }
321
+ });
322
+ Object.defineProperty(exports, "importRealmsFromFile", {
323
+ enumerable: true,
324
+ get: function() {
325
+ return importRealmsFromFile;
326
+ }
327
+ });
328
+ Object.defineProperty(exports, "importRealmsFromFiles", {
329
+ enumerable: true,
330
+ get: function() {
331
+ return importRealmsFromFiles;
332
+ }
333
+ });
334
+ Object.defineProperty(exports, "listRealms", {
335
+ enumerable: true,
336
+ get: function() {
337
+ return listRealms;
338
+ }
339
+ });
340
+
341
+ //# sourceMappingURL=RealmOps-CQwmHsxG.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RealmOps-CQwmHsxG.cjs","names":["frodo","createTable","c","createProgressIndicator","FrodoError","createKeyValueTable"],"sources":["../src/ops/RealmOps.ts"],"sourcesContent":["import fs from 'fs';\nimport {\n frodo,\n FrodoError,\n type RealmExportInterface,\n} from '@rockcarver/frodo-lib';\nimport c from '../utils/ColorTheme';\nimport {\n createKeyValueTable,\n createProgressIndicator,\n createTable,\n debugMessage,\n printError,\n printMessage,\n stopProgressIndicator,\n updateProgressIndicator,\n} from '../utils/Console';\n\nconst {\n readRealm,\n readRealms,\n readRealmByName,\n exportRealms,\n importRealms,\n updateRealm,\n} = frodo.realm;\n\nconst {\n getTypedFilename,\n saveToFile,\n saveJsonToFile,\n getFilePath,\n getWorkingDirectory,\n} = frodo.utils;\n\n/**\n * Per-invocation cache of the realm list. The realm picker reads\n * realms right after auth, and commands like `frodo realm list` read them\n * again moments later -- two HTTP calls to the same endpoint that would\n * (a) double the latency and (b) break Polly's order-matched replay in e2e\n * recordings, which have one entry for the endpoint. Sharing one memoized\n * read keeps both callers on a single fetch.\n */\nlet realmsCache: Awaited<ReturnType<typeof readRealms>> | undefined;\n\n/**\n * Reads all realms, memoized for the remainder of this invocation. Callers\n * that need fresh data (import/export mutations) call frodo.realm\n * .readRealms directly.\n */\nexport async function readRealmsCached() {\n if (!realmsCache) {\n realmsCache = await readRealms();\n }\n return realmsCache;\n}\n\n/**\n * Clears the memoized realm list (test hygiene between invocations).\n */\nexport function resetRealmsCacheForTests(): void {\n realmsCache = undefined;\n}\n\n/**\n * List realms\n * @param {boolean} long Long list format with details\n */\nexport async function listRealms(long = false) {\n try {\n const realms = await readRealmsCached();\n if (long) {\n const table = createTable([\n c.heading('Id'),\n c.heading('Name'),\n c.heading('Status'),\n c.heading('Custom Domains'),\n c.heading('Parent Path'),\n ]);\n realms.forEach((realmConfig) => {\n table.push([\n realmConfig._id,\n realmConfig.name,\n realmConfig.active ? c.positive('active') : c.negative('inactive'),\n realmConfig.aliases.join('\\n'),\n realmConfig.parentPath,\n ]);\n });\n printMessage(table.toString(), 'data');\n } else {\n realms.forEach((realmConfig) => {\n printMessage(\n (realmConfig.parentPath || '') +\n (realmConfig.parentPath && !realmConfig.parentPath.endsWith('/')\n ? '/'\n : '') +\n realmConfig.name,\n 'data'\n );\n });\n }\n } catch (error) {\n printMessage(error, 'error');\n printMessage(`Error listing realms: ${error.message}`, 'error');\n printMessage(error.response?.data, 'error');\n }\n}\n\n/**\n * Export realm to file by id\n * @param {string} realmId realm id\n * @param {string} file file name\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportRealmById(\n realmId: string,\n file: string,\n includeMeta: boolean = true\n): Promise<boolean> {\n const indicatorId = createProgressIndicator(\n 'determinate',\n 1,\n `Exporting ${realmId}...`\n );\n try {\n const realm = await readRealm(realmId);\n let fileName = getTypedFilename(realmId, `realm`);\n if (file) {\n fileName = file;\n }\n updateProgressIndicator(indicatorId, `Saving ${realmId} to ${fileName}...`);\n saveToFile(\n 'realm',\n [realm],\n '_id',\n getFilePath(fileName, true),\n includeMeta\n );\n stopProgressIndicator(\n indicatorId,\n `Exported realm ${realmId} to file`,\n 'success'\n );\n return true;\n } catch (error) {\n stopProgressIndicator(\n indicatorId,\n `Error exporting realm ${realmId} to file`,\n 'fail'\n );\n printError(error);\n }\n return false;\n}\n\n/**\n * Export realm to file by name\n * @param {string} realmName realm name\n * @param {string} file file name\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportRealmByName(\n realmName: string,\n file: string,\n includeMeta: boolean = true\n): Promise<boolean> {\n const indicatorId = createProgressIndicator(\n 'determinate',\n 1,\n `Exporting ${realmName}...`\n );\n try {\n const realm = await readRealmByName(realmName);\n let fileName = getTypedFilename(\n !realmName || realmName === '/' ? 'root' : realmName,\n `realm`\n );\n if (file) {\n fileName = file;\n }\n updateProgressIndicator(\n indicatorId,\n `Saving ${realmName} to ${fileName}...`\n );\n saveToFile(\n 'realm',\n [realm],\n '_id',\n getFilePath(fileName, true),\n includeMeta\n );\n stopProgressIndicator(\n indicatorId,\n `Exported realm ${realmName} to file`,\n 'success'\n );\n return true;\n } catch (error) {\n stopProgressIndicator(\n indicatorId,\n `Error exporting realm ${realmName} to file`,\n 'fail'\n );\n printError(error);\n }\n return false;\n}\n\n/**\n * Export all realms to file\n * @param {string} file file name\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportRealmsToFile(\n file: string,\n includeMeta: boolean = true\n): Promise<boolean> {\n try {\n const exportData = await exportRealms();\n let fileName = getTypedFilename(`allRealms`, `realm`);\n if (file) {\n fileName = file;\n }\n saveJsonToFile(exportData, getFilePath(fileName, true), includeMeta);\n return true;\n } catch (error) {\n printError(error, `Error exporting realms to file`);\n }\n return false;\n}\n\n/**\n * Export all realms to separate files\n * @param {boolean} includeMeta true to include metadata, false otherwise. Default: true\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function exportRealmsToFiles(\n includeMeta: boolean = true\n): Promise<boolean> {\n try {\n const realms = await readRealms();\n for (const realm of realms) {\n const fileName = getTypedFilename(\n !realm.name || realm.name === '/' ? 'root' : realm.name,\n 'realm'\n );\n saveToFile(\n 'realm',\n realm,\n '_id',\n getFilePath(fileName, true),\n includeMeta\n );\n }\n return true;\n } catch (error) {\n printError(error, `Error exporting realms to files`);\n }\n return false;\n}\n\n/**\n * Import a realm from file. The first realm from the file will be imported if no id/name is provided.\n * @param {string} realmId realm id\n * @param {string} realmName realm name\n * @param {string} file import file name\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importRealmFromFile(\n realmId: string,\n realmName: string,\n file: string\n): Promise<boolean> {\n const indicatorId = createProgressIndicator(\n 'determinate',\n 1,\n 'Importing realm...'\n );\n try {\n const importData = JSON.parse(\n fs.readFileSync(getFilePath(file), 'utf8')\n ) as RealmExportInterface;\n if (!realmId && !realmName) {\n const firstRealm = Object.values(importData.realm)[0];\n if (!firstRealm) {\n stopProgressIndicator(indicatorId, `No realms found!`, 'fail');\n return false;\n }\n realmName = firstRealm.name;\n }\n updateProgressIndicator(\n indicatorId,\n `Importing realm ${realmName ? realmName : realmId}.`\n );\n await importRealms(importData, realmId, realmName);\n stopProgressIndicator(indicatorId, `Successfully imported realm.`);\n return true;\n } catch (error) {\n stopProgressIndicator(indicatorId, `Error importing realm`, 'fail');\n printError(error);\n }\n return false;\n}\n\n/**\n * Import all realms from file\n * @param {string} file import file name\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importRealmsFromFile(file: string): Promise<boolean> {\n try {\n debugMessage(`importRealmsFromFile: start`);\n const filePath = getFilePath(file);\n const data = fs.readFileSync(filePath, 'utf8');\n debugMessage(`importRealmsFromFile: importing ${filePath}`);\n const importData = JSON.parse(data);\n await importRealms(importData);\n debugMessage(`importRealmsFromFile: end`);\n return true;\n } catch (error) {\n printError(error, `Error importing realms from file`);\n }\n return false;\n}\n\n/**\n * Import all realms from separate files\n * @returns {Promise<boolean>} true if successful, false otherwise\n */\nexport async function importRealmsFromFiles(): Promise<boolean> {\n const errors: Error[] = [];\n try {\n const names = fs.readdirSync(getWorkingDirectory());\n const realmFiles = names.filter((name) =>\n name.toLowerCase().endsWith('.realm.json')\n );\n for (const file of realmFiles) {\n try {\n await importRealmsFromFile(file);\n } catch (error) {\n errors.push(\n new FrodoError(`Error importing realms from ${file}`, error)\n );\n }\n }\n if (errors.length > 0) {\n throw new FrodoError(`One or more errors importing realms`, errors);\n }\n return true;\n } catch (error) {\n if (errors.length > 0) {\n printError(error);\n } else {\n printError(error, `Error importing realms from files`);\n }\n }\n return false;\n}\n\n/**\n * Describe realm\n * @param {String} realm realm name\n */\nexport async function describeRealm(realm: string) {\n try {\n const realmConfig = await readRealmByName(realm);\n const table = createKeyValueTable();\n table.push([c.heading('Name'), realmConfig.name]);\n table.push([\n c.heading('Status'),\n realmConfig.active ? c.positive('active') : c.negative('inactive'),\n ]);\n table.push([c.heading('Custom Domains'), realmConfig.aliases.join('\\n')]);\n table.push([c.heading('Parent'), realmConfig.parentPath]);\n table.push([c.heading('Id'), realmConfig._id]);\n printMessage(table.toString(), 'data');\n } catch {\n printMessage(`Realm ${realm} not found!`, 'error');\n }\n}\n\n/**\n * Add custom DNS domain name (realm DNS alias)\n * @param {String} realm realm name\n * @param {String} domain domain name\n */\nexport async function addCustomDomain(realm: string, domain: string) {\n try {\n let realmConfig = await readRealmByName(realm);\n let exists = false;\n realmConfig.aliases.forEach((alias) => {\n if (domain.toLowerCase() === alias.toLowerCase()) {\n exists = true;\n }\n });\n if (!exists) {\n try {\n realmConfig.aliases.push(domain.toLowerCase());\n realmConfig = await updateRealm(realmConfig._id, realmConfig);\n const table = createKeyValueTable();\n table.push([c.heading('Name'), realmConfig.name]);\n table.push([\n c.heading('Status'),\n realmConfig.active ? c.positive('active') : c.negative('inactive'),\n ]);\n table.push([\n c.heading('Custom Domains'),\n realmConfig.aliases.join('\\n'),\n ]);\n table.push([c.heading('Parent'), realmConfig.parentPath]);\n table.push([c.heading('Id'), realmConfig._id]);\n printMessage(table.toString());\n } catch (error) {\n printMessage(`Error adding custom domain: ${error.message}`, 'error');\n }\n }\n } catch (error) {\n printMessage(`${error.message}`, 'error');\n }\n}\n\n/**\n * Remove custom DNS domain name (realm DNS alias)\n * @param {String} realm realm name\n * @param {String} domain domain name\n */\nexport async function removeCustomDomain(realm: string, domain: string) {\n try {\n let realmConfig = await readRealmByName(realm);\n const aliases = realmConfig.aliases.filter(\n (alias) => domain.toLowerCase() !== alias.toLowerCase()\n );\n if (aliases.length < realmConfig.aliases.length) {\n try {\n realmConfig.aliases = aliases;\n realmConfig = await updateRealm(realmConfig._id, realmConfig);\n const table = createKeyValueTable();\n table.push([c.heading('Name'), realmConfig.name]);\n table.push([\n c.heading('Status'),\n realmConfig.active ? c.positive('active') : c.negative('inactive'),\n ]);\n table.push([\n c.heading('Custom Domains'),\n realmConfig.aliases.join('\\n'),\n ]);\n table.push([c.heading('Parent'), realmConfig.parentPath]);\n table.push([c.heading('Id'), realmConfig._id]);\n printMessage(table.toString());\n } catch (error) {\n printMessage(`Error removing custom domain: ${error.message}`, 'error');\n }\n }\n } catch (error) {\n printMessage(`${error.message}`, 'error');\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAkBA,MAAM,EACJ,WACA,YACA,iBACA,cACA,cACA,gBACEA,mBAAAA,MAAM;AAEV,MAAM,EACJ,kBACA,YACA,gBACA,aACA,wBACEA,mBAAAA,MAAM;;;;;;;;;AAUV,IAAI;;;;;;AAOJ,eAAsB,mBAAmB;CACvC,IAAI,CAAC,aACH,cAAc,MAAM,WAAW;CAEjC,OAAO;AACT;;;;;AAaA,eAAsB,WAAW,OAAO,OAAO;CAC7C,IAAI;EACF,MAAM,SAAS,MAAM,iBAAiB;EACtC,IAAI,MAAM;GACR,MAAM,QAAQC,gBAAAA,YAAY;IACxBC,mBAAAA,MAAE,QAAQ,IAA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AY,KAAK,WAAW;GAC5D,MAAM,QAAQG,gBAAAA,oBAAoB;GAClC,MAAM,KAAK,CAACH,mBAAAA,MAAE,QAAQ,MAAM,GAAG,YAAY,IAAI,CAAC;GAChD,MAAM,KAAK,CACTA,mBAAAA,MAAE,QAAQ,QAAQ,GAClB,YAAY,SAASA,mBAAAA,MAAE,SAAS,QAAQ,IAAIA,mBAAAA,MAAE,SAAS,UAAU,CACnE,CAAC;GACD,MAAM,KAAK,CACTA,mBAAAA,MAAE,QAAQ,gBAAgB,GAC1B,YAAY,QAAQ,KAAK,IAAI,CAC/B,CAAC;GACD,MAAM,KAAK,CAACA,mBAAAA,MAAE,QAAQ,QAAQ,GAAG,YAAY,UAAU,CAAC;GACxD,MAAM,KAAK,CAACA,mBAAAA,MAAE,QAAQ,IAAI,GAAG,YAAY,GAAG,CAAC;GAC7C,gBAAA,aAAa,MAAM,SAAS,CAAC;EAC/B,SAAS,OAAO;GACd,gBAAA,aAAa,+BAA+B,MAAM,WAAW,OAAO;EACtE;CAEJ,SAAS,OAAO;EACd,gBAAA,aAAa,GAAG,MAAM,WAAW,OAAO;CAC1C;AACF"}
@@ -0,0 +1,138 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-Ctb5zv51.cjs");
2
+ const require_ColorTheme = require("./ColorTheme-DEHDqYXV.cjs");
3
+ const require_Console = require("./Console--leD9RdR.cjs");
4
+ const require_EscapableSelectPrompt = require("./EscapableSelectPrompt-Us2SkS12.cjs");
5
+ //#region src/utils/interactive/RealmPickers.ts
6
+ /**
7
+ * Realm picker (docs/INTERACTIVE-COMMANDS.md, post-auth pickers).
8
+ *
9
+ * After authentication succeeds, a command whose realm argument was left
10
+ * at its default can offer a dropdown of the target system's realms --
11
+ * but ONLY when the system actually has more than one (a single-realm
12
+ * tenant has no choice to offer; the default is already correct). The
13
+ * pick fires from the getTokens wrapper (AuthenticateOps) immediately
14
+ * after auth succeeds, so every command gets it without per-command
15
+ * wiring; a prompt only happens when
16
+ *
17
+ * - the gate allows prompting (canPrompt()),
18
+ * - the command declares a realm positional argument,
19
+ * - the user did not name a realm explicitly (argument value or
20
+ * FRODO_REALM -- recorded by `noteRealmProvenance` during the
21
+ * resolution pass, BEFORE frodo-lib maps the sentinel default to the
22
+ * deployment type's realm during auth), and
23
+ * - the target system reports more than one realm.
24
+ *
25
+ * Every other path is a no-op. Escape declines the offer and keeps the
26
+ * deployment-type default -- unlike the entity pickers there is no
27
+ * "wrong" continuation to protect here (the default is a valid choice),
28
+ * so backing out just means "keep the default".
29
+ *
30
+ * The loader failing (permission denied on realm listing, older servers,
31
+ * classic deployments where the endpoint differs) is swallowed and the
32
+ * default kept: the command is about to run against the default realm
33
+ * exactly as it did before the interactive layer existed.
34
+ */
35
+ var RealmPickers_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
36
+ noteRealmProvenance: () => noteRealmProvenance,
37
+ resolveRealmPick: () => resolveRealmPick
38
+ });
39
+ /** frodo-lib's sentinel default for "no realm chosen yet". */
40
+ const DEFAULT_REALM_KEY = "__default__realm__";
41
+ /** Cache of the realms read during this invocation (one fetch per run). */
42
+ let cachedRealms;
43
+ /**
44
+ * Whether the current invocation's realm was user-specified. Captured by
45
+ * `noteRealmProvenance` during the resolution pass -- it CANNOT be
46
+ * re-derived after auth, because frodo-lib's determineDefaultRealm
47
+ * replaces the sentinel default with the deployment type's realm (alpha
48
+ * or /) during _getTokens, making a user choice and a mapped default
49
+ * indistinguishable afterwards.
50
+ */
51
+ let realmUserSpecified = false;
52
+ /**
53
+ * Records whether this invocation's realm came from the user (positional
54
+ * argument value or FRODO_REALM) as opposed to the sentinel default.
55
+ * Called by the resolution pass BEFORE auth -- see the `realmUserSpecified`
56
+ * doc for why the timing matters.
57
+ */
58
+ function noteRealmProvenance() {
59
+ const realm = require_ColorTheme.state.getRealm();
60
+ realmUserSpecified = !!realm && realm !== DEFAULT_REALM_KEY;
61
+ }
62
+ /**
63
+ * Offers the realm dropdown for `command`'s realm argument when the
64
+ * conditions in the module doc hold. Called by the getTokens wrapper
65
+ * after a successful login. Never throws; on any problem it simply keeps
66
+ * the default.
67
+ */
68
+ async function resolveRealmPick(command) {
69
+ if (!require_EscapableSelectPrompt.canPrompt()) return;
70
+ if (!command.registeredArguments.some((a) => a.name() === "realm")) return;
71
+ if (realmUserSpecified) return;
72
+ let realms;
73
+ try {
74
+ if (!cachedRealms) {
75
+ const { readRealmsCached } = await Promise.resolve().then(() => require("./RealmOps-CQwmHsxG.cjs")).then((n) => n.RealmOps_exports);
76
+ cachedRealms = (await readRealmsCached()).map((realm) => ({
77
+ name: realm.name ?? realm._id ?? "",
78
+ active: realm.active ?? true
79
+ }));
80
+ }
81
+ realms = cachedRealms;
82
+ } catch {
83
+ return;
84
+ }
85
+ if (realms.length <= 1) return;
86
+ const current = require_ColorTheme.state.getRealm();
87
+ let choice;
88
+ for (;;) {
89
+ const { livePositionalPreviewFor, runInvocationEditorForCommand } = await Promise.resolve().then(() => require("./ResolveInteractiveInputs-CQBVc_CT.cjs")).then((n) => n.ResolveInteractiveInputs_exports);
90
+ const answer = await require_EscapableSelectPrompt.escapableSelect({
91
+ message: `Choose a realm (default: ${current}):`,
92
+ default: current,
93
+ hint: require_EscapableSelectPrompt.editableOptionsHint(command),
94
+ preview: livePositionalPreviewFor(command, "realm"),
95
+ choices: realms.map((realm) => ({
96
+ value: realm.name,
97
+ name: realm.name,
98
+ description: realm.active ? void 0 : "inactive"
99
+ }))
100
+ });
101
+ if (answer === require_EscapableSelectPrompt.EXIT_ALL) throw require_EscapableSelectPrompt.EXIT_ALL_SIGNAL;
102
+ if (answer === require_EscapableSelectPrompt.RIGHT) {
103
+ await runInvocationEditorForCommand(command);
104
+ continue;
105
+ }
106
+ choice = answer;
107
+ break;
108
+ }
109
+ if (choice === require_EscapableSelectPrompt.ESCAPE) {
110
+ require_Console.verboseMessage(`Keeping the default realm ${current}.`);
111
+ return;
112
+ }
113
+ if (!choice || choice === current) {
114
+ require_Console.verboseMessage(`Keeping the default realm ${current}.`);
115
+ return;
116
+ }
117
+ require_ColorTheme.state.setRealm(choice);
118
+ {
119
+ const { setPositionalValueForCommand } = await Promise.resolve().then(() => require("./ResolveInteractiveInputs-CQBVc_CT.cjs")).then((n) => n.ResolveInteractiveInputs_exports);
120
+ setPositionalValueForCommand(command, "realm", choice.replace(/^\//, ""));
121
+ }
122
+ require_Console.verboseMessage(`Using realm ${choice}.`);
123
+ }
124
+ //#endregion
125
+ Object.defineProperty(exports, "RealmPickers_exports", {
126
+ enumerable: true,
127
+ get: function() {
128
+ return RealmPickers_exports;
129
+ }
130
+ });
131
+ Object.defineProperty(exports, "noteRealmProvenance", {
132
+ enumerable: true,
133
+ get: function() {
134
+ return noteRealmProvenance;
135
+ }
136
+ });
137
+
138
+ //# sourceMappingURL=RealmPickers-7b9g8ZTE.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RealmPickers-7b9g8ZTE.cjs","names":["state","canPrompt","escapableSelect","editableOptionsHint","EXIT_ALL","EXIT_ALL_SIGNAL","RIGHT","ESCAPE"],"sources":["../src/utils/interactive/RealmPickers.ts"],"sourcesContent":["/**\n * Realm picker (docs/INTERACTIVE-COMMANDS.md, post-auth pickers).\n *\n * After authentication succeeds, a command whose realm argument was left\n * at its default can offer a dropdown of the target system's realms --\n * but ONLY when the system actually has more than one (a single-realm\n * tenant has no choice to offer; the default is already correct). The\n * pick fires from the getTokens wrapper (AuthenticateOps) immediately\n * after auth succeeds, so every command gets it without per-command\n * wiring; a prompt only happens when\n *\n * - the gate allows prompting (canPrompt()),\n * - the command declares a realm positional argument,\n * - the user did not name a realm explicitly (argument value or\n * FRODO_REALM -- recorded by `noteRealmProvenance` during the\n * resolution pass, BEFORE frodo-lib maps the sentinel default to the\n * deployment type's realm during auth), and\n * - the target system reports more than one realm.\n *\n * Every other path is a no-op. Escape declines the offer and keeps the\n * deployment-type default -- unlike the entity pickers there is no\n * \"wrong\" continuation to protect here (the default is a valid choice),\n * so backing out just means \"keep the default\".\n *\n * The loader failing (permission denied on realm listing, older servers,\n * classic deployments where the endpoint differs) is swallowed and the\n * default kept: the command is about to run against the default realm\n * exactly as it did before the interactive layer existed.\n */\n\nimport { state } from '@rockcarver/frodo-lib';\nimport { Command } from 'commander';\nimport { verboseMessage } from '../Console';\nimport { editableOptionsHint } from './EditableOptions';\nimport { escapableSelect, ESCAPE, RIGHT } from './EscapableSelectPrompt';\nimport { EXIT_ALL, EXIT_ALL_SIGNAL } from './ExitAll';\nimport { canPrompt } from './PromptGateState';\n\n/** frodo-lib's sentinel default for \"no realm chosen yet\". */\nconst DEFAULT_REALM_KEY = '__default__realm__';\n\n/** Cache of the realms read during this invocation (one fetch per run). */\nlet cachedRealms: { name: string; active: boolean }[] | undefined;\n\n/**\n * Whether the current invocation's realm was user-specified. Captured by\n * `noteRealmProvenance` during the resolution pass -- it CANNOT be\n * re-derived after auth, because frodo-lib's determineDefaultRealm\n * replaces the sentinel default with the deployment type's realm (alpha\n * or /) during _getTokens, making a user choice and a mapped default\n * indistinguishable afterwards.\n */\nlet realmUserSpecified = false;\n\n/**\n * Records whether this invocation's realm came from the user (positional\n * argument value or FRODO_REALM) as opposed to the sentinel default.\n * Called by the resolution pass BEFORE auth -- see the `realmUserSpecified`\n * doc for why the timing matters.\n */\nexport function noteRealmProvenance(): void {\n const realm = state.getRealm();\n realmUserSpecified = !!realm && realm !== DEFAULT_REALM_KEY;\n}\n\n/** Test hygiene: clears the per-invocation provenance + realm cache. */\nexport function resetRealmPickerStateForTests(): void {\n realmUserSpecified = false;\n cachedRealms = undefined;\n}\n\n/**\n * Offers the realm dropdown for `command`'s realm argument when the\n * conditions in the module doc hold. Called by the getTokens wrapper\n * after a successful login. Never throws; on any problem it simply keeps\n * the default.\n */\nexport async function resolveRealmPick(command: Command): Promise<void> {\n if (!canPrompt()) return;\n if (!command.registeredArguments.some((a) => a.name() === 'realm')) return;\n if (realmUserSpecified) return;\n\n let realms: { name: string; active: boolean }[];\n try {\n if (!cachedRealms) {\n // Via the memoized ops helper: shares one fetch with commands that\n // read realms themselves (frodo realm list), keeping Polly's\n // order-matched replay intact (recordings have one entry for the\n // endpoint) and halving the latency when both run.\n const { readRealmsCached } = await import('../../ops/RealmOps');\n const skeletons = await readRealmsCached();\n cachedRealms = skeletons.map((realm) => ({\n name: realm.name ?? realm._id ?? '',\n active: realm.active ?? true,\n }));\n }\n realms = cachedRealms;\n } catch {\n return; // can't list realms: keep the default\n }\n if (realms.length <= 1) return;\n\n const current = state.getRealm();\n // The picker runs POST-AUTH, so `current` is already frodo-lib's mapped\n // deployment default (alpha on cloud, / on classic/forgeops) -- passing\n // it as the select's default pre-highlights the TRUE default instead of\n // the first row, so a bare <enter> means \"keep the deployment default\".\n // The default may legitimately be absent from the list (the realms\n // endpoint never returns the root realm, so on classic/forgeops \"/\" has\n // no row): escapableSelect falls back to the first row in that case.\n // → (armed by the hint) opens the invocation editor, then\n // re-prompts this picker; ESCAPE keeps the default as before; EXIT_ALL\n // THROWS the unwind signal (the session ends even though auth already\n // succeeded -- the gesture means \"leave everything\", from any depth,\n // per docs/INTERACTIVE-COMMANDS.md).\n // The loop's exit type is string | typeof ESCAPE (the RIGHT case loops;\n // EXIT_ALL never resolves out of the loop -- it throws).\n let choice: string | typeof ESCAPE;\n for (;;) {\n const { livePositionalPreviewFor, runInvocationEditorForCommand } =\n await import('../../cli/ResolveInteractiveInputs');\n const answer = await escapableSelect<string>({\n message: `Choose a realm (default: ${current}):`,\n default: current,\n hint: editableOptionsHint(command),\n // LIVE footer: the highlighted realm shadows the realm positional\n // per render, so the footer's realm token moves with the cursor\n // BEFORE <enter> commits (live preview).\n preview: livePositionalPreviewFor(command, 'realm'),\n choices: realms.map((realm) => ({\n value: realm.name,\n name: realm.name,\n description: realm.active ? undefined : 'inactive',\n })),\n });\n if (answer === EXIT_ALL) throw EXIT_ALL_SIGNAL;\n if (answer === RIGHT) {\n // The hint advertised the editor, so → must open it (this branch\n // used to just re-prompt, making the key look dead). The editor\n // throws EXIT_ALL_SIGNAL on a double-ESC; a plain return loops\n // back here and the user can still ESC the picker.\n await runInvocationEditorForCommand(command);\n continue;\n }\n choice = answer;\n break;\n }\n if (choice === ESCAPE) {\n // Backed out: keep the deployment default (the pre-interactive\n // behavior), AND say so -- a silent return after the frame erased\n // left the terminal idle with no explanation (user report\n // 2026-10-13: \"the picker wasn't active\" -- the prompt had actually\n // concluded; nothing showed why nothing then happened).\n verboseMessage(`Keeping the default realm ${current}.`);\n return;\n }\n if (!choice || choice === current) {\n // <enter> on the already-highlighted default: an explicit \"keep\n // it\". The pick is DONE -- do NOT loop back into another picker\n // instance (the old silent re-prompt read as a dead screen: the\n // prompt concluded and nothing re-appeared).\n verboseMessage(`Keeping the default realm ${current}.`);\n return;\n }\n state.setRealm(choice);\n // Write the picked realm back into the command's realm positional so the\n // deferred authoring print (flushed at the action's postAction hook, see\n // FrodoCommand/AuthoringPrintState) shows the command EXACTLY as it ran\n // -- the printed realm token matches state.getRealm() token for token.\n // Without this, a non-default pick would print the (sentinel-translated)\n // positional while the action actually runs in `choice`. The CLI\n // positional convention is the plain name (no leading slash) -- the\n // exact value the user would type -- and handleDefaultArgsAndOpts\n // re-feeds it into state.setRealm inside the action body, so the value\n // must be positional-shaped, not state-shaped.\n {\n const { setPositionalValueForCommand } =\n await import('../../cli/ResolveInteractiveInputs');\n setPositionalValueForCommand(command, 'realm', choice.replace(/^\\//, ''));\n }\n verboseMessage(`Using realm ${choice}.`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAM,oBAAoB;;AAG1B,IAAI;;;;;;;;;AAUJ,IAAI,qBAAqB;;;;;;;AAQzB,SAAgB,sBAA4B;CAC1C,MAAM,QAAQA,mBAAAA,MAAM,SAAS;CAC7B,qBAAqB,CAAC,CAAC,SAAS,UAAU;AAC5C;;;;;;;AAcA,eAAsB,iBAAiB,SAAiC;CACtE,IAAI,CAACC,8BAAAA,UAAU,GAAG;CAClB,IAAI,CAAC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