@settlemint/sdk-utils 2.3.2-pr6cb5dd2e → 2.3.2-pr74f654b5

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 (89) hide show
  1. package/README.md +51 -7
  2. package/dist/environment.cjs +25 -408
  3. package/dist/environment.d.cts +3 -176
  4. package/dist/environment.d.ts +3 -176
  5. package/dist/environment.js +4 -0
  6. package/dist/filesystem.cjs +39 -123
  7. package/dist/filesystem.d.cts +4 -59
  8. package/dist/filesystem.d.ts +4 -59
  9. package/dist/filesystem.js +5 -0
  10. package/dist/http.cjs +35 -147
  11. package/dist/http.d.cts +4 -50
  12. package/dist/http.d.ts +4 -50
  13. package/dist/http.js +5 -0
  14. package/dist/index.cjs +27 -184
  15. package/dist/index.d.cts +4 -122
  16. package/dist/index.d.ts +4 -122
  17. package/dist/index.js +7 -0
  18. package/dist/json.cjs +83 -0
  19. package/dist/json.cjs.map +1 -0
  20. package/dist/json.d.cts +56 -0
  21. package/dist/json.d.ts +56 -0
  22. package/dist/json.js +80 -0
  23. package/dist/json.js.map +1 -0
  24. package/dist/logging.cjs +34 -141
  25. package/dist/logging.d.cts +4 -70
  26. package/dist/logging.d.ts +4 -70
  27. package/dist/logging.js +5 -0
  28. package/dist/package-manager.cjs +51 -196
  29. package/dist/package-manager.d.cts +7 -114
  30. package/dist/package-manager.d.ts +7 -114
  31. package/dist/package-manager.js +9 -0
  32. package/dist/retry.cjs +69 -0
  33. package/dist/retry.cjs.map +1 -0
  34. package/dist/retry.d.cts +19 -0
  35. package/dist/retry.d.ts +19 -0
  36. package/dist/retry.js +46 -0
  37. package/dist/retry.js.map +1 -0
  38. package/dist/runtime.cjs +38 -42
  39. package/dist/runtime.d.cts +2 -32
  40. package/dist/runtime.d.ts +2 -32
  41. package/dist/runtime.js +3 -0
  42. package/dist/string.cjs +76 -0
  43. package/dist/string.cjs.map +1 -0
  44. package/dist/string.d.cts +58 -0
  45. package/dist/string.d.ts +58 -0
  46. package/dist/string.js +72 -0
  47. package/dist/string.js.map +1 -0
  48. package/dist/terminal.cjs +91 -258
  49. package/dist/terminal.d.cts +11 -219
  50. package/dist/terminal.d.ts +11 -219
  51. package/dist/terminal.js +12 -0
  52. package/dist/url.cjs +25 -0
  53. package/dist/url.cjs.map +1 -0
  54. package/dist/url.d.cts +20 -0
  55. package/dist/url.d.ts +20 -0
  56. package/dist/url.js +24 -0
  57. package/dist/url.js.map +1 -0
  58. package/dist/validation.cjs +89 -183
  59. package/dist/validation.d.cts +7 -239
  60. package/dist/validation.d.ts +7 -239
  61. package/dist/validation.js +8 -0
  62. package/package.json +6 -6
  63. package/dist/environment.cjs.map +0 -1
  64. package/dist/environment.mjs +0 -383
  65. package/dist/environment.mjs.map +0 -1
  66. package/dist/filesystem.cjs.map +0 -1
  67. package/dist/filesystem.mjs +0 -105
  68. package/dist/filesystem.mjs.map +0 -1
  69. package/dist/http.cjs.map +0 -1
  70. package/dist/http.mjs +0 -129
  71. package/dist/http.mjs.map +0 -1
  72. package/dist/index.cjs.map +0 -1
  73. package/dist/index.mjs +0 -156
  74. package/dist/index.mjs.map +0 -1
  75. package/dist/logging.cjs.map +0 -1
  76. package/dist/logging.mjs +0 -123
  77. package/dist/logging.mjs.map +0 -1
  78. package/dist/package-manager.cjs.map +0 -1
  79. package/dist/package-manager.mjs +0 -167
  80. package/dist/package-manager.mjs.map +0 -1
  81. package/dist/runtime.cjs.map +0 -1
  82. package/dist/runtime.mjs +0 -23
  83. package/dist/runtime.mjs.map +0 -1
  84. package/dist/terminal.cjs.map +0 -1
  85. package/dist/terminal.mjs +0 -230
  86. package/dist/terminal.mjs.map +0 -1
  87. package/dist/validation.cjs.map +0 -1
  88. package/dist/validation.mjs +0 -159
  89. package/dist/validation.mjs.map +0 -1
