@settlemint/sdk-utils 2.3.2 → 2.3.3-main6f8f814c

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 (98) hide show
  1. package/README.md +121 -77
  2. package/dist/environment.cjs +17708 -383
  3. package/dist/environment.cjs.map +1 -1
  4. package/dist/environment.d.cts +263 -98
  5. package/dist/environment.d.ts +263 -98
  6. package/dist/environment.js +17746 -0
  7. package/dist/environment.js.map +1 -0
  8. package/dist/filesystem.cjs +6746 -113
  9. package/dist/filesystem.cjs.map +1 -1
  10. package/dist/filesystem.d.cts +22 -1
  11. package/dist/filesystem.d.ts +22 -1
  12. package/dist/filesystem.js +6766 -0
  13. package/dist/filesystem.js.map +1 -0
  14. package/dist/http.cjs +217 -79
  15. package/dist/http.cjs.map +1 -1
  16. package/dist/http.d.cts +14 -1
  17. package/dist/http.d.ts +14 -1
  18. package/dist/http.js +226 -0
  19. package/dist/http.js.map +1 -0
  20. package/dist/index.cjs +295 -104
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +26 -1
  23. package/dist/index.d.ts +26 -1
  24. package/dist/index.js +306 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/json.cjs +83 -0
  27. package/dist/json.cjs.map +1 -0
  28. package/dist/json.d.cts +56 -0
  29. package/dist/json.d.ts +56 -0
  30. package/dist/json.js +80 -0
  31. package/dist/json.js.map +1 -0
  32. package/dist/logging.cjs +209 -137
  33. package/dist/logging.cjs.map +1 -1
  34. package/dist/logging.d.cts +23 -14
  35. package/dist/logging.d.ts +23 -14
  36. package/dist/logging.js +221 -0
  37. package/dist/logging.js.map +1 -0
  38. package/dist/package-manager.cjs +7353 -173
  39. package/dist/package-manager.cjs.map +1 -1
  40. package/dist/package-manager.d.cts +26 -3
  41. package/dist/package-manager.d.ts +26 -3
  42. package/dist/package-manager.js +7385 -0
  43. package/dist/package-manager.js.map +1 -0
  44. package/dist/retry.cjs +137 -0
  45. package/dist/retry.cjs.map +1 -0
  46. package/dist/retry.d.cts +19 -0
  47. package/dist/retry.d.ts +19 -0
  48. package/dist/retry.js +136 -0
  49. package/dist/retry.js.map +1 -0
  50. package/dist/runtime.cjs +58 -40
  51. package/dist/runtime.cjs.map +1 -1
  52. package/dist/runtime.d.cts +3 -0
  53. package/dist/runtime.d.ts +3 -0
  54. package/dist/runtime.js +45 -0
  55. package/dist/runtime.js.map +1 -0
  56. package/dist/string.cjs +76 -0
  57. package/dist/string.cjs.map +1 -0
  58. package/dist/string.d.cts +58 -0
  59. package/dist/string.d.ts +58 -0
  60. package/dist/string.js +72 -0
  61. package/dist/string.js.map +1 -0
  62. package/dist/terminal.cjs +426 -229
  63. package/dist/terminal.cjs.map +1 -1
  64. package/dist/terminal.d.cts +54 -24
  65. package/dist/terminal.d.ts +54 -24
  66. package/dist/terminal.js +441 -0
  67. package/dist/terminal.js.map +1 -0
  68. package/dist/url.cjs +25 -0
  69. package/dist/url.cjs.map +1 -0
  70. package/dist/url.d.cts +20 -0
  71. package/dist/url.d.ts +20 -0
  72. package/dist/url.js +24 -0
  73. package/dist/url.js.map +1 -0
  74. package/dist/validation.cjs +10486 -190
  75. package/dist/validation.cjs.map +1 -1
  76. package/dist/validation.d.cts +128 -94
  77. package/dist/validation.d.ts +128 -94
  78. package/dist/validation.js +10482 -0
  79. package/dist/validation.js.map +1 -0
  80. package/package.json +6 -6
  81. package/dist/environment.mjs +0 -383
  82. package/dist/environment.mjs.map +0 -1
  83. package/dist/filesystem.mjs +0 -105
  84. package/dist/filesystem.mjs.map +0 -1
  85. package/dist/http.mjs +0 -63
  86. package/dist/http.mjs.map +0 -1
  87. package/dist/index.mjs +0 -90
  88. package/dist/index.mjs.map +0 -1
  89. package/dist/logging.mjs +0 -123
  90. package/dist/logging.mjs.map +0 -1
  91. package/dist/package-manager.mjs +0 -167
  92. package/dist/package-manager.mjs.map +0 -1
  93. package/dist/runtime.mjs +0 -23
  94. package/dist/runtime.mjs.map +0 -1
  95. package/dist/terminal.mjs +0 -230
  96. package/dist/terminal.mjs.map +0 -1
  97. package/dist/validation.mjs +0 -159
  98. package/dist/validation.mjs.map +0 -1