@@ -0,0 +1,5 @@
1
+ import { projectRoot } from "./filesystem/project-root.js";
2
+ import { exists } from "./filesystem/exists.js";
3
+ import { findMonoRepoPackages, findMonoRepoRoot } from "./filesystem/mono-repo.js";
4
+
5
+ export { exists, findMonoRepoPackages, findMonoRepoRoot, projectRoot };
package/dist/http.cjs CHANGED
@@ -1,157 +1,45 @@
1
- "use strict";
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
8
  var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/http.ts
21
- var http_exports = {};
22
- __export(http_exports, {
23
- fetchWithRetry: () => fetchWithRetry,
24
- graphqlFetchWithRetry: () => graphqlFetchWithRetry
25
- });
26
- module.exports = __toCommonJS(http_exports);
27
-
28
- // src/logging/mask-tokens.ts
29
- var maskTokens = (output) => {
30
- return output.replace(/sm_(pat|aat|sat)_[0-9a-zA-Z]+/g, "***");
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
31
17
  };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
32
22
 
33
- // src/logging/logger.ts
34
- function createLogger(options = {}) {
35
- const { level = "warn", prefix = "" } = options;
36
- const logLevels = {
37
- debug: 0,
38
- info: 1,
39
- warn: 2,
40
- error: 3,
41
- none: 4
42
- };
43
- const currentLevelValue = logLevels[level];
44
- const formatArgs = (args) => {
45
- if (args.length === 0 || args.every((arg) => arg === void 0 || arg === null)) {
46
- return "";
47
- }
48
- const formatted = args.map((arg) => {
49
- if (arg instanceof Error) {
50
- return `
51
- ${arg.stack || arg.message}`;
52
- }
53
- if (typeof arg === "object" && arg !== null) {
54
- return `
55
- ${JSON.stringify(arg, null, 2)}`;
56
- }
57
- return ` ${String(arg)}`;
58
- }).join("");
59
- return `, args:${formatted}`;
60
- };
61
- const shouldLog = (level2) => {
62
- return logLevels[level2] >= currentLevelValue;
63
- };
64
- return {
65
- debug: (message, ...args) => {
66
- if (shouldLog("debug")) {
67
- console.debug(`\x1B[32m${prefix}[DEBUG] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1B[0m`);
68
- }
69
- },
70
- info: (message, ...args) => {
71
- if (shouldLog("info")) {
72
- console.info(`\x1B[34m${prefix}[INFO] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1B[0m`);
73
- }
74
- },
75
- warn: (message, ...args) => {
76
- if (shouldLog("warn")) {
77
- console.warn(`\x1B[33m${prefix}[WARN] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1B[0m`);
78
- }
79
- },
80
- error: (message, ...args) => {
81
- if (shouldLog("error")) {
82
- console.error(`\x1B[31m${prefix}[ERROR] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1B[0m`);
83
- }
84
- }
85
- };
86
- }
87
- var logger = createLogger();
23
+ //#endregion
24
+ const src_http_fetch_with_retry_js = __toESM(require("./http/fetch-with-retry.js"));
25
+ const src_http_graphql_fetch_with_retry_js = __toESM(require("./http/graphql-fetch-with-retry.js"));
26
+ const src_http_headers_js = __toESM(require("./http/headers.js"));
88
27
 
89
- // src/retry.ts
90
- async function retryWhenFailed(fn, maxRetries = 5, initialSleepTime = 1e3, stopOnError) {
91
- let retries = 0;
92
- const maxAttempts = maxRetries + 1;
93
- while (retries < maxAttempts) {
94
- try {
95
- return await fn();
96
- } catch (e) {
97
- const error = e;
98
- if (typeof stopOnError === "function") {
99
- if (stopOnError(error)) {
100
- throw error;
101
- }
102
- }
103
- if (retries >= maxRetries) {
104
- throw e;
105
- }
106
- const baseDelay = 2 ** retries * initialSleepTime;
107
- const jitterAmount = initialSleepTime * (Math.random() / 10);
108
- const delay = baseDelay + jitterAmount;
109
- retries += 1;
110
- logger.warn(
111
- `An error occurred ${error.message}, retrying in ${delay.toFixed(0)}ms (retry ${retries} of ${maxRetries})...`
112
- );
113
- await new Promise((resolve) => setTimeout(resolve, delay));
114
- }
28
+ Object.defineProperty(exports, 'appendHeaders', {
29
+ enumerable: true,
30
+ get: function () {
31
+ return src_http_headers_js.appendHeaders;
115
32
  }
116
- throw new Error("Retry failed");
117
- }
118
-
119
- // src/http/fetch-with-retry.ts
120
- async function fetchWithRetry(input, init, maxRetries = 5, initialSleepTime = 3e3) {
121
- return retryWhenFailed(
122
- async () => {
123
- const response = await fetch(input, init);
124
- if (response.ok) {
125
- return response;
126
- }
127
- if (response.status < 500 && response.status !== 429 && response.status !== 408 && response.status !== 0) {
128
- return response;
129
- }
130
- throw new Error(`HTTP error! status: ${response.status} ${response.statusText}`);
131
- },
132
- maxRetries,
133
- initialSleepTime
134
- );
135
- }
136
-
137
- // src/http/graphql-fetch-with-retry.ts
138
- async function graphqlFetchWithRetry(input, init, maxRetries = 5, initialSleepTime = 3e3) {
139
- return retryWhenFailed(
140
- async () => {
141
- const response = await fetchWithRetry(input, init);
142
- const json = await response.json();
143
- if (json.errors) {
144
- throw new Error(`GraphQL errors in response: ${json.errors.map((error) => error.message).join(", ")}`);
145
- }
146
- return json.data;
147
- },
148
- maxRetries,
149
- initialSleepTime
150
- );
151
- }
152
- // Annotate the CommonJS export names for ESM import in node:
153
- 0 && (module.exports = {
154
- fetchWithRetry,
155
- graphqlFetchWithRetry
156
33
  });
157
- //# sourceMappingURL=http.cjs.map
34
+ Object.defineProperty(exports, 'fetchWithRetry', {
35
+ enumerable: true,
36
+ get: function () {
37
+ return src_http_fetch_with_retry_js.fetchWithRetry;
38
+ }
39
+ });
40
+ Object.defineProperty(exports, 'graphqlFetchWithRetry', {
41
+ enumerable: true,
42
+ get: function () {
43
+ return src_http_graphql_fetch_with_retry_js.graphqlFetchWithRetry;
44
+ }
45
+ });
package/dist/http.d.cts CHANGED
@@ -1,50 +1,4 @@
1
- /**
2
- * Retry an HTTP request with exponential backoff and jitter.
3
- * Only retries on server errors (5xx), rate limits (429), timeouts (408), and network errors.
4
- *
5
- * @param input - The URL or Request object to fetch
6
- * @param init - The fetch init options
7
- * @param maxRetries - Maximum number of retry attempts
8
- * @param initialSleepTime - Initial sleep time between retries in ms
9
- * @returns The fetch Response
10
- * @throws Error if all retries fail
11
- * @example
12
- * import { fetchWithRetry } from "@settlemint/sdk-utils/http";
13
- *
14
- * const response = await fetchWithRetry("https://api.example.com/data");
15
- */
16
- declare function fetchWithRetry(input: RequestInfo | URL, init?: RequestInit, maxRetries?: number, initialSleepTime?: number): Promise<Response>;
17
-
18
- /**
19
- * Executes a GraphQL request with automatic retries using exponential backoff and jitter.
20
- * Only retries on server errors (5xx), rate limits (429), timeouts (408), and network errors.
21
- * Will also retry if the GraphQL response contains errors.
22
- *
23
- * @param input - The URL or Request object for the GraphQL endpoint
24
- * @param init - Optional fetch configuration options
25
- * @param maxRetries - Maximum retry attempts before failing (default: 5)
26
- * @param initialSleepTime - Initial delay between retries in milliseconds (default: 3000)
27
- * @returns The parsed GraphQL response data
28
- * @throws Error if all retries fail or if GraphQL response contains errors
29
- * @example
30
- * import { graphqlFetchWithRetry } from "@settlemint/sdk-utils/http";
31
- *
32
- * const data = await graphqlFetchWithRetry<{ user: { id: string } }>(
33
- * "https://api.example.com/graphql",
34
- * {
35
- * method: "POST",
36
- * headers: { "Content-Type": "application/json" },
37
- * body: JSON.stringify({
38
- * query: `query GetUser($id: ID!) {
39
- * user(id: $id) {
40
- * id
41
- * }
42
- * }`,
43
- * variables: { id: "123" }
44
- * })
45
- * }
46
- * );
47
- */
48
- declare function graphqlFetchWithRetry<Data>(input: RequestInfo | URL, init?: RequestInit, maxRetries?: number, initialSleepTime?: number): Promise<Data>;
49
-
50
- export { fetchWithRetry, graphqlFetchWithRetry };
1
+ import { fetchWithRetry } from "./http/fetch-with-retry.js";
2
+ import { graphqlFetchWithRetry } from "./http/graphql-fetch-with-retry.js";
3
+ import { appendHeaders } from "./http/headers.js";
4
+ export { appendHeaders, fetchWithRetry, graphqlFetchWithRetry };
package/dist/http.d.ts CHANGED
@@ -1,50 +1,4 @@
1
- /**
2
- * Retry an HTTP request with exponential backoff and jitter.
3
- * Only retries on server errors (5xx), rate limits (429), timeouts (408), and network errors.
4
- *
5
- * @param input - The URL or Request object to fetch
6
- * @param init - The fetch init options
7
- * @param maxRetries - Maximum number of retry attempts
8
- * @param initialSleepTime - Initial sleep time between retries in ms
9
- * @returns The fetch Response
10
- * @throws Error if all retries fail
11
- * @example
12
- * import { fetchWithRetry } from "@settlemint/sdk-utils/http";
13
- *
14
- * const response = await fetchWithRetry("https://api.example.com/data");
15
- */
16
- declare function fetchWithRetry(input: RequestInfo | URL, init?: RequestInit, maxRetries?: number, initialSleepTime?: number): Promise<Response>;
17
-
18
- /**
19
- * Executes a GraphQL request with automatic retries using exponential backoff and jitter.
20
- * Only retries on server errors (5xx), rate limits (429), timeouts (408), and network errors.
21
- * Will also retry if the GraphQL response contains errors.
22
- *
23
- * @param input - The URL or Request object for the GraphQL endpoint
24
- * @param init - Optional fetch configuration options
25
- * @param maxRetries - Maximum retry attempts before failing (default: 5)
26
- * @param initialSleepTime - Initial delay between retries in milliseconds (default: 3000)
27
- * @returns The parsed GraphQL response data
28
- * @throws Error if all retries fail or if GraphQL response contains errors
29
- * @example
30
- * import { graphqlFetchWithRetry } from "@settlemint/sdk-utils/http";
31
- *
32
- * const data = await graphqlFetchWithRetry<{ user: { id: string } }>(
33
- * "https://api.example.com/graphql",
34
- * {
35
- * method: "POST",
36
- * headers: { "Content-Type": "application/json" },
37
- * body: JSON.stringify({
38
- * query: `query GetUser($id: ID!) {
39
- * user(id: $id) {
40
- * id
41
- * }
42
- * }`,
43
- * variables: { id: "123" }
44
- * })
45
- * }
46
- * );
47
- */
48
- declare function graphqlFetchWithRetry<Data>(input: RequestInfo | URL, init?: RequestInit, maxRetries?: number, initialSleepTime?: number): Promise<Data>;
49
-
50
- export { fetchWithRetry, graphqlFetchWithRetry };
1
+ import { fetchWithRetry } from "./http/fetch-with-retry.js";
2
+ import { graphqlFetchWithRetry } from "./http/graphql-fetch-with-retry.js";
3
+ import { appendHeaders } from "./http/headers.js";
4
+ export { appendHeaders, fetchWithRetry, graphqlFetchWithRetry };
package/dist/http.js ADDED
@@ -0,0 +1,5 @@
1
+ import { fetchWithRetry } from "./http/fetch-with-retry.js";
2
+ import { graphqlFetchWithRetry } from "./http/graphql-fetch-with-retry.js";
3
+ import { appendHeaders } from "./http/headers.js";
4
+
5
+ export { appendHeaders, fetchWithRetry, graphqlFetchWithRetry };
package/dist/index.cjs CHANGED
@@ -1,190 +1,33 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
1
 
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- camelCaseToWords: () => camelCaseToWords,
24
- capitalizeFirstLetter: () => capitalizeFirstLetter,
25
- extractJsonObject: () => extractJsonObject,
26
- makeJsonStringifiable: () => makeJsonStringifiable,
27
- replaceUnderscoresAndHyphensWithSpaces: () => replaceUnderscoresAndHyphensWithSpaces,
28
- retryWhenFailed: () => retryWhenFailed,
29
- truncate: () => truncate,
30
- tryParseJson: () => tryParseJson
31
- });
32
- module.exports = __toCommonJS(index_exports);
33
-
34
- // src/json.ts
35
- function tryParseJson(value, defaultValue = null) {
36
- try {
37
- const parsed = JSON.parse(value);
38
- if (parsed === void 0 || parsed === null) {
39
- return defaultValue;
40
- }
41
- return parsed;
42
- } catch (err) {
43
- return defaultValue;
44
- }
45
- }
46
- function extractJsonObject(value) {
47
- if (value.length > 5e3) {
48
- throw new Error("Input too long");
49
- }
50
- const result = /\{([\s\S]*)\}/.exec(value);
51
- if (!result) {
52
- return null;
53
- }
54
- return tryParseJson(result[0]);
55
- }
56
- function makeJsonStringifiable(value) {
57
- if (value === void 0 || value === null) {
58
- return value;
59
- }
60
- return tryParseJson(
61
- JSON.stringify(
62
- value,
63
- (_, value2) => typeof value2 === "bigint" ? value2.toString() : value2
64
- // return everything else unchanged
65
- )
66
- );
67
- }
68
2
 
69
- // src/logging/mask-tokens.ts
70
- var maskTokens = (output) => {
71
- return output.replace(/sm_(pat|aat|sat)_[0-9a-zA-Z]+/g, "***");
72
- };
3
+ var src_json_js = require("./json.js");
4
+ Object.keys(src_json_js).forEach(function (k) {
5
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
6
+ enumerable: true,
7
+ get: function () { return src_json_js[k]; }
8
+ });
9
+ });
73
10
 