@@ -0,0 +1,441 @@
1
+ import { greenBright, inverse, magentaBright, redBright, whiteBright, yellowBright } from "yoctocolors";
2
+ import { spawn } from "node:child_process";
3
+ import isInCi from "is-in-ci";
4
+ import yoctoSpinner from "yocto-spinner";
5
+ import { Table } from "console-table-printer";
6
+
7
+ //#region src/terminal/should-print.ts
8
+ /**
9
+ * Returns true if the terminal should print, false otherwise.
10
+ * @returns true if the terminal should print, false otherwise.
11
+ */
12
+ function shouldPrint() {
13
+ return process.env.SETTLEMINT_DISABLE_TERMINAL !== "true";
14
+ }
15
+
16
+ //#endregion
17
+ //#region src/terminal/ascii.ts
18
+ /**
19
+ * Prints the SettleMint ASCII art logo to the console in magenta color.
20
+ * Used for CLI branding and visual identification.
21
+ *
22
+ * @example
23
+ * import { ascii } from "@settlemint/sdk-utils/terminal";
24
+ *
25
+ * // Prints the SettleMint logo
26
+ * ascii();
27
+ */
28
+ const ascii = () => {
29
+ if (!shouldPrint()) {
30
+ return;
31
+ }
32
+ console.log(magentaBright(`
33
+ _________ __ __ .__ _____ .__ __
34
+ / _____/ _____/ |__/ |_| | ____ / \\ |__| _____/ |_
35
+ \\_____ \\_/ __ \\ __\\ __\\ | _/ __ \\ / \\ / \\| |/ \\ __\\
36
+ / \\ ___/| | | | | |_\\ ___// Y \\ | | \\ |
37
+ /_________/\\_____>__| |__| |____/\\_____>____|____/__|___|__/__|
38
+ `));
39
+ };
40
+
41
+ //#endregion
42
+ //#region src/logging/mask-tokens.ts
43
+ /**
44
+ * Masks sensitive SettleMint tokens in output text by replacing them with asterisks.
45
+ * Handles personal access tokens (PAT), application access tokens (AAT), and service account tokens (SAT).
46
+ *
47
+ * @param output - The text string that may contain sensitive tokens
48
+ * @returns The text with any sensitive tokens masked with asterisks
49
+ * @example
50
+ * import { maskTokens } from "@settlemint/sdk-utils/terminal";
51
+ *
52
+ * // Masks a token in text
53
+ * const masked = maskTokens("Token: sm_pat_****"); // "Token: ***"
54
+ */
55
+ const maskTokens = (output) => {
56
+ return output.replace(/sm_(pat|aat|sat)_[0-9a-zA-Z]+/g, "***");
57
+ };
58
+
59
+ //#endregion
60
+ //#region src/terminal/cancel.ts
61
+ /**
62
+ * Error class used to indicate that the operation was cancelled.
63
+ * This error is used to signal that the operation should be aborted.
64
+ */
65
+ var CancelError = class extends Error {};
66
+ /**
67
+ * Displays an error message in red inverse text and throws a CancelError.
68
+ * Used to terminate execution with a visible error message.
69
+ * Any sensitive tokens in the message are masked before display.
70
+ *
71
+ * @param msg - The error message to display
72
+ * @returns never - Function does not return as it throws an error
73
+ * @example
74
+ * import { cancel } from "@settlemint/sdk-utils/terminal";
75
+ *
76
+ * // Exits process with error message
77
+ * cancel("An error occurred");
78
+ */
79
+ const cancel = (msg) => {
80
+ console.log("");
81
+ console.log(inverse(redBright(maskTokens(msg))));
82
+ console.log("");
83
+ throw new CancelError(msg);
84
+ };
85
+
86
+ //#endregion
87
+ //#region src/terminal/execute-command.ts
88
+ /**
89
+ * Error class for command execution errors
90
+ * @extends Error
91
+ */
92
+ var CommandError = class extends Error {
93
+ /**
94
+ * Constructs a new CommandError
95
+ * @param message - The error message
96
+ * @param code - The exit code of the command
97
+ * @param output - The output of the command
98
+ */
99
+ constructor(message, code, output) {
100
+ super(message);
101
+ this.code = code;
102
+ this.output = output;
103
+ }
104
+ };
105
+ /**
106
+ * Executes a command with the given arguments in a child process.
107
+ * Pipes stdin to the child process and captures stdout/stderr output.
108
+ * Masks any sensitive tokens in the output before displaying or returning.
109
+ *
110
+ * @param command - The command to execute
111
+ * @param args - Array of arguments to pass to the command
112
+ * @param options - Options for customizing command execution
113
+ * @returns Array of output strings from stdout and stderr
114
+ * @throws {CommandError} If the process fails to start or exits with non-zero code
115
+ * @example
116
+ * import { executeCommand } from "@settlemint/sdk-utils/terminal";
117
+ *
118
+ * // Execute git clone
119
+ * await executeCommand("git", ["clone", "repo-url"]);
120
+ *
121
+ * // Execute silently
122
+ * await executeCommand("npm", ["install"], { silent: true });
123
+ */
124
+ async function executeCommand(command, args, options) {
125
+ const { silent,...spawnOptions } = options ?? {};
126
+ const child = spawn(command, args, {
127
+ ...spawnOptions,
128
+ env: {
129
+ ...process.env,
130
+ ...options?.env
131
+ }
132
+ });
133
+ process.stdin.pipe(child.stdin);
134
+ const output = [];
135
+ return new Promise((resolve, reject) => {
136
+ child.stdout.on("data", (data) => {
137
+ const maskedData = maskTokens(data.toString());
138
+ if (!silent) {
139
+ process.stdout.write(maskedData);
140
+ }
141
+ output.push(maskedData);
142
+ });
143
+ child.stderr.on("data", (data) => {
144
+ const maskedData = maskTokens(data.toString());
145
+ if (!silent) {
146
+ process.stderr.write(maskedData);
147
+ }
148
+ output.push(maskedData);
149
+ });
150
+ child.on("error", (err) => {
151
+ process.stdin.unpipe(child.stdin);
152
+ reject(new CommandError(err.message, "code" in err && typeof err.code === "number" ? err.code : 1, output));
153
+ });
154
+ child.on("close", (code) => {
155
+ process.stdin.unpipe(child.stdin);
156
+ if (code === 0 || code === null || code === 143) {
157
+ resolve(output);
158
+ return;
159
+ }
160
+ reject(new CommandError(`Command "${command}" exited with code ${code}`, code, output));
161
+ });
162
+ });
163
+ }
164
+
165
+ //#endregion
166
+ //#region src/terminal/intro.ts
167
+ /**
168
+ * Displays an introductory message in magenta text with padding.
169
+ * Any sensitive tokens in the message are masked before display.
170
+ *
171
+ * @param msg - The message to display as introduction
172
+ * @example
173
+ * import { intro } from "@settlemint/sdk-utils/terminal";
174
+ *
175
+ * // Display intro message
176
+ * intro("Starting deployment...");
177
+ */
178
+ const intro = (msg) => {
179
+ if (!shouldPrint()) {
180
+ return;
181
+ }
182
+ console.log("");
183
+ console.log(magentaBright(maskTokens(msg)));
184
+ console.log("");
185
+ };
186
+
187
+ //#endregion
188
+ //#region src/terminal/note.ts
189
+ /**
190
+ * Displays a note message with optional warning level formatting.
191
+ * Regular notes are displayed in normal text, while warnings are shown in yellow.
192
+ * Any sensitive tokens in the message are masked before display.
193
+ *
194
+ * @param message - The message to display as a note
195
+ * @param level - The note level: "info" (default) or "warn" for warning styling
196
+ * @example
197
+ * import { note } from "@settlemint/sdk-utils/terminal";
198
+ *
199
+ * // Display info note
200
+ * note("Operation completed successfully");
201
+ *
202
+ * // Display warning note
203
+ * note("Low disk space remaining", "warn");
204
+ */
205
+ const note = (message, level = "info") => {
206
+ if (!shouldPrint()) {
207
+ return;
208
+ }
209
+ const maskedMessage = maskTokens(message);
210
+ console.log("");
211
+ if (level === "warn") {
212
+ console.warn(yellowBright(maskedMessage));
213
+ return;
214
+ }
215
+ console.log(maskedMessage);
216
+ };
217
+
218
+ //#endregion
219
+ //#region src/terminal/list.ts
220
+ /**
221
+ * Displays a list of items in a formatted manner, supporting nested items.
222
+ *
223
+ * @param title - The title of the list
224
+ * @param items - The items to display, can be strings or arrays for nested items
225
+ * @returns The formatted list
226
+ * @example
227
+ * import { list } from "@settlemint/sdk-utils/terminal";
228
+ *
229
+ * // Simple list
230
+ * list("Use cases", ["use case 1", "use case 2", "use case 3"]);
231
+ *
232
+ * // Nested list
233
+ * list("Providers", [
234
+ * "AWS",
235
+ * ["us-east-1", "eu-west-1"],
236
+ * "Azure",
237
+ * ["eastus", "westeurope"]
238
+ * ]);
239
+ */
240
+ function list(title, items) {
241
+ const formatItems = (items$1) => {
242
+ return items$1.map((item) => {
243
+ if (Array.isArray(item)) {
244
+ return item.map((subItem) => ` • ${subItem}`).join("\n");
245
+ }
246
+ return ` • ${item}`;
247
+ }).join("\n");
248
+ };
249
+ return note(`${title}:\n\n${formatItems(items)}`);
250
+ }
251
+
252
+ //#endregion
253
+ //#region src/terminal/outro.ts
254
+ /**
255
+ * Displays a closing message in green inverted text with padding.
256
+ * Any sensitive tokens in the message are masked before display.
257
+ *
258
+ * @param msg - The message to display as conclusion
259
+ * @example
260
+ * import { outro } from "@settlemint/sdk-utils/terminal";
261
+ *
262
+ * // Display outro message
263
+ * outro("Deployment completed successfully!");
264
+ */
265
+ const outro = (msg) => {
266
+ if (!shouldPrint()) {
267
+ return;
268
+ }
269
+ console.log("");
270
+ console.log(inverse(greenBright(maskTokens(msg))));
271
+ console.log("");
272
+ };
273
+
274
+ //#endregion
275
+ //#region src/terminal/spinner.ts
276
+ /**
277
+ * Error class used to indicate that the spinner operation failed.
278
+ * This error is used to signal that the operation should be aborted.
279
+ */
280
+ var SpinnerError = class extends Error {
281
+ constructor(message, originalError) {
282
+ super(message);
283
+ this.originalError = originalError;
284
+ this.name = "SpinnerError";
285
+ }
286
+ };
287
+ /**
288
+ * Displays a loading spinner while executing an async task.
289
+ * Shows progress with start/stop messages and handles errors.
290
+ * Spinner is disabled in CI environments.
291
+ *
292
+ * @param options - Configuration options for the spinner
293
+ * @returns The result from the executed task
294
+ * @throws Will exit process with code 1 if task fails
295
+ * @example
296
+ * import { spinner } from "@settlemint/sdk-utils/terminal";
297
+ *
298
+ * // Show spinner during async task
299
+ * const result = await spinner({
300
+ * startMessage: "Deploying...",
301
+ * task: async () => {
302
+ * // Async work here
303
+ * return "success";
304
+ * },
305
+ * stopMessage: "Deployed successfully!"
306
+ * });
307
+ */
308
+ const spinner = async (options) => {
309
+ const handleError = (error) => {
310
+ const errorMessage = maskTokens(error.message);
311
+ note(redBright(`${errorMessage}\n\n${error.stack}`));
312
+ throw new SpinnerError(errorMessage, error);
313
+ };
314
+ if (isInCi || !shouldPrint()) {
315
+ try {
316
+ return await options.task();
317
+ } catch (err) {
318
+ return handleError(err);
319
+ }
320
+ }
321
+ const spinner$1 = yoctoSpinner({ stream: process.stdout }).start(options.startMessage);
322
+ try {
323
+ const result = await options.task(spinner$1);
324
+ spinner$1.success(options.stopMessage);
325
+ await new Promise((resolve) => process.nextTick(resolve));
326
+ return result;
327
+ } catch (err) {
328
+ spinner$1.error(redBright(`${options.startMessage} --> Error!`));
329
+ return handleError(err);
330
+ }
331
+ };
332
+
333
+ //#endregion
334
+ //#region src/string.ts
335
+ /**
336
+ * Capitalizes the first letter of a string.
337
+ *
338
+ * @param val - The string to capitalize
339
+ * @returns The input string with its first letter capitalized
340
+ *
341
+ * @example
342
+ * import { capitalizeFirstLetter } from "@settlemint/sdk-utils";
343
+ *
344
+ * const capitalized = capitalizeFirstLetter("hello");
345
+ * // Returns: "Hello"
346
+ */
347
+ function capitalizeFirstLetter(val) {
348
+ return String(val).charAt(0).toUpperCase() + String(val).slice(1);
349
+ }
350
+ /**
351
+ * Converts a camelCase string to a human-readable string.
352
+ *
353
+ * @param s - The camelCase string to convert
354
+ * @returns The human-readable string
355
+ *
356
+ * @example
357
+ * import { camelCaseToWords } from "@settlemint/sdk-utils";
358
+ *
359
+ * const words = camelCaseToWords("camelCaseString");
360
+ * // Returns: "Camel Case String"
361
+ */
362
+ function camelCaseToWords(s) {
363
+ const result = s.replace(/([a-z])([A-Z])/g, "$1 $2");
364
+ const withSpaces = result.replace(/([A-Z])([a-z])/g, " $1$2");
365
+ const capitalized = capitalizeFirstLetter(withSpaces);
366
+ return capitalized.replace(/\s+/g, " ").trim();
367
+ }
368
+ /**
369
+ * Replaces underscores and hyphens with spaces.
370
+ *
371
+ * @param s - The string to replace underscores and hyphens with spaces
372
+ * @returns The input string with underscores and hyphens replaced with spaces
373
+ *
374
+ * @example
375
+ * import { replaceUnderscoresAndHyphensWithSpaces } from "@settlemint/sdk-utils";
376
+ *
377
+ * const result = replaceUnderscoresAndHyphensWithSpaces("Already_Spaced-Second");
378
+ * // Returns: "Already Spaced Second"
379
+ */
380
+ function replaceUnderscoresAndHyphensWithSpaces(s) {
381
+ return s.replace(/[-_]/g, " ");
382
+ }
383
+ /**
384
+ * Truncates a string to a maximum length and appends "..." if it is longer.
385
+ *
386
+ * @param value - The string to truncate
387
+ * @param maxLength - The maximum length of the string
388
+ * @returns The truncated string or the original string if it is shorter than the maximum length
389
+ *
390
+ * @example
391
+ * import { truncate } from "@settlemint/sdk-utils";
392
+ *
393
+ * const truncated = truncate("Hello, world!", 10);
394
+ * // Returns: "Hello, wor..."
395
+ */
396
+ function truncate(value, maxLength) {
397
+ if (value.length <= maxLength) {
398
+ return value;
399
+ }
400
+ return `${value.slice(0, maxLength)}...`;
401
+ }
402
+
403
+ //#endregion
404
+ //#region src/terminal/table.ts
405
+ /**
406
+ * Displays data in a formatted table in the terminal.
407
+ *
408
+ * @param title - Title to display above the table
409
+ * @param data - Array of objects to display in table format
410
+ * @example
411
+ * import { table } from "@settlemint/sdk-utils/terminal";
412
+ *
413
+ * const data = [
414
+ * { name: "Item 1", value: 100 },
415
+ * { name: "Item 2", value: 200 }
416
+ * ];
417
+ *
418
+ * table("My Table", data);
419
+ */
420
+ function table(title, data) {
421
+ if (!shouldPrint()) {
422
+ return;
423
+ }
424
+ note(title);
425
+ if (!data || data.length === 0) {
426
+ note("No data to display");
427
+ return;
428
+ }
429
+ const columnKeys = Object.keys(data[0]);
430
+ const table$1 = new Table({ columns: columnKeys.map((key) => ({
431
+ name: key,
432
+ title: whiteBright(camelCaseToWords(key)),
433
+ alignment: "left"
434
+ })) });
435
+ table$1.addRows(data);
436
+ table$1.printTable();
437
+ }
438
+
439
+ //#endregion
440
+ export { CancelError, CommandError, SpinnerError, ascii, cancel, executeCommand, intro, list, maskTokens, note, outro, spinner, table };
441
+ //# sourceMappingURL=terminal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"terminal.js","names":["output: string","msg: string","message: string","code: number","output: string[]","command: string","args: string[]","options?: ExecuteCommandOptions","data: Buffer | string","msg: string","message: string","level: \"info\" | \"warn\"","title: string","items: Array<string | string[]>","msg: string","message: string","originalError: Error","options: SpinnerOptions<R>","error: Error","spinner","val: string","s: string","value: string","maxLength: number","title: string","data: unknown[]","table"],"sources":["../src/terminal/should-print.ts","../src/terminal/ascii.ts","../src/logging/mask-tokens.ts","../src/terminal/cancel.ts","../src/terminal/execute-command.ts","../src/terminal/intro.ts","../src/terminal/note.ts","../src/terminal/list.ts","../src/terminal/outro.ts","../src/terminal/spinner.ts","../src/string.ts","../src/terminal/table.ts"],"sourcesContent":["/**\n * Returns true if the terminal should print, false otherwise.\n * @returns true if the terminal should print, false otherwise.\n */\nexport function shouldPrint() {\n return process.env.SETTLEMINT_DISABLE_TERMINAL !== \"true\";\n}\n","import { magentaBright } from \"yoctocolors\";\nimport { shouldPrint } from \"./should-print.js\";\n\n/**\n * Prints the SettleMint ASCII art logo to the console in magenta color.\n * Used for CLI branding and visual identification.\n *\n * @example\n * import { ascii } from \"@settlemint/sdk-utils/terminal\";\n *\n * // Prints the SettleMint logo\n * ascii();\n */\nexport const ascii = (): void => {\n if (!shouldPrint()) {\n return;\n }\n console.log(\n magentaBright(`\n _________ __ __ .__ _____ .__ __\n / _____/ _____/ |__/ |_| | ____ / \\\\ |__| _____/ |_\n \\\\_____ \\\\_/ __ \\\\ __\\\\ __\\\\ | _/ __ \\\\ / \\\\ / \\\\| |/ \\\\ __\\\\\n / \\\\ ___/| | | | | |_\\\\ ___// Y \\\\ | | \\\\ |\n/_________/\\\\_____>__| |__| |____/\\\\_____>____|____/__|___|__/__|\n`),\n );\n};\n","/**\n * Masks sensitive SettleMint tokens in output text by replacing them with asterisks.\n * Handles personal access tokens (PAT), application access tokens (AAT), and service account tokens (SAT).\n *\n * @param output - The text string that may contain sensitive tokens\n * @returns The text with any sensitive tokens masked with asterisks\n * @example\n * import { maskTokens } from \"@settlemint/sdk-utils/terminal\";\n *\n * // Masks a token in text\n * const masked = maskTokens(\"Token: sm_pat_****\"); // \"Token: ***\"\n */\nexport const maskTokens = (output: string): string => {\n return output.replace(/sm_(pat|aat|sat)_[0-9a-zA-Z]+/g, \"***\");\n};\n","import { maskTokens } from \"@/logging/mask-tokens.js\";\nimport { inverse, redBright } from \"yoctocolors\";\n\n/**\n * Error class used to indicate that the operation was cancelled.\n * This error is used to signal that the operation should be aborted.\n */\nexport class CancelError extends Error {}\n\n/**\n * Displays an error message in red inverse text and throws a CancelError.\n * Used to terminate execution with a visible error message.\n * Any sensitive tokens in the message are masked before display.\n *\n * @param msg - The error message to display\n * @returns never - Function does not return as it throws an error\n * @example\n * import { cancel } from \"@settlemint/sdk-utils/terminal\";\n *\n * // Exits process with error message\n * cancel(\"An error occurred\");\n */\nexport const cancel = (msg: string): never => {\n console.log(\"\");\n console.log(inverse(redBright(maskTokens(msg))));\n console.log(\"\");\n throw new CancelError(msg);\n};\n","import { type SpawnOptionsWithoutStdio, spawn } from \"node:child_process\";\nimport { maskTokens } from \"../logging/mask-tokens.js\";\n\n/**\n * Options for executing a command, extending SpawnOptionsWithoutStdio\n */\nexport interface ExecuteCommandOptions extends SpawnOptionsWithoutStdio {\n /** Whether to suppress output to stdout/stderr */\n silent?: boolean;\n}\n\n/**\n * Error class for command execution errors\n * @extends Error\n */\nexport class CommandError extends Error {\n /**\n * Constructs a new CommandError\n * @param message - The error message\n * @param code - The exit code of the command\n * @param output - The output of the command\n */\n constructor(\n message: string,\n public readonly code: number,\n public readonly output: string[],\n ) {\n super(message);\n }\n}\n\n/**\n * Executes a command with the given arguments in a child process.\n * Pipes stdin to the child process and captures stdout/stderr output.\n * Masks any sensitive tokens in the output before displaying or returning.\n *\n * @param command - The command to execute\n * @param args - Array of arguments to pass to the command\n * @param options - Options for customizing command execution\n * @returns Array of output strings from stdout and stderr\n * @throws {CommandError} If the process fails to start or exits with non-zero code\n * @example\n * import { executeCommand } from \"@settlemint/sdk-utils/terminal\";\n *\n * // Execute git clone\n * await executeCommand(\"git\", [\"clone\", \"repo-url\"]);\n *\n * // Execute silently\n * await executeCommand(\"npm\", [\"install\"], { silent: true });\n */\nexport async function executeCommand(\n command: string,\n args: string[],\n options?: ExecuteCommandOptions,\n): Promise<string[]> {\n const { silent, ...spawnOptions } = options ?? {};\n const child = spawn(command, args, { ...spawnOptions, env: { ...process.env, ...options?.env } });\n process.stdin.pipe(child.stdin);\n const output: string[] = [];\n return new Promise((resolve, reject) => {\n child.stdout.on(\"data\", (data: Buffer | string) => {\n const maskedData = maskTokens(data.toString());\n if (!silent) {\n process.stdout.write(maskedData);\n }\n output.push(maskedData);\n });\n child.stderr.on(\"data\", (data: Buffer | string) => {\n const maskedData = maskTokens(data.toString());\n if (!silent) {\n process.stderr.write(maskedData);\n }\n output.push(maskedData);\n });\n child.on(\"error\", (err) => {\n process.stdin.unpipe(child.stdin);\n reject(new CommandError(err.message, \"code\" in err && typeof err.code === \"number\" ? err.code : 1, output));\n });\n child.on(\"close\", (code) => {\n process.stdin.unpipe(child.stdin);\n if (code === 0 || code === null || code === 143) {\n resolve(output);\n return;\n }\n reject(new CommandError(`Command \"${command}\" exited with code ${code}`, code, output));\n });\n });\n}\n","import { maskTokens } from \"@/logging/mask-tokens.js\";\nimport { magentaBright } from \"yoctocolors\";\nimport { shouldPrint } from \"./should-print.js\";\n\n/**\n * Displays an introductory message in magenta text with padding.\n * Any sensitive tokens in the message are masked before display.\n *\n * @param msg - The message to display as introduction\n * @example\n * import { intro } from \"@settlemint/sdk-utils/terminal\";\n *\n * // Display intro message\n * intro(\"Starting deployment...\");\n */\nexport const intro = (msg: string): void => {\n if (!shouldPrint()) {\n return;\n }\n console.log(\"\");\n console.log(magentaBright(maskTokens(msg)));\n console.log(\"\");\n};\n","import { maskTokens } from \"@/logging/mask-tokens.js\";\nimport { yellowBright } from \"yoctocolors\";\nimport { shouldPrint } from \"./should-print.js\";\n\n/**\n * Displays a note message with optional warning level formatting.\n * Regular notes are displayed in normal text, while warnings are shown in yellow.\n * Any sensitive tokens in the message are masked before display.\n *\n * @param message - The message to display as a note\n * @param level - The note level: \"info\" (default) or \"warn\" for warning styling\n * @example\n * import { note } from \"@settlemint/sdk-utils/terminal\";\n *\n * // Display info note\n * note(\"Operation completed successfully\");\n *\n * // Display warning note\n * note(\"Low disk space remaining\", \"warn\");\n */\nexport const note = (message: string, level: \"info\" | \"warn\" = \"info\"): void => {\n if (!shouldPrint()) {\n return;\n }\n const maskedMessage = maskTokens(message);\n\n console.log(\"\");\n if (level === \"warn\") {\n console.warn(yellowBright(maskedMessage));\n return;\n }\n\n console.log(maskedMessage);\n};\n","import { note } from \"./note.js\";\n\n/**\n * Displays a list of items in a formatted manner, supporting nested items.\n *\n * @param title - The title of the list\n * @param items - The items to display, can be strings or arrays for nested items\n * @returns The formatted list\n * @example\n * import { list } from \"@settlemint/sdk-utils/terminal\";\n *\n * // Simple list\n * list(\"Use cases\", [\"use case 1\", \"use case 2\", \"use case 3\"]);\n *\n * // Nested list\n * list(\"Providers\", [\n * \"AWS\",\n * [\"us-east-1\", \"eu-west-1\"],\n * \"Azure\",\n * [\"eastus\", \"westeurope\"]\n * ]);\n */\nexport function list(title: string, items: Array<string | string[]>) {\n const formatItems = (items: Array<string | string[]>): string => {\n return items\n .map((item) => {\n if (Array.isArray(item)) {\n return item.map((subItem) => ` • ${subItem}`).join(\"\\n\");\n }\n return ` • ${item}`;\n })\n .join(\"\\n\");\n };\n\n return note(`${title}:\\n\\n${formatItems(items)}`);\n}\n","import { maskTokens } from \"@/logging/mask-tokens.js\";\nimport { shouldPrint } from \"@/terminal/should-print.js\";\nimport { greenBright, inverse } from \"yoctocolors\";\n\n/**\n * Displays a closing message in green inverted text with padding.\n * Any sensitive tokens in the message are masked before display.\n *\n * @param msg - The message to display as conclusion\n * @example\n * import { outro } from \"@settlemint/sdk-utils/terminal\";\n *\n * // Display outro message\n * outro(\"Deployment completed successfully!\");\n */\nexport const outro = (msg: string): void => {\n if (!shouldPrint()) {\n return;\n }\n console.log(\"\");\n console.log(inverse(greenBright(maskTokens(msg))));\n console.log(\"\");\n};\n","import isInCi from \"is-in-ci\";\nimport yoctoSpinner, { type Spinner } from \"yocto-spinner\";\nimport { redBright } from \"yoctocolors\";\nimport { maskTokens } from \"../logging/mask-tokens.js\";\nimport { note } from \"./note.js\";\nimport { shouldPrint } from \"./should-print.js\";\n\n/**\n * Error class used to indicate that the spinner operation failed.\n * This error is used to signal that the operation should be aborted.\n */\nexport class SpinnerError extends Error {\n constructor(\n message: string,\n public readonly originalError: Error,\n ) {\n super(message);\n this.name = \"SpinnerError\";\n }\n}\n\n/**\n * Options for configuring the spinner behavior\n */\nexport interface SpinnerOptions<R> {\n /** Message to display when spinner starts */\n startMessage: string;\n /** Async task to execute while spinner is active */\n task: (spinner?: Spinner) => Promise<R>;\n /** Message to display when spinner completes successfully */\n stopMessage: string;\n}\n\n/**\n * Displays a loading spinner while executing an async task.\n * Shows progress with start/stop messages and handles errors.\n * Spinner is disabled in CI environments.\n *\n * @param options - Configuration options for the spinner\n * @returns The result from the executed task\n * @throws Will exit process with code 1 if task fails\n * @example\n * import { spinner } from \"@settlemint/sdk-utils/terminal\";\n *\n * // Show spinner during async task\n * const result = await spinner({\n * startMessage: \"Deploying...\",\n * task: async () => {\n * // Async work here\n * return \"success\";\n * },\n * stopMessage: \"Deployed successfully!\"\n * });\n */\nexport const spinner = async <R>(options: SpinnerOptions<R>): Promise<R> => {\n const handleError = (error: Error) => {\n const errorMessage = maskTokens(error.message);\n note(redBright(`${errorMessage}\\n\\n${error.stack}`));\n throw new SpinnerError(errorMessage, error);\n };\n if (isInCi || !shouldPrint()) {\n try {\n return await options.task();\n } catch (err) {\n return handleError(err as Error);\n }\n }\n const spinner = yoctoSpinner({ stream: process.stdout }).start(options.startMessage);\n try {\n const result = await options.task(spinner);\n spinner.success(options.stopMessage);\n // Ensure spinner success message renders before proceeding to avoid\n // terminal output overlap issues with subsequent messages\n await new Promise((resolve) => process.nextTick(resolve));\n return result;\n } catch (err) {\n spinner.error(redBright(`${options.startMessage} --> Error!`));\n return handleError(err as Error);\n }\n};\n","/**\n * Capitalizes the first letter of a string.\n *\n * @param val - The string to capitalize\n * @returns The input string with its first letter capitalized\n *\n * @example\n * import { capitalizeFirstLetter } from \"@settlemint/sdk-utils\";\n *\n * const capitalized = capitalizeFirstLetter(\"hello\");\n * // Returns: \"Hello\"\n */\nexport function capitalizeFirstLetter(val: string) {\n return String(val).charAt(0).toUpperCase() + String(val).slice(1);\n}\n\n/**\n * Converts a camelCase string to a human-readable string.\n *\n * @param s - The camelCase string to convert\n * @returns The human-readable string\n *\n * @example\n * import { camelCaseToWords } from \"@settlemint/sdk-utils\";\n *\n * const words = camelCaseToWords(\"camelCaseString\");\n * // Returns: \"Camel Case String\"\n */\nexport function camelCaseToWords(s: string) {\n const result = s.replace(/([a-z])([A-Z])/g, \"$1 $2\");\n const withSpaces = result.replace(/([A-Z])([a-z])/g, \" $1$2\");\n const capitalized = capitalizeFirstLetter(withSpaces);\n return capitalized.replace(/\\s+/g, \" \").trim();\n}\n\n/**\n * Replaces underscores and hyphens with spaces.\n *\n * @param s - The string to replace underscores and hyphens with spaces\n * @returns The input string with underscores and hyphens replaced with spaces\n *\n * @example\n * import { replaceUnderscoresAndHyphensWithSpaces } from \"@settlemint/sdk-utils\";\n *\n * const result = replaceUnderscoresAndHyphensWithSpaces(\"Already_Spaced-Second\");\n * // Returns: \"Already Spaced Second\"\n */\nexport function replaceUnderscoresAndHyphensWithSpaces(s: string) {\n return s.replace(/[-_]/g, \" \");\n}\n\n/**\n * Truncates a string to a maximum length and appends \"...\" if it is longer.\n *\n * @param value - The string to truncate\n * @param maxLength - The maximum length of the string\n * @returns The truncated string or the original string if it is shorter than the maximum length\n *\n * @example\n * import { truncate } from \"@settlemint/sdk-utils\";\n *\n * const truncated = truncate(\"Hello, world!\", 10);\n * // Returns: \"Hello, wor...\"\n */\nexport function truncate(value: string, maxLength: number) {\n if (value.length <= maxLength) {\n return value;\n }\n return `${value.slice(0, maxLength)}...`;\n}\n","import { camelCaseToWords } from \"@/string.js\";\nimport { Table } from \"console-table-printer\";\nimport { whiteBright } from \"yoctocolors\";\nimport { note } from \"./note.js\";\nimport { shouldPrint } from \"./should-print.js\";\n/**\n * Displays data in a formatted table in the terminal.\n *\n * @param title - Title to display above the table\n * @param data - Array of objects to display in table format\n * @example\n * import { table } from \"@settlemint/sdk-utils/terminal\";\n *\n * const data = [\n * { name: \"Item 1\", value: 100 },\n * { name: \"Item 2\", value: 200 }\n * ];\n *\n * table(\"My Table\", data);\n */\nexport function table(title: string, data: unknown[]): void {\n if (!shouldPrint()) {\n return;\n }\n\n note(title);\n\n if (!data || data.length === 0) {\n note(\"No data to display\");\n return;\n }\n\n const columnKeys = Object.keys(data[0] as Record<string, unknown>);\n const table = new Table({\n columns: columnKeys.map((key) => ({\n name: key,\n title: whiteBright(camelCaseToWords(key)),\n alignment: \"left\",\n })),\n });\n table.addRows(data);\n table.printTable();\n}\n"],"mappings":";;;;;;;;;;;AAIA,SAAgB,cAAc;AAC5B,QAAO,QAAQ,IAAI,gCAAgC;AACpD;;;;;;;;;;;;;;ACOD,MAAa,QAAQ,MAAY;AAC/B,MAAK,aAAa,EAAE;AAClB;CACD;AACD,SAAQ,IACN,eAAe;;;;;;EAMjB,CACC;AACF;;;;;;;;;;;;;;;;ACdD,MAAa,aAAa,CAACA,WAA2B;AACpD,QAAO,OAAO,QAAQ,kCAAkC,MAAM;AAC/D;;;;;;;;ACPD,IAAa,cAAb,cAAiC,MAAM,CAAE;;;;;;;;;;;;;;AAezC,MAAa,SAAS,CAACC,QAAuB;AAC5C,SAAQ,IAAI,GAAG;AACf,SAAQ,IAAI,QAAQ,UAAU,WAAW,IAAI,CAAC,CAAC,CAAC;AAChD,SAAQ,IAAI,GAAG;AACf,OAAM,IAAI,YAAY;AACvB;;;;;;;;ACZD,IAAa,eAAb,cAAkC,MAAM;;;;;;;CAOtC,YACEC,SACgBC,MACAC,QAChB;AACA,QAAM,QAAQ;EAHE;EACA;CAGjB;AACF;;;;;;;;;;;;;;;;;;;;AAqBD,eAAsB,eACpBC,SACAC,MACAC,SACmB;CACnB,MAAM,EAAE,OAAQ,GAAG,cAAc,GAAG,WAAW,CAAE;CACjD,MAAM,QAAQ,MAAM,SAAS,MAAM;EAAE,GAAG;EAAc,KAAK;GAAE,GAAG,QAAQ;GAAK,GAAG,SAAS;EAAK;CAAE,EAAC;AACjG,SAAQ,MAAM,KAAK,MAAM,MAAM;CAC/B,MAAMH,SAAmB,CAAE;AAC3B,QAAO,IAAI,QAAQ,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/url.cjs ADDED
@@ -0,0 +1,25 @@
1
+
2
+ //#region src/url.ts
3
+ /**
4
+ * Extracts the base URL before a specific segment in a URL.
5
+ *
6
+ * @param baseUrl - The base URL to extract the path from
7
+ * @param pathSegment - The path segment to start from
8
+ * @returns The base URL before the specified segment
9
+ * @example
10
+ * ```typescript
11
+ * import { extractBaseUrlBeforeSegment } from "@settlemint/sdk-utils/url";
12
+ *
13
+ * const baseUrl = extractBaseUrlBeforeSegment("https://example.com/api/v1/subgraphs/name/my-subgraph", "/subgraphs");
14
+ * // Returns: "https://example.com/api/v1"
15
+ * ```
16
+ */
17
+ function extractBaseUrlBeforeSegment(baseUrl, pathSegment) {
18
+ const url = new URL(baseUrl);
19
+ const segmentIndex = url.pathname.indexOf(pathSegment);
20
+ return url.origin + (segmentIndex >= 0 ? url.pathname.substring(0, segmentIndex) : url.pathname);
21
+ }
22
+
23
+ //#endregion
24
+ exports.extractBaseUrlBeforeSegment = extractBaseUrlBeforeSegment;
25
+ //# sourceMappingURL=url.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"url.cjs","names":["baseUrl: string","pathSegment: string"],"sources":["../src/url.ts"],"sourcesContent":["/**\n * Extracts the base URL before a specific segment in a URL.\n *\n * @param baseUrl - The base URL to extract the path from\n * @param pathSegment - The path segment to start from\n * @returns The base URL before the specified segment\n * @example\n * ```typescript\n * import { extractBaseUrlBeforeSegment } from \"@settlemint/sdk-utils/url\";\n *\n * const baseUrl = extractBaseUrlBeforeSegment(\"https://example.com/api/v1/subgraphs/name/my-subgraph\", \"/subgraphs\");\n * // Returns: \"https://example.com/api/v1\"\n * ```\n */\nexport function extractBaseUrlBeforeSegment(baseUrl: string, pathSegment: string) {\n const url = new URL(baseUrl);\n const segmentIndex = url.pathname.indexOf(pathSegment);\n return url.origin + (segmentIndex >= 0 ? url.pathname.substring(0, segmentIndex) : url.pathname);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAcA,SAAgB,4BAA4BA,SAAiBC,aAAqB;CAChF,MAAM,MAAM,IAAI,IAAI;CACpB,MAAM,eAAe,IAAI,SAAS,QAAQ,YAAY;AACtD,QAAO,IAAI,UAAU,gBAAgB,IAAI,IAAI,SAAS,UAAU,GAAG,aAAa,GAAG,IAAI;AACxF"}
package/dist/url.d.cts ADDED
@@ -0,0 +1,20 @@
1
+ //#region src/url.d.ts
2
+ /**
3
+ * Extracts the base URL before a specific segment in a URL.
4
+ *
5
+ * @param baseUrl - The base URL to extract the path from
6
+ * @param pathSegment - The path segment to start from
7
+ * @returns The base URL before the specified segment
8
+ * @example
9
+ * ```typescript
10
+ * import { extractBaseUrlBeforeSegment } from "@settlemint/sdk-utils/url";
11
+ *
12
+ * const baseUrl = extractBaseUrlBeforeSegment("https://example.com/api/v1/subgraphs/name/my-subgraph", "/subgraphs");
13
+ * // Returns: "https://example.com/api/v1"
14
+ * ```
15
+ */
16
+ declare function extractBaseUrlBeforeSegment(baseUrl: string, pathSegment: string): string;
17
+
18
+ //#endregion
19
+ export { extractBaseUrlBeforeSegment };
20
+ //# sourceMappingURL=url.d.cts.map
package/dist/url.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ //#region src/url.d.ts
2
+ /**
3
+ * Extracts the base URL before a specific segment in a URL.
4
+ *
5
+ * @param baseUrl - The base URL to extract the path from
6
+ * @param pathSegment - The path segment to start from
7
+ * @returns The base URL before the specified segment
8
+ * @example
9
+ * ```typescript
10
+ * import { extractBaseUrlBeforeSegment } from "@settlemint/sdk-utils/url";
11
+ *
12
+ * const baseUrl = extractBaseUrlBeforeSegment("https://example.com/api/v1/subgraphs/name/my-subgraph", "/subgraphs");
13
+ * // Returns: "https://example.com/api/v1"
14
+ * ```
15
+ */
16
+ declare function extractBaseUrlBeforeSegment(baseUrl: string, pathSegment: string): string;
17
+
18
+ //#endregion
19
+ export { extractBaseUrlBeforeSegment };
20
+ //# sourceMappingURL=url.d.ts.map
package/dist/url.js ADDED
@@ -0,0 +1,24 @@
1
+ //#region src/url.ts
2
+ /**
3
+ * Extracts the base URL before a specific segment in a URL.
4
+ *
5
+ * @param baseUrl - The base URL to extract the path from
6
+ * @param pathSegment - The path segment to start from
7
+ * @returns The base URL before the specified segment
8
+ * @example
9
+ * ```typescript
10
+ * import { extractBaseUrlBeforeSegment } from "@settlemint/sdk-utils/url";
11
+ *
12
+ * const baseUrl = extractBaseUrlBeforeSegment("https://example.com/api/v1/subgraphs/name/my-subgraph", "/subgraphs");
13
+ * // Returns: "https://example.com/api/v1"
14
+ * ```
15
+ */
16
+ function extractBaseUrlBeforeSegment(baseUrl, pathSegment) {
17
+ const url = new URL(baseUrl);
18
+ const segmentIndex = url.pathname.indexOf(pathSegment);
19
+ return url.origin + (segmentIndex >= 0 ? url.pathname.substring(0, segmentIndex) : url.pathname);
20
+ }
21
+
22
+ //#endregion
23
+ export { extractBaseUrlBeforeSegment };
24
+ //# sourceMappingURL=url.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"url.js","names":["baseUrl: string","pathSegment: string"],"sources":["../src/url.ts"],"sourcesContent":["/**\n * Extracts the base URL before a specific segment in a URL.\n *\n * @param baseUrl - The base URL to extract the path from\n * @param pathSegment - The path segment to start from\n * @returns The base URL before the specified segment\n * @example\n * ```typescript\n * import { extractBaseUrlBeforeSegment } from \"@settlemint/sdk-utils/url\";\n *\n * const baseUrl = extractBaseUrlBeforeSegment(\"https://example.com/api/v1/subgraphs/name/my-subgraph\", \"/subgraphs\");\n * // Returns: \"https://example.com/api/v1\"\n * ```\n */\nexport function extractBaseUrlBeforeSegment(baseUrl: string, pathSegment: string) {\n const url = new URL(baseUrl);\n const segmentIndex = url.pathname.indexOf(pathSegment);\n return url.origin + (segmentIndex >= 0 ? url.pathname.substring(0, segmentIndex) : url.pathname);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,SAAgB,4BAA4BA,SAAiBC,aAAqB;CAChF,MAAM,MAAM,IAAI,IAAI;CACpB,MAAM,eAAe,IAAI,SAAS,QAAQ,YAAY;AACtD,QAAO,IAAI,UAAU,gBAAgB,IAAI,IAAI,SAAS,UAAU,GAAG,aAAa,GAAG,IAAI;AACxF"}