74
- // src/logging/logger.ts
75
- function createLogger(options = {}) {
76
- const { level = "warn", prefix = "" } = options;
77
- const logLevels = {
78
- debug: 0,
79
- info: 1,
80
- warn: 2,
81
- error: 3,
82
- none: 4
83
- };
84
- const currentLevelValue = logLevels[level];
85
- const formatArgs = (args) => {
86
- if (args.length === 0 || args.every((arg) => arg === void 0 || arg === null)) {
87
- return "";
88
- }
89
- const formatted = args.map((arg) => {
90
- if (arg instanceof Error) {
91
- return `
92
- ${arg.stack || arg.message}`;
93
- }
94
- if (typeof arg === "object" && arg !== null) {
95
- return `
96
- ${JSON.stringify(arg, null, 2)}`;
97
- }
98
- return ` ${String(arg)}`;
99
- }).join("");
100
- return `, args:${formatted}`;
101
- };
102
- const shouldLog = (level2) => {
103
- return logLevels[level2] >= currentLevelValue;
104
- };
105
- return {
106
- debug: (message, ...args) => {
107
- if (shouldLog("debug")) {
108
- console.debug(`\x1B[32m${prefix}[DEBUG] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1B[0m`);
109
- }
110
- },
111
- info: (message, ...args) => {
112
- if (shouldLog("info")) {
113
- console.info(`\x1B[34m${prefix}[INFO] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1B[0m`);
114
- }
115
- },
116
- warn: (message, ...args) => {
117
- if (shouldLog("warn")) {
118
- console.warn(`\x1B[33m${prefix}[WARN] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1B[0m`);
119
- }
120
- },
121
- error: (message, ...args) => {
122
- if (shouldLog("error")) {
123
- console.error(`\x1B[31m${prefix}[ERROR] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1B[0m`);
124
- }
125
- }
126
- };
127
- }
128
- var logger = createLogger();
11
+ var src_retry_js = require("./retry.js");
12
+ Object.keys(src_retry_js).forEach(function (k) {
13
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
14
+ enumerable: true,
15
+ get: function () { return src_retry_js[k]; }
16
+ });
17
+ });
129
18
 
130
- // src/retry.ts
131
- async function retryWhenFailed(fn, maxRetries = 5, initialSleepTime = 1e3, stopOnError) {
132
- let retries = 0;
133
- const maxAttempts = maxRetries + 1;
134
- while (retries < maxAttempts) {
135
- try {
136
- return await fn();
137
- } catch (e) {
138
- const error = e;
139
- if (typeof stopOnError === "function") {
140
- if (stopOnError(error)) {
141
- throw error;
142
- }
143
- }
144
- if (retries >= maxRetries) {
145
- throw e;
146
- }
147
- const baseDelay = 2 ** retries * initialSleepTime;
148
- const jitterAmount = initialSleepTime * (Math.random() / 10);
149
- const delay = baseDelay + jitterAmount;
150
- retries += 1;
151
- logger.warn(
152
- `An error occurred ${error.message}, retrying in ${delay.toFixed(0)}ms (retry ${retries} of ${maxRetries})...`
153
- );
154
- await new Promise((resolve) => setTimeout(resolve, delay));
155
- }
156
- }
157
- throw new Error("Retry failed");
158
- }
19
+ var src_string_js = require("./string.js");
20
+ Object.keys(src_string_js).forEach(function (k) {
21
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
22
+ enumerable: true,
23
+ get: function () { return src_string_js[k]; }
24
+ });
25
+ });
159
26
 
160
- // src/string.ts
161
- function capitalizeFirstLetter(val) {
162
- return String(val).charAt(0).toUpperCase() + String(val).slice(1);
163
- }
164
- function camelCaseToWords(s) {
165
- const result = s.replace(/([a-z])([A-Z])/g, "$1 $2");
166
- const withSpaces = result.replace(/([A-Z])([a-z])/g, " $1$2");
167
- const capitalized = capitalizeFirstLetter(withSpaces);
168
- return capitalized.replace(/\s+/g, " ").trim();
169
- }
170
- function replaceUnderscoresAndHyphensWithSpaces(s) {
171
- return s.replace(/[-_]/g, " ");
172
- }
173
- function truncate(value, maxLength) {
174
- if (value.length <= maxLength) {
175
- return value;
176
- }
177
- return `${value.slice(0, maxLength)}...`;
178
- }
179
- // Annotate the CommonJS export names for ESM import in node:
180
- 0 && (module.exports = {
181
- camelCaseToWords,
182
- capitalizeFirstLetter,
183
- extractJsonObject,
184
- makeJsonStringifiable,
185
- replaceUnderscoresAndHyphensWithSpaces,
186
- retryWhenFailed,
187
- truncate,
188
- tryParseJson
27
+ var src_url_js = require("./url.js");
28
+ Object.keys(src_url_js).forEach(function (k) {
29
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
30
+ enumerable: true,
31
+ get: function () { return src_url_js[k]; }
32
+ });
189
33
  });
190
- //# sourceMappingURL=index.cjs.map
package/dist/index.d.cts CHANGED
@@ -1,122 +1,4 @@
1
- /**
2
- * Attempts to parse a JSON string into a typed value, returning a default value if parsing fails.
3
- *
4
- * @param value - The JSON string to parse
5
- * @param defaultValue - The value to return if parsing fails or results in null/undefined
6
- * @returns The parsed JSON value as type T, or the default value if parsing fails
7
- *
8
- * @example
9
- * import { tryParseJson } from "@settlemint/sdk-utils";
10
- *
11
- * const config = tryParseJson<{ port: number }>(
12
- * '{"port": 3000}',
13
- * { port: 8080 }
14
- * );
15
- * // Returns: { port: 3000 }
16
- *
17
- * const invalid = tryParseJson<string[]>(
18
- * 'invalid json',
19
- * []
20
- * );
21
- * // Returns: []
22
- */
23
- declare function tryParseJson<T>(value: string, defaultValue?: T | null): T | null;
24
- /**
25
- * Extracts a JSON object from a string.
26
- *
27
- * @param value - The string to extract the JSON object from
28
- * @returns The parsed JSON object, or null if no JSON object is found
29
- * @throws {Error} If the input string is too long (longer than 5000 characters)
30
- * @example
31
- * import { extractJsonObject } from "@settlemint/sdk-utils";
32
- *
33
- * const json = extractJsonObject<{ port: number }>(
34
- * 'port info: {"port": 3000}',
35
- * );
36
- * // Returns: { port: 3000 }
37
- */
38
- declare function extractJsonObject<T>(value: string): T | null;
39
- /**
40
- * Converts a value to a JSON stringifiable format.
41
- *
42
- * @param value - The value to convert
43
- * @returns The JSON stringifiable value
44
- *
45
- * @example
46
- * import { makeJsonStringifiable } from "@settlemint/sdk-utils";
47
- *
48
- * const json = makeJsonStringifiable<{ amount: bigint }>({ amount: BigInt(1000) });
49
- * // Returns: '{"amount":"1000"}'
50
- */
51
- declare function makeJsonStringifiable<T>(value: unknown): T;
52
-
53
- /**
54
- * Retry a function when it fails.
55
- * @param fn - The function to retry.
56
- * @param maxRetries - The maximum number of retries.
57
- * @param initialSleepTime - The initial time to sleep between exponential backoff retries.
58
- * @param stopOnError - The function to stop on error.
59
- * @returns The result of the function or undefined if it fails.
60
- * @example
61
- * import { retryWhenFailed } from "@settlemint/sdk-utils";
62
- * import { readFile } from "node:fs/promises";
63
- *
64
- * const result = await retryWhenFailed(() => readFile("/path/to/file.txt"), 3, 1_000);
65
- */
66
- declare function retryWhenFailed<T>(fn: () => Promise<T>, maxRetries?: number, initialSleepTime?: number, stopOnError?: (error: Error) => boolean): Promise<T>;
67
-
68
- /**
69
- * Capitalizes the first letter of a string.
70
- *
71
- * @param val - The string to capitalize
72
- * @returns The input string with its first letter capitalized
73
- *
74
- * @example
75
- * import { capitalizeFirstLetter } from "@settlemint/sdk-utils";
76
- *
77
- * const capitalized = capitalizeFirstLetter("hello");
78
- * // Returns: "Hello"
79
- */
80
- declare function capitalizeFirstLetter(val: string): string;
81
- /**
82
- * Converts a camelCase string to a human-readable string.
83
- *
84
- * @param s - The camelCase string to convert
85
- * @returns The human-readable string
86
- *
87
- * @example
88
- * import { camelCaseToWords } from "@settlemint/sdk-utils";
89
- *
90
- * const words = camelCaseToWords("camelCaseString");
91
- * // Returns: "Camel Case String"
92
- */
93
- declare function camelCaseToWords(s: string): string;
94
- /**
95
- * Replaces underscores and hyphens with spaces.
96
- *
97
- * @param s - The string to replace underscores and hyphens with spaces
98
- * @returns The input string with underscores and hyphens replaced with spaces
99
- *
100
- * @example
101
- * import { replaceUnderscoresAndHyphensWithSpaces } from "@settlemint/sdk-utils";
102
- *
103
- * const result = replaceUnderscoresAndHyphensWithSpaces("Already_Spaced-Second");
104
- * // Returns: "Already Spaced Second"
105
- */
106
- declare function replaceUnderscoresAndHyphensWithSpaces(s: string): string;
107
- /**
108
- * Truncates a string to a maximum length and appends "..." if it is longer.
109
- *
110
- * @param value - The string to truncate
111
- * @param maxLength - The maximum length of the string
112
- * @returns The truncated string or the original string if it is shorter than the maximum length
113
- *
114
- * @example
115
- * import { truncate } from "@settlemint/sdk-utils";
116
- *
117
- * const truncated = truncate("Hello, world!", 10);
118
- * // Returns: "Hello, wor..."
119
- */
120
- declare function truncate(value: string, maxLength: number): string;
121
-
122
- export { camelCaseToWords, capitalizeFirstLetter, extractJsonObject, makeJsonStringifiable, replaceUnderscoresAndHyphensWithSpaces, retryWhenFailed, truncate, tryParseJson };
1
+ export * from "./json.js";
2
+ export * from "./retry.js";
3
+ export * from "./string.js";
4
+ export * from "./url.js";