@settlemint/sdk-utils 2.3.2-pref75df5f → 2.3.2-preff27199
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +51 -7
- package/dist/environment.cjs +17705 -383
- package/dist/environment.cjs.map +1 -1
- package/dist/environment.d.cts +263 -98
- package/dist/environment.d.ts +263 -98
- package/dist/environment.js +17743 -0
- package/dist/environment.js.map +1 -0
- package/dist/filesystem.cjs +6746 -113
- package/dist/filesystem.cjs.map +1 -1
- package/dist/filesystem.d.cts +22 -1
- package/dist/filesystem.d.ts +22 -1
- package/dist/filesystem.js +6766 -0
- package/dist/filesystem.js.map +1 -0
- package/dist/http.cjs +217 -79
- package/dist/http.cjs.map +1 -1
- package/dist/http.d.cts +14 -1
- package/dist/http.d.ts +14 -1
- package/dist/http.js +226 -0
- package/dist/http.js.map +1 -0
- package/dist/index.cjs +295 -104
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +26 -1
- package/dist/index.d.ts +26 -1
- package/dist/index.js +306 -0
- package/dist/index.js.map +1 -0
- package/dist/json.cjs +83 -0
- package/dist/json.cjs.map +1 -0
- package/dist/json.d.cts +56 -0
- package/dist/json.d.ts +56 -0
- package/dist/json.js +80 -0
- package/dist/json.js.map +1 -0
- package/dist/logging.cjs +209 -137
- package/dist/logging.cjs.map +1 -1
- package/dist/logging.d.cts +23 -14
- package/dist/logging.d.ts +23 -14
- package/dist/logging.js +221 -0
- package/dist/logging.js.map +1 -0
- package/dist/package-manager.cjs +7350 -173
- package/dist/package-manager.cjs.map +1 -1
- package/dist/package-manager.d.cts +26 -3
- package/dist/package-manager.d.ts +26 -3
- package/dist/package-manager.js +7382 -0
- package/dist/package-manager.js.map +1 -0
- package/dist/retry.cjs +137 -0
- package/dist/retry.cjs.map +1 -0
- package/dist/retry.d.cts +19 -0
- package/dist/retry.d.ts +19 -0
- package/dist/retry.js +136 -0
- package/dist/retry.js.map +1 -0
- package/dist/runtime.cjs +58 -40
- package/dist/runtime.cjs.map +1 -1
- package/dist/runtime.d.cts +3 -0
- package/dist/runtime.d.ts +3 -0
- package/dist/runtime.js +45 -0
- package/dist/runtime.js.map +1 -0
- package/dist/string.cjs +76 -0
- package/dist/string.cjs.map +1 -0
- package/dist/string.d.cts +58 -0
- package/dist/string.d.ts +58 -0
- package/dist/string.js +72 -0
- package/dist/string.js.map +1 -0
- package/dist/terminal.cjs +423 -229
- package/dist/terminal.cjs.map +1 -1
- package/dist/terminal.d.cts +54 -24
- package/dist/terminal.d.ts +54 -24
- package/dist/terminal.js +438 -0
- package/dist/terminal.js.map +1 -0
- package/dist/url.cjs +25 -0
- package/dist/url.cjs.map +1 -0
- package/dist/url.d.cts +20 -0
- package/dist/url.d.ts +20 -0
- package/dist/url.js +24 -0
- package/dist/url.js.map +1 -0
- package/dist/validation.cjs +10486 -190
- package/dist/validation.cjs.map +1 -1
- package/dist/validation.d.cts +128 -94
- package/dist/validation.d.ts +128 -94
- package/dist/validation.js +10482 -0
- package/dist/validation.js.map +1 -0
- package/package.json +6 -6
- package/dist/environment.mjs +0 -383
- package/dist/environment.mjs.map +0 -1
- package/dist/filesystem.mjs +0 -105
- package/dist/filesystem.mjs.map +0 -1
- package/dist/http.mjs +0 -63
- package/dist/http.mjs.map +0 -1
- package/dist/index.mjs +0 -90
- package/dist/index.mjs.map +0 -1
- package/dist/logging.mjs +0 -123
- package/dist/logging.mjs.map +0 -1
- package/dist/package-manager.mjs +0 -167
- package/dist/package-manager.mjs.map +0 -1
- package/dist/runtime.mjs +0 -23
- package/dist/runtime.mjs.map +0 -1
- package/dist/terminal.mjs +0 -230
- package/dist/terminal.mjs.map +0 -1
- package/dist/validation.mjs +0 -159
- package/dist/validation.mjs.map +0 -1
package/dist/retry.cjs
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
|
|
2
|
+
//#region src/logging/mask-tokens.ts
|
|
3
|
+
/**
|
|
4
|
+
* Masks sensitive SettleMint tokens in output text by replacing them with asterisks.
|
|
5
|
+
* Handles personal access tokens (PAT), application access tokens (AAT), and service account tokens (SAT).
|
|
6
|
+
*
|
|
7
|
+
* @param output - The text string that may contain sensitive tokens
|
|
8
|
+
* @returns The text with any sensitive tokens masked with asterisks
|
|
9
|
+
* @example
|
|
10
|
+
* import { maskTokens } from "@settlemint/sdk-utils/terminal";
|
|
11
|
+
*
|
|
12
|
+
* // Masks a token in text
|
|
13
|
+
* const masked = maskTokens("Token: sm_pat_****"); // "Token: ***"
|
|
14
|
+
*/
|
|
15
|
+
const maskTokens = (output) => {
|
|
16
|
+
return output.replace(/sm_(pat|aat|sat)_[0-9a-zA-Z]+/g, "***");
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
//#endregion
|
|
20
|
+
//#region src/logging/logger.ts
|
|
21
|
+
/**
|
|
22
|
+
* Creates a simple logger with configurable log level
|
|
23
|
+
*
|
|
24
|
+
* @param options - Configuration options for the logger
|
|
25
|
+
* @param options.level - The minimum log level to output (default: warn)
|
|
26
|
+
* @param options.prefix - The prefix to add to the log message (default: "")
|
|
27
|
+
* @returns A logger instance with debug, info, warn, and error methods
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* import { createLogger } from "@/utils/logging/logger";
|
|
31
|
+
*
|
|
32
|
+
* const logger = createLogger({ level: 'info' });
|
|
33
|
+
*
|
|
34
|
+
* logger.info('User logged in', { userId: '123' });
|
|
35
|
+
* logger.error('Operation failed', new Error('Connection timeout'));
|
|
36
|
+
*/
|
|
37
|
+
function createLogger(options = {}) {
|
|
38
|
+
const { level = "warn", prefix = "" } = options;
|
|
39
|
+
const logLevels = {
|
|
40
|
+
debug: 0,
|
|
41
|
+
info: 1,
|
|
42
|
+
warn: 2,
|
|
43
|
+
error: 3,
|
|
44
|
+
none: 4
|
|
45
|
+
};
|
|
46
|
+
const currentLevelValue = logLevels[level];
|
|
47
|
+
const formatArgs = (args) => {
|
|
48
|
+
if (args.length === 0 || args.every((arg) => arg === undefined || arg === null)) {
|
|
49
|
+
return "";
|
|
50
|
+
}
|
|
51
|
+
const formatted = args.map((arg) => {
|
|
52
|
+
if (arg instanceof Error) {
|
|
53
|
+
return `\n${arg.stack || arg.message}`;
|
|
54
|
+
}
|
|
55
|
+
if (typeof arg === "object" && arg !== null) {
|
|
56
|
+
return `\n${JSON.stringify(arg, null, 2)}`;
|
|
57
|
+
}
|
|
58
|
+
return ` ${String(arg)}`;
|
|
59
|
+
}).join("");
|
|
60
|
+
return `, args:${formatted}`;
|
|
61
|
+
};
|
|
62
|
+
const shouldLog = (level$1) => {
|
|
63
|
+
return logLevels[level$1] >= currentLevelValue;
|
|
64
|
+
};
|
|
65
|
+
return {
|
|
66
|
+
debug: (message, ...args) => {
|
|
67
|
+
if (shouldLog("debug")) {
|
|
68
|
+
console.debug(`\x1b[32m${prefix}[DEBUG] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1b[0m`);
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
info: (message, ...args) => {
|
|
72
|
+
if (shouldLog("info")) {
|
|
73
|
+
console.info(`\x1b[34m${prefix}[INFO] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1b[0m`);
|
|
74
|
+
}
|
|
75
|
+
},
|
|
76
|
+
warn: (message, ...args) => {
|
|
77
|
+
if (shouldLog("warn")) {
|
|
78
|
+
console.warn(`\x1b[33m${prefix}[WARN] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1b[0m`);
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
error: (message, ...args) => {
|
|
82
|
+
if (shouldLog("error")) {
|
|
83
|
+
console.error(`\x1b[31m${prefix}[ERROR] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1b[0m`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Default logger instance with standard configuration
|
|
90
|
+
*/
|
|
91
|
+
const logger = createLogger();
|
|
92
|
+
|
|
93
|
+
//#endregion
|
|
94
|
+
//#region src/retry.ts
|
|
95
|
+
/**
|
|
96
|
+
* Retry a function when it fails.
|
|
97
|
+
* @param fn - The function to retry.
|
|
98
|
+
* @param maxRetries - The maximum number of retries.
|
|
99
|
+
* @param initialSleepTime - The initial time to sleep between exponential backoff retries.
|
|
100
|
+
* @param stopOnError - The function to stop on error.
|
|
101
|
+
* @returns The result of the function or undefined if it fails.
|
|
102
|
+
* @example
|
|
103
|
+
* import { retryWhenFailed } from "@settlemint/sdk-utils";
|
|
104
|
+
* import { readFile } from "node:fs/promises";
|
|
105
|
+
*
|
|
106
|
+
* const result = await retryWhenFailed(() => readFile("/path/to/file.txt"), 3, 1_000);
|
|
107
|
+
*/
|
|
108
|
+
async function retryWhenFailed(fn, maxRetries = 5, initialSleepTime = 1e3, stopOnError) {
|
|
109
|
+
let retries = 0;
|
|
110
|
+
const maxAttempts = maxRetries + 1;
|
|
111
|
+
while (retries < maxAttempts) {
|
|
112
|
+
try {
|
|
113
|
+
return await fn();
|
|
114
|
+
} catch (e) {
|
|
115
|
+
const error = e;
|
|
116
|
+
if (typeof stopOnError === "function") {
|
|
117
|
+
if (stopOnError(error)) {
|
|
118
|
+
throw error;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (retries >= maxRetries) {
|
|
122
|
+
throw e;
|
|
123
|
+
}
|
|
124
|
+
const baseDelay = 2 ** retries * initialSleepTime;
|
|
125
|
+
const jitterAmount = initialSleepTime * (Math.random() / 10);
|
|
126
|
+
const delay = baseDelay + jitterAmount;
|
|
127
|
+
retries += 1;
|
|
128
|
+
logger.warn(`An error occurred ${error.message}, retrying in ${delay.toFixed(0)}ms (retry ${retries} of ${maxRetries})...`);
|
|
129
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
throw new Error("Retry failed");
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
//#endregion
|
|
136
|
+
exports.retryWhenFailed = retryWhenFailed;
|
|
137
|
+
//# sourceMappingURL=retry.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"retry.cjs","names":["output: string","options: LoggerOptions","logLevels: Record<LogLevel, number>","args: unknown[]","level: LogLevel","level","message: string","fn: () => Promise<T>","stopOnError?: (error: Error) => boolean"],"sources":["../src/logging/mask-tokens.ts","../src/logging/logger.ts","../src/retry.ts"],"sourcesContent":["/**\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 \"./mask-tokens.js\";\n\n/**\n * Log levels supported by the logger\n */\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\" | \"none\";\n\n/**\n * Configuration options for the logger\n * @interface LoggerOptions\n */\nexport interface LoggerOptions {\n /** The minimum log level to output */\n level?: LogLevel;\n /** The prefix to add to the log message */\n prefix?: string;\n}\n\n/**\n * Simple logger interface with basic logging methods\n * @interface Logger\n */\nexport interface Logger {\n /** Log debug information */\n debug: (message: string, ...args: unknown[]) => void;\n /** Log general information */\n info: (message: string, ...args: unknown[]) => void;\n /** Log warnings */\n warn: (message: string, ...args: unknown[]) => void;\n /** Log errors */\n error: (message: string, ...args: unknown[]) => void;\n}\n\n/**\n * Creates a simple logger with configurable log level\n *\n * @param options - Configuration options for the logger\n * @param options.level - The minimum log level to output (default: warn)\n * @param options.prefix - The prefix to add to the log message (default: \"\")\n * @returns A logger instance with debug, info, warn, and error methods\n *\n * @example\n * import { createLogger } from \"@/utils/logging/logger\";\n *\n * const logger = createLogger({ level: 'info' });\n *\n * logger.info('User logged in', { userId: '123' });\n * logger.error('Operation failed', new Error('Connection timeout'));\n */\nexport function createLogger(options: LoggerOptions = {}): Logger {\n const { level = \"warn\", prefix = \"\" } = options;\n\n const logLevels: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n none: 4,\n };\n\n const currentLevelValue = logLevels[level];\n\n const formatArgs = (args: unknown[]): string => {\n if (args.length === 0 || args.every((arg) => arg === undefined || arg === null)) {\n return \"\";\n }\n\n const formatted = args\n .map((arg) => {\n if (arg instanceof Error) {\n return `\\n${arg.stack || arg.message}`;\n }\n if (typeof arg === \"object\" && arg !== null) {\n return `\\n${JSON.stringify(arg, null, 2)}`;\n }\n return ` ${String(arg)}`;\n })\n .join(\"\");\n\n return `, args:${formatted}`;\n };\n\n const shouldLog = (level: LogLevel): boolean => {\n return logLevels[level] >= currentLevelValue;\n };\n\n return {\n debug: (message: string, ...args: unknown[]) => {\n if (shouldLog(\"debug\")) {\n console.debug(`\\x1b[32m${prefix}[DEBUG] ${maskTokens(message)}${maskTokens(formatArgs(args))}\\x1b[0m`);\n }\n },\n info: (message: string, ...args: unknown[]) => {\n if (shouldLog(\"info\")) {\n console.info(`\\x1b[34m${prefix}[INFO] ${maskTokens(message)}${maskTokens(formatArgs(args))}\\x1b[0m`);\n }\n },\n warn: (message: string, ...args: unknown[]) => {\n if (shouldLog(\"warn\")) {\n console.warn(`\\x1b[33m${prefix}[WARN] ${maskTokens(message)}${maskTokens(formatArgs(args))}\\x1b[0m`);\n }\n },\n error: (message: string, ...args: unknown[]) => {\n if (shouldLog(\"error\")) {\n console.error(`\\x1b[31m${prefix}[ERROR] ${maskTokens(message)}${maskTokens(formatArgs(args))}\\x1b[0m`);\n }\n },\n };\n}\n\n/**\n * Default logger instance with standard configuration\n */\nexport const logger = createLogger();\n","import { logger } from \"./logging/logger.js\";\n\n/**\n * Retry a function when it fails.\n * @param fn - The function to retry.\n * @param maxRetries - The maximum number of retries.\n * @param initialSleepTime - The initial time to sleep between exponential backoff retries.\n * @param stopOnError - The function to stop on error.\n * @returns The result of the function or undefined if it fails.\n * @example\n * import { retryWhenFailed } from \"@settlemint/sdk-utils\";\n * import { readFile } from \"node:fs/promises\";\n *\n * const result = await retryWhenFailed(() => readFile(\"/path/to/file.txt\"), 3, 1_000);\n */\nexport async function retryWhenFailed<T>(\n fn: () => Promise<T>,\n maxRetries = 5,\n initialSleepTime = 1_000,\n stopOnError?: (error: Error) => boolean,\n): Promise<T> {\n let retries = 0;\n const maxAttempts = maxRetries + 1;\n\n while (retries < maxAttempts) {\n try {\n return await fn();\n } catch (e) {\n const error = e as Error;\n if (typeof stopOnError === \"function\") {\n if (stopOnError(error)) {\n throw error;\n }\n }\n if (retries >= maxRetries) {\n throw e;\n }\n // Exponential backoff with jitter to prevent thundering herd\n // Jitter: Random value between 0-10% of initialSleepTime\n const baseDelay = 2 ** retries * initialSleepTime;\n const jitterAmount = initialSleepTime * (Math.random() / 10);\n const delay = baseDelay + jitterAmount;\n retries += 1;\n logger.warn(\n `An error occurred ${error.message}, retrying in ${delay.toFixed(0)}ms (retry ${retries} of ${maxRetries})...`,\n );\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n throw new Error(\"Retry failed\");\n}\n"],"mappings":";;;;;;;;;;;;;;AAYA,MAAa,aAAa,CAACA,WAA2B;AACpD,QAAO,OAAO,QAAQ,kCAAkC,MAAM;AAC/D;;;;;;;;;;;;;;;;;;;;ACmCD,SAAgB,aAAaC,UAAyB,CAAE,GAAU;CAChE,MAAM,EAAE,QAAQ,QAAQ,SAAS,IAAI,GAAG;CAExC,MAAMC,YAAsC;EAC1C,OAAO;EACP,MAAM;EACN,MAAM;EACN,OAAO;EACP,MAAM;CACP;CAED,MAAM,oBAAoB,UAAU;CAEpC,MAAM,aAAa,CAACC,SAA4B;AAC9C,MAAI,KAAK,WAAW,KAAK,KAAK,MAAM,CAAC,QAAQ,QAAQ,aAAa,QAAQ,KAAK,EAAE;AAC/E,UAAO;EACR;EAED,MAAM,YAAY,KACf,IAAI,CAAC,QAAQ;AACZ,OAAI,eAAe,OAAO;AACxB,YAAQ,IAAI,IAAI,SAAS,IAAI,QAAQ;GACtC;AACD,cAAW,QAAQ,YAAY,QAAQ,MAAM;AAC3C,YAAQ,IAAI,KAAK,UAAU,KAAK,MAAM,EAAE,CAAC;GAC1C;AACD,WAAQ,GAAG,OAAO,IAAI,CAAC;EACxB,EAAC,CACD,KAAK,GAAG;AAEX,UAAQ,SAAS,UAAU;CAC5B;CAED,MAAM,YAAY,CAACC,YAA6B;AAC9C,SAAO,UAAUC,YAAU;CAC5B;AAED,QAAO;EACL,OAAO,CAACC,SAAiB,GAAG,SAAoB;AAC9C,OAAI,UAAU,QAAQ,EAAE;AACtB,YAAQ,OAAO,UAAU,OAAO,UAAU,WAAW,QAAQ,CAAC,EAAE,WAAW,WAAW,KAAK,CAAC,CAAC,SAAS;GACvG;EACF;EACD,MAAM,CAACA,SAAiB,GAAG,SAAoB;AAC7C,OAAI,UAAU,OAAO,EAAE;AACrB,YAAQ,MAAM,UAAU,OAAO,SAAS,WAAW,QAAQ,CAAC,EAAE,WAAW,WAAW,KAAK,CAAC,CAAC,SAAS;GACrG;EACF;EACD,MAAM,CAACA,SAAiB,GAAG,SAAoB;AAC7C,OAAI,UAAU,OAAO,EAAE;AACrB,YAAQ,MAAM,UAAU,OAAO,SAAS,WAAW,QAAQ,CAAC,EAAE,WAAW,WAAW,KAAK,CAAC,CAAC,SAAS;GACrG;EACF;EACD,OAAO,CAACA,SAAiB,GAAG,SAAoB;AAC9C,OAAI,UAAU,QAAQ,EAAE;AACtB,YAAQ,OAAO,UAAU,OAAO,UAAU,WAAW,QAAQ,CAAC,EAAE,WAAW,WAAW,KAAK,CAAC,CAAC,SAAS;GACvG;EACF;CACF;AACF;;;;AAKD,MAAa,SAAS,cAAc;;;;;;;;;;;;;;;;;AClGpC,eAAsB,gBACpBC,IACA,aAAa,GACb,mBAAmB,KACnBC,aACY;CACZ,IAAI,UAAU;CACd,MAAM,cAAc,aAAa;AAEjC,QAAO,UAAU,aAAa;AAC5B,MAAI;AACF,UAAO,MAAM,IAAI;EAClB,SAAQ,GAAG;GACV,MAAM,QAAQ;AACd,cAAW,gBAAgB,YAAY;AACrC,QAAI,YAAY,MAAM,EAAE;AACtB,WAAM;IACP;GACF;AACD,OAAI,WAAW,YAAY;AACzB,UAAM;GACP;GAGD,MAAM,YAAY,KAAK,UAAU;GACjC,MAAM,eAAe,oBAAoB,KAAK,QAAQ,GAAG;GACzD,MAAM,QAAQ,YAAY;AAC1B,cAAW;AACX,UAAO,MACJ,oBAAoB,MAAM,QAAQ,gBAAgB,MAAM,QAAQ,EAAE,CAAC,YAAY,QAAQ,MAAM,WAAW,MAC1G;AACD,SAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,MAAM;EAC1D;CACF;AAED,OAAM,IAAI,MAAM;AACjB"}
|
package/dist/retry.d.cts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
//#region src/retry.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Retry a function when it fails.
|
|
4
|
+
* @param fn - The function to retry.
|
|
5
|
+
* @param maxRetries - The maximum number of retries.
|
|
6
|
+
* @param initialSleepTime - The initial time to sleep between exponential backoff retries.
|
|
7
|
+
* @param stopOnError - The function to stop on error.
|
|
8
|
+
* @returns The result of the function or undefined if it fails.
|
|
9
|
+
* @example
|
|
10
|
+
* import { retryWhenFailed } from "@settlemint/sdk-utils";
|
|
11
|
+
* import { readFile } from "node:fs/promises";
|
|
12
|
+
*
|
|
13
|
+
* const result = await retryWhenFailed(() => readFile("/path/to/file.txt"), 3, 1_000);
|
|
14
|
+
*/
|
|
15
|
+
declare function retryWhenFailed<T>(fn: () => Promise<T>, maxRetries?: number, initialSleepTime?: number, stopOnError?: (error: Error) => boolean): Promise<T>;
|
|
16
|
+
|
|
17
|
+
//#endregion
|
|
18
|
+
export { retryWhenFailed };
|
|
19
|
+
//# sourceMappingURL=retry.d.cts.map
|
package/dist/retry.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
//#region src/retry.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Retry a function when it fails.
|
|
4
|
+
* @param fn - The function to retry.
|
|
5
|
+
* @param maxRetries - The maximum number of retries.
|
|
6
|
+
* @param initialSleepTime - The initial time to sleep between exponential backoff retries.
|
|
7
|
+
* @param stopOnError - The function to stop on error.
|
|
8
|
+
* @returns The result of the function or undefined if it fails.
|
|
9
|
+
* @example
|
|
10
|
+
* import { retryWhenFailed } from "@settlemint/sdk-utils";
|
|
11
|
+
* import { readFile } from "node:fs/promises";
|
|
12
|
+
*
|
|
13
|
+
* const result = await retryWhenFailed(() => readFile("/path/to/file.txt"), 3, 1_000);
|
|
14
|
+
*/
|
|
15
|
+
declare function retryWhenFailed<T>(fn: () => Promise<T>, maxRetries?: number, initialSleepTime?: number, stopOnError?: (error: Error) => boolean): Promise<T>;
|
|
16
|
+
|
|
17
|
+
//#endregion
|
|
18
|
+
export { retryWhenFailed };
|
|
19
|
+
//# sourceMappingURL=retry.d.ts.map
|
package/dist/retry.js
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
//#region src/logging/mask-tokens.ts
|
|
2
|
+
/**
|
|
3
|
+
* Masks sensitive SettleMint tokens in output text by replacing them with asterisks.
|
|
4
|
+
* Handles personal access tokens (PAT), application access tokens (AAT), and service account tokens (SAT).
|
|
5
|
+
*
|
|
6
|
+
* @param output - The text string that may contain sensitive tokens
|
|
7
|
+
* @returns The text with any sensitive tokens masked with asterisks
|
|
8
|
+
* @example
|
|
9
|
+
* import { maskTokens } from "@settlemint/sdk-utils/terminal";
|
|
10
|
+
*
|
|
11
|
+
* // Masks a token in text
|
|
12
|
+
* const masked = maskTokens("Token: sm_pat_****"); // "Token: ***"
|
|
13
|
+
*/
|
|
14
|
+
const maskTokens = (output) => {
|
|
15
|
+
return output.replace(/sm_(pat|aat|sat)_[0-9a-zA-Z]+/g, "***");
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
//#endregion
|
|
19
|
+
//#region src/logging/logger.ts
|
|
20
|
+
/**
|
|
21
|
+
* Creates a simple logger with configurable log level
|
|
22
|
+
*
|
|
23
|
+
* @param options - Configuration options for the logger
|
|
24
|
+
* @param options.level - The minimum log level to output (default: warn)
|
|
25
|
+
* @param options.prefix - The prefix to add to the log message (default: "")
|
|
26
|
+
* @returns A logger instance with debug, info, warn, and error methods
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* import { createLogger } from "@/utils/logging/logger";
|
|
30
|
+
*
|
|
31
|
+
* const logger = createLogger({ level: 'info' });
|
|
32
|
+
*
|
|
33
|
+
* logger.info('User logged in', { userId: '123' });
|
|
34
|
+
* logger.error('Operation failed', new Error('Connection timeout'));
|
|
35
|
+
*/
|
|
36
|
+
function createLogger(options = {}) {
|
|
37
|
+
const { level = "warn", prefix = "" } = options;
|
|
38
|
+
const logLevels = {
|
|
39
|
+
debug: 0,
|
|
40
|
+
info: 1,
|
|
41
|
+
warn: 2,
|
|
42
|
+
error: 3,
|
|
43
|
+
none: 4
|
|
44
|
+
};
|
|
45
|
+
const currentLevelValue = logLevels[level];
|
|
46
|
+
const formatArgs = (args) => {
|
|
47
|
+
if (args.length === 0 || args.every((arg) => arg === undefined || arg === null)) {
|
|
48
|
+
return "";
|
|
49
|
+
}
|
|
50
|
+
const formatted = args.map((arg) => {
|
|
51
|
+
if (arg instanceof Error) {
|
|
52
|
+
return `\n${arg.stack || arg.message}`;
|
|
53
|
+
}
|
|
54
|
+
if (typeof arg === "object" && arg !== null) {
|
|
55
|
+
return `\n${JSON.stringify(arg, null, 2)}`;
|
|
56
|
+
}
|
|
57
|
+
return ` ${String(arg)}`;
|
|
58
|
+
}).join("");
|
|
59
|
+
return `, args:${formatted}`;
|
|
60
|
+
};
|
|
61
|
+
const shouldLog = (level$1) => {
|
|
62
|
+
return logLevels[level$1] >= 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
|
+
/**
|
|
88
|
+
* Default logger instance with standard configuration
|
|
89
|
+
*/
|
|
90
|
+
const logger = createLogger();
|
|
91
|
+
|
|
92
|
+
//#endregion
|
|
93
|
+
//#region src/retry.ts
|
|
94
|
+
/**
|
|
95
|
+
* Retry a function when it fails.
|
|
96
|
+
* @param fn - The function to retry.
|
|
97
|
+
* @param maxRetries - The maximum number of retries.
|
|
98
|
+
* @param initialSleepTime - The initial time to sleep between exponential backoff retries.
|
|
99
|
+
* @param stopOnError - The function to stop on error.
|
|
100
|
+
* @returns The result of the function or undefined if it fails.
|
|
101
|
+
* @example
|
|
102
|
+
* import { retryWhenFailed } from "@settlemint/sdk-utils";
|
|
103
|
+
* import { readFile } from "node:fs/promises";
|
|
104
|
+
*
|
|
105
|
+
* const result = await retryWhenFailed(() => readFile("/path/to/file.txt"), 3, 1_000);
|
|
106
|
+
*/
|
|
107
|
+
async function retryWhenFailed(fn, maxRetries = 5, initialSleepTime = 1e3, stopOnError) {
|
|
108
|
+
let retries = 0;
|
|
109
|
+
const maxAttempts = maxRetries + 1;
|
|
110
|
+
while (retries < maxAttempts) {
|
|
111
|
+
try {
|
|
112
|
+
return await fn();
|
|
113
|
+
} catch (e) {
|
|
114
|
+
const error = e;
|
|
115
|
+
if (typeof stopOnError === "function") {
|
|
116
|
+
if (stopOnError(error)) {
|
|
117
|
+
throw error;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (retries >= maxRetries) {
|
|
121
|
+
throw e;
|
|
122
|
+
}
|
|
123
|
+
const baseDelay = 2 ** retries * initialSleepTime;
|
|
124
|
+
const jitterAmount = initialSleepTime * (Math.random() / 10);
|
|
125
|
+
const delay = baseDelay + jitterAmount;
|
|
126
|
+
retries += 1;
|
|
127
|
+
logger.warn(`An error occurred ${error.message}, retrying in ${delay.toFixed(0)}ms (retry ${retries} of ${maxRetries})...`);
|
|
128
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
throw new Error("Retry failed");
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
//#endregion
|
|
135
|
+
export { retryWhenFailed };
|
|
136
|
+
//# sourceMappingURL=retry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"retry.js","names":["output: string","options: LoggerOptions","logLevels: Record<LogLevel, number>","args: unknown[]","level: LogLevel","level","message: string","fn: () => Promise<T>","stopOnError?: (error: Error) => boolean"],"sources":["../src/logging/mask-tokens.ts","../src/logging/logger.ts","../src/retry.ts"],"sourcesContent":["/**\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 \"./mask-tokens.js\";\n\n/**\n * Log levels supported by the logger\n */\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\" | \"none\";\n\n/**\n * Configuration options for the logger\n * @interface LoggerOptions\n */\nexport interface LoggerOptions {\n /** The minimum log level to output */\n level?: LogLevel;\n /** The prefix to add to the log message */\n prefix?: string;\n}\n\n/**\n * Simple logger interface with basic logging methods\n * @interface Logger\n */\nexport interface Logger {\n /** Log debug information */\n debug: (message: string, ...args: unknown[]) => void;\n /** Log general information */\n info: (message: string, ...args: unknown[]) => void;\n /** Log warnings */\n warn: (message: string, ...args: unknown[]) => void;\n /** Log errors */\n error: (message: string, ...args: unknown[]) => void;\n}\n\n/**\n * Creates a simple logger with configurable log level\n *\n * @param options - Configuration options for the logger\n * @param options.level - The minimum log level to output (default: warn)\n * @param options.prefix - The prefix to add to the log message (default: \"\")\n * @returns A logger instance with debug, info, warn, and error methods\n *\n * @example\n * import { createLogger } from \"@/utils/logging/logger\";\n *\n * const logger = createLogger({ level: 'info' });\n *\n * logger.info('User logged in', { userId: '123' });\n * logger.error('Operation failed', new Error('Connection timeout'));\n */\nexport function createLogger(options: LoggerOptions = {}): Logger {\n const { level = \"warn\", prefix = \"\" } = options;\n\n const logLevels: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n none: 4,\n };\n\n const currentLevelValue = logLevels[level];\n\n const formatArgs = (args: unknown[]): string => {\n if (args.length === 0 || args.every((arg) => arg === undefined || arg === null)) {\n return \"\";\n }\n\n const formatted = args\n .map((arg) => {\n if (arg instanceof Error) {\n return `\\n${arg.stack || arg.message}`;\n }\n if (typeof arg === \"object\" && arg !== null) {\n return `\\n${JSON.stringify(arg, null, 2)}`;\n }\n return ` ${String(arg)}`;\n })\n .join(\"\");\n\n return `, args:${formatted}`;\n };\n\n const shouldLog = (level: LogLevel): boolean => {\n return logLevels[level] >= currentLevelValue;\n };\n\n return {\n debug: (message: string, ...args: unknown[]) => {\n if (shouldLog(\"debug\")) {\n console.debug(`\\x1b[32m${prefix}[DEBUG] ${maskTokens(message)}${maskTokens(formatArgs(args))}\\x1b[0m`);\n }\n },\n info: (message: string, ...args: unknown[]) => {\n if (shouldLog(\"info\")) {\n console.info(`\\x1b[34m${prefix}[INFO] ${maskTokens(message)}${maskTokens(formatArgs(args))}\\x1b[0m`);\n }\n },\n warn: (message: string, ...args: unknown[]) => {\n if (shouldLog(\"warn\")) {\n console.warn(`\\x1b[33m${prefix}[WARN] ${maskTokens(message)}${maskTokens(formatArgs(args))}\\x1b[0m`);\n }\n },\n error: (message: string, ...args: unknown[]) => {\n if (shouldLog(\"error\")) {\n console.error(`\\x1b[31m${prefix}[ERROR] ${maskTokens(message)}${maskTokens(formatArgs(args))}\\x1b[0m`);\n }\n },\n };\n}\n\n/**\n * Default logger instance with standard configuration\n */\nexport const logger = createLogger();\n","import { logger } from \"./logging/logger.js\";\n\n/**\n * Retry a function when it fails.\n * @param fn - The function to retry.\n * @param maxRetries - The maximum number of retries.\n * @param initialSleepTime - The initial time to sleep between exponential backoff retries.\n * @param stopOnError - The function to stop on error.\n * @returns The result of the function or undefined if it fails.\n * @example\n * import { retryWhenFailed } from \"@settlemint/sdk-utils\";\n * import { readFile } from \"node:fs/promises\";\n *\n * const result = await retryWhenFailed(() => readFile(\"/path/to/file.txt\"), 3, 1_000);\n */\nexport async function retryWhenFailed<T>(\n fn: () => Promise<T>,\n maxRetries = 5,\n initialSleepTime = 1_000,\n stopOnError?: (error: Error) => boolean,\n): Promise<T> {\n let retries = 0;\n const maxAttempts = maxRetries + 1;\n\n while (retries < maxAttempts) {\n try {\n return await fn();\n } catch (e) {\n const error = e as Error;\n if (typeof stopOnError === \"function\") {\n if (stopOnError(error)) {\n throw error;\n }\n }\n if (retries >= maxRetries) {\n throw e;\n }\n // Exponential backoff with jitter to prevent thundering herd\n // Jitter: Random value between 0-10% of initialSleepTime\n const baseDelay = 2 ** retries * initialSleepTime;\n const jitterAmount = initialSleepTime * (Math.random() / 10);\n const delay = baseDelay + jitterAmount;\n retries += 1;\n logger.warn(\n `An error occurred ${error.message}, retrying in ${delay.toFixed(0)}ms (retry ${retries} of ${maxRetries})...`,\n );\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n throw new Error(\"Retry failed\");\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAa,aAAa,CAACA,WAA2B;AACpD,QAAO,OAAO,QAAQ,kCAAkC,MAAM;AAC/D;;;;;;;;;;;;;;;;;;;;ACmCD,SAAgB,aAAaC,UAAyB,CAAE,GAAU;CAChE,MAAM,EAAE,QAAQ,QAAQ,SAAS,IAAI,GAAG;CAExC,MAAMC,YAAsC;EAC1C,OAAO;EACP,MAAM;EACN,MAAM;EACN,OAAO;EACP,MAAM;CACP;CAED,MAAM,oBAAoB,UAAU;CAEpC,MAAM,aAAa,CAACC,SAA4B;AAC9C,MAAI,KAAK,WAAW,KAAK,KAAK,MAAM,CAAC,QAAQ,QAAQ,aAAa,QAAQ,KAAK,EAAE;AAC/E,UAAO;EACR;EAED,MAAM,YAAY,KACf,IAAI,CAAC,QAAQ;AACZ,OAAI,eAAe,OAAO;AACxB,YAAQ,IAAI,IAAI,SAAS,IAAI,QAAQ;GACtC;AACD,cAAW,QAAQ,YAAY,QAAQ,MAAM;AAC3C,YAAQ,IAAI,KAAK,UAAU,KAAK,MAAM,EAAE,CAAC;GAC1C;AACD,WAAQ,GAAG,OAAO,IAAI,CAAC;EACxB,EAAC,CACD,KAAK,GAAG;AAEX,UAAQ,SAAS,UAAU;CAC5B;CAED,MAAM,YAAY,CAACC,YAA6B;AAC9C,SAAO,UAAUC,YAAU;CAC5B;AAED,QAAO;EACL,OAAO,CAACC,SAAiB,GAAG,SAAoB;AAC9C,OAAI,UAAU,QAAQ,EAAE;AACtB,YAAQ,OAAO,UAAU,OAAO,UAAU,WAAW,QAAQ,CAAC,EAAE,WAAW,WAAW,KAAK,CAAC,CAAC,SAAS;GACvG;EACF;EACD,MAAM,CAACA,SAAiB,GAAG,SAAoB;AAC7C,OAAI,UAAU,OAAO,EAAE;AACrB,YAAQ,MAAM,UAAU,OAAO,SAAS,WAAW,QAAQ,CAAC,EAAE,WAAW,WAAW,KAAK,CAAC,CAAC,SAAS;GACrG;EACF;EACD,MAAM,CAACA,SAAiB,GAAG,SAAoB;AAC7C,OAAI,UAAU,OAAO,EAAE;AACrB,YAAQ,MAAM,UAAU,OAAO,SAAS,WAAW,QAAQ,CAAC,EAAE,WAAW,WAAW,KAAK,CAAC,CAAC,SAAS;GACrG;EACF;EACD,OAAO,CAACA,SAAiB,GAAG,SAAoB;AAC9C,OAAI,UAAU,QAAQ,EAAE;AACtB,YAAQ,OAAO,UAAU,OAAO,UAAU,WAAW,QAAQ,CAAC,EAAE,WAAW,WAAW,KAAK,CAAC,CAAC,SAAS;GACvG;EACF;CACF;AACF;;;;AAKD,MAAa,SAAS,cAAc;;;;;;;;;;;;;;;;;AClGpC,eAAsB,gBACpBC,IACA,aAAa,GACb,mBAAmB,KACnBC,aACY;CACZ,IAAI,UAAU;CACd,MAAM,cAAc,aAAa;AAEjC,QAAO,UAAU,aAAa;AAC5B,MAAI;AACF,UAAO,MAAM,IAAI;EAClB,SAAQ,GAAG;GACV,MAAM,QAAQ;AACd,cAAW,gBAAgB,YAAY;AACrC,QAAI,YAAY,MAAM,EAAE;AACtB,WAAM;IACP;GACF;AACD,OAAI,WAAW,YAAY;AACzB,UAAM;GACP;GAGD,MAAM,YAAY,KAAK,UAAU;GACjC,MAAM,eAAe,oBAAoB,KAAK,QAAQ,GAAG;GACzD,MAAM,QAAQ,YAAY;AAC1B,cAAW;AACX,UAAO,MACJ,oBAAoB,MAAM,QAAQ,gBAAgB,MAAM,QAAQ,EAAE,CAAC,YAAY,QAAQ,MAAM,WAAW,MAC1G;AACD,SAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,MAAM;EAC1D;CACF;AAED,OAAM,IAAI,MAAM;AACjB"}
|
package/dist/runtime.cjs
CHANGED
|
@@ -1,53 +1,71 @@
|
|
|
1
|
-
|
|
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
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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;
|
|
17
17
|
};
|
|
18
|
-
var
|
|
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));
|
|
19
22
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
__export(runtime_exports, {
|
|
23
|
-
ensureBrowser: () => ensureBrowser,
|
|
24
|
-
ensureServer: () => ensureServer,
|
|
25
|
-
runsInBrowser: () => runsInBrowser,
|
|
26
|
-
runsOnServer: () => runsOnServer
|
|
27
|
-
});
|
|
28
|
-
module.exports = __toCommonJS(runtime_exports);
|
|
23
|
+
//#endregion
|
|
24
|
+
const environment = __toESM(require("environment"));
|
|
29
25
|
|
|
30
|
-
|
|
31
|
-
|
|
26
|
+
//#region src/runtime/ensure-server.ts
|
|
27
|
+
/**
|
|
28
|
+
* Ensures that code is running on the server and not in a browser environment.
|
|
29
|
+
*
|
|
30
|
+
* @throws {Error} If called from a browser environment
|
|
31
|
+
* @example
|
|
32
|
+
* import { ensureServer } from "@settlemint/sdk-utils/runtime";
|
|
33
|
+
*
|
|
34
|
+
* // Will throw if running in browser
|
|
35
|
+
* ensureServer();
|
|
36
|
+
*/
|
|
32
37
|
function ensureServer() {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
);
|
|
37
|
-
}
|
|
38
|
+
if (environment.isBrowser) {
|
|
39
|
+
throw new Error("This function can only be used on the server as including it in the browser will expose your access token.");
|
|
40
|
+
}
|
|
38
41
|
}
|
|
42
|
+
/**
|
|
43
|
+
* Ensures that code is running in a browser environment and not on the server.
|
|
44
|
+
*
|
|
45
|
+
* @throws {Error} If called from a server environment
|
|
46
|
+
* @example
|
|
47
|
+
* import { ensureBrowser } from "@settlemint/sdk-utils/runtime";
|
|
48
|
+
*
|
|
49
|
+
* // Will throw if running on server
|
|
50
|
+
* ensureBrowser();
|
|
51
|
+
*/
|
|
39
52
|
function ensureBrowser() {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
53
|
+
if (!environment.isBrowser) {
|
|
54
|
+
throw new Error("This function can only be used on the browser as it is missing the access token.");
|
|
55
|
+
}
|
|
43
56
|
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
57
|
+
/**
|
|
58
|
+
* Boolean indicating if code is currently running in a browser environment
|
|
59
|
+
*/
|
|
60
|
+
const runsInBrowser = environment.isBrowser;
|
|
61
|
+
/**
|
|
62
|
+
* Boolean indicating if code is currently running in a server environment
|
|
63
|
+
*/
|
|
64
|
+
const runsOnServer = !environment.isBrowser;
|
|
65
|
+
|
|
66
|
+
//#endregion
|
|
67
|
+
exports.ensureBrowser = ensureBrowser;
|
|
68
|
+
exports.ensureServer = ensureServer;
|
|
69
|
+
exports.runsInBrowser = runsInBrowser;
|
|
70
|
+
exports.runsOnServer = runsOnServer;
|
|
53
71
|
//# sourceMappingURL=runtime.cjs.map
|
package/dist/runtime.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"
|
|
1
|
+
{"version":3,"file":"runtime.cjs","names":["isBrowser"],"sources":["../src/runtime/ensure-server.ts"],"sourcesContent":["import { isBrowser } from \"environment\";\n\n/**\n * Ensures that code is running on the server and not in a browser environment.\n *\n * @throws {Error} If called from a browser environment\n * @example\n * import { ensureServer } from \"@settlemint/sdk-utils/runtime\";\n *\n * // Will throw if running in browser\n * ensureServer();\n */\nexport function ensureServer(): void {\n if (isBrowser) {\n throw new Error(\n \"This function can only be used on the server as including it in the browser will expose your access token.\",\n );\n }\n}\n\n/**\n * Ensures that code is running in a browser environment and not on the server.\n *\n * @throws {Error} If called from a server environment\n * @example\n * import { ensureBrowser } from \"@settlemint/sdk-utils/runtime\";\n *\n * // Will throw if running on server\n * ensureBrowser();\n */\nexport function ensureBrowser(): void {\n if (!isBrowser) {\n throw new Error(\"This function can only be used on the browser as it is missing the access token.\");\n }\n}\n\n/**\n * Boolean indicating if code is currently running in a browser environment\n */\nexport const runsInBrowser = isBrowser;\n\n/**\n * Boolean indicating if code is currently running in a server environment\n */\nexport const runsOnServer = !isBrowser;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,SAAgB,eAAqB;AACnC,KAAIA,uBAAW;AACb,QAAM,IAAI,MACR;CAEH;AACF;;;;;;;;;;;AAYD,SAAgB,gBAAsB;AACpC,MAAKA,uBAAW;AACd,QAAM,IAAI,MAAM;CACjB;AACF;;;;AAKD,MAAa,gBAAgBA;;;;AAK7B,MAAa,gBAAgBA"}
|
package/dist/runtime.d.cts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
//#region src/runtime/ensure-server.d.ts
|
|
1
2
|
/**
|
|
2
3
|
* Ensures that code is running on the server and not in a browser environment.
|
|
3
4
|
*
|
|
@@ -29,4 +30,6 @@ declare const runsInBrowser: boolean;
|
|
|
29
30
|
*/
|
|
30
31
|
declare const runsOnServer: boolean;
|
|
31
32
|
|
|
33
|
+
//#endregion
|
|
32
34
|
export { ensureBrowser, ensureServer, runsInBrowser, runsOnServer };
|
|
35
|
+
//# sourceMappingURL=runtime.d.cts.map
|
package/dist/runtime.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
//#region src/runtime/ensure-server.d.ts
|
|
1
2
|
/**
|
|
2
3
|
* Ensures that code is running on the server and not in a browser environment.
|
|
3
4
|
*
|
|
@@ -29,4 +30,6 @@ declare const runsInBrowser: boolean;
|
|
|
29
30
|
*/
|
|
30
31
|
declare const runsOnServer: boolean;
|
|
31
32
|
|
|
33
|
+
//#endregion
|
|
32
34
|
export { ensureBrowser, ensureServer, runsInBrowser, runsOnServer };
|
|
35
|
+
//# sourceMappingURL=runtime.d.ts.map
|
package/dist/runtime.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { isBrowser } from "environment";
|
|
2
|
+
|
|
3
|
+
//#region src/runtime/ensure-server.ts
|
|
4
|
+
/**
|
|
5
|
+
* Ensures that code is running on the server and not in a browser environment.
|
|
6
|
+
*
|
|
7
|
+
* @throws {Error} If called from a browser environment
|
|
8
|
+
* @example
|
|
9
|
+
* import { ensureServer } from "@settlemint/sdk-utils/runtime";
|
|
10
|
+
*
|
|
11
|
+
* // Will throw if running in browser
|
|
12
|
+
* ensureServer();
|
|
13
|
+
*/
|
|
14
|
+
function ensureServer() {
|
|
15
|
+
if (isBrowser) {
|
|
16
|
+
throw new Error("This function can only be used on the server as including it in the browser will expose your access token.");
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Ensures that code is running in a browser environment and not on the server.
|
|
21
|
+
*
|
|
22
|
+
* @throws {Error} If called from a server environment
|
|
23
|
+
* @example
|
|
24
|
+
* import { ensureBrowser } from "@settlemint/sdk-utils/runtime";
|
|
25
|
+
*
|
|
26
|
+
* // Will throw if running on server
|
|
27
|
+
* ensureBrowser();
|
|
28
|
+
*/
|
|
29
|
+
function ensureBrowser() {
|
|
30
|
+
if (!isBrowser) {
|
|
31
|
+
throw new Error("This function can only be used on the browser as it is missing the access token.");
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Boolean indicating if code is currently running in a browser environment
|
|
36
|
+
*/
|
|
37
|
+
const runsInBrowser = isBrowser;
|
|
38
|
+
/**
|
|
39
|
+
* Boolean indicating if code is currently running in a server environment
|
|
40
|
+
*/
|
|
41
|
+
const runsOnServer = !isBrowser;
|
|
42
|
+
|
|
43
|
+
//#endregion
|
|
44
|
+
export { ensureBrowser, ensureServer, runsInBrowser, runsOnServer };
|
|
45
|
+
//# sourceMappingURL=runtime.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime.js","names":[],"sources":["../src/runtime/ensure-server.ts"],"sourcesContent":["import { isBrowser } from \"environment\";\n\n/**\n * Ensures that code is running on the server and not in a browser environment.\n *\n * @throws {Error} If called from a browser environment\n * @example\n * import { ensureServer } from \"@settlemint/sdk-utils/runtime\";\n *\n * // Will throw if running in browser\n * ensureServer();\n */\nexport function ensureServer(): void {\n if (isBrowser) {\n throw new Error(\n \"This function can only be used on the server as including it in the browser will expose your access token.\",\n );\n }\n}\n\n/**\n * Ensures that code is running in a browser environment and not on the server.\n *\n * @throws {Error} If called from a server environment\n * @example\n * import { ensureBrowser } from \"@settlemint/sdk-utils/runtime\";\n *\n * // Will throw if running on server\n * ensureBrowser();\n */\nexport function ensureBrowser(): void {\n if (!isBrowser) {\n throw new Error(\"This function can only be used on the browser as it is missing the access token.\");\n }\n}\n\n/**\n * Boolean indicating if code is currently running in a browser environment\n */\nexport const runsInBrowser = isBrowser;\n\n/**\n * Boolean indicating if code is currently running in a server environment\n */\nexport const runsOnServer = !isBrowser;\n"],"mappings":";;;;;;;;;;;;;AAYA,SAAgB,eAAqB;AACnC,KAAI,WAAW;AACb,QAAM,IAAI,MACR;CAEH;AACF;;;;;;;;;;;AAYD,SAAgB,gBAAsB;AACpC,MAAK,WAAW;AACd,QAAM,IAAI,MAAM;CACjB;AACF;;;;AAKD,MAAa,gBAAgB;;;;AAK7B,MAAa,gBAAgB"}
|
package/dist/string.cjs
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
|
|
2
|
+
//#region src/string.ts
|
|
3
|
+
/**
|
|
4
|
+
* Capitalizes the first letter of a string.
|
|
5
|
+
*
|
|
6
|
+
* @param val - The string to capitalize
|
|
7
|
+
* @returns The input string with its first letter capitalized
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* import { capitalizeFirstLetter } from "@settlemint/sdk-utils";
|
|
11
|
+
*
|
|
12
|
+
* const capitalized = capitalizeFirstLetter("hello");
|
|
13
|
+
* // Returns: "Hello"
|
|
14
|
+
*/
|
|
15
|
+
function capitalizeFirstLetter(val) {
|
|
16
|
+
return String(val).charAt(0).toUpperCase() + String(val).slice(1);
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Converts a camelCase string to a human-readable string.
|
|
20
|
+
*
|
|
21
|
+
* @param s - The camelCase string to convert
|
|
22
|
+
* @returns The human-readable string
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* import { camelCaseToWords } from "@settlemint/sdk-utils";
|
|
26
|
+
*
|
|
27
|
+
* const words = camelCaseToWords("camelCaseString");
|
|
28
|
+
* // Returns: "Camel Case String"
|
|
29
|
+
*/
|
|
30
|
+
function camelCaseToWords(s) {
|
|
31
|
+
const result = s.replace(/([a-z])([A-Z])/g, "$1 $2");
|
|
32
|
+
const withSpaces = result.replace(/([A-Z])([a-z])/g, " $1$2");
|
|
33
|
+
const capitalized = capitalizeFirstLetter(withSpaces);
|
|
34
|
+
return capitalized.replace(/\s+/g, " ").trim();
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Replaces underscores and hyphens with spaces.
|
|
38
|
+
*
|
|
39
|
+
* @param s - The string to replace underscores and hyphens with spaces
|
|
40
|
+
* @returns The input string with underscores and hyphens replaced with spaces
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* import { replaceUnderscoresAndHyphensWithSpaces } from "@settlemint/sdk-utils";
|
|
44
|
+
*
|
|
45
|
+
* const result = replaceUnderscoresAndHyphensWithSpaces("Already_Spaced-Second");
|
|
46
|
+
* // Returns: "Already Spaced Second"
|
|
47
|
+
*/
|
|
48
|
+
function replaceUnderscoresAndHyphensWithSpaces(s) {
|
|
49
|
+
return s.replace(/[-_]/g, " ");
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Truncates a string to a maximum length and appends "..." if it is longer.
|
|
53
|
+
*
|
|
54
|
+
* @param value - The string to truncate
|
|
55
|
+
* @param maxLength - The maximum length of the string
|
|
56
|
+
* @returns The truncated string or the original string if it is shorter than the maximum length
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* import { truncate } from "@settlemint/sdk-utils";
|
|
60
|
+
*
|
|
61
|
+
* const truncated = truncate("Hello, world!", 10);
|
|
62
|
+
* // Returns: "Hello, wor..."
|
|
63
|
+
*/
|
|
64
|
+
function truncate(value, maxLength) {
|
|
65
|
+
if (value.length <= maxLength) {
|
|
66
|
+
return value;
|
|
67
|
+
}
|
|
68
|
+
return `${value.slice(0, maxLength)}...`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
//#endregion
|
|
72
|
+
exports.camelCaseToWords = camelCaseToWords;
|
|
73
|
+
exports.capitalizeFirstLetter = capitalizeFirstLetter;
|
|
74
|
+
exports.replaceUnderscoresAndHyphensWithSpaces = replaceUnderscoresAndHyphensWithSpaces;
|
|
75
|
+
exports.truncate = truncate;
|
|
76
|
+
//# sourceMappingURL=string.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"string.cjs","names":["val: string","s: string","value: string","maxLength: number"],"sources":["../src/string.ts"],"sourcesContent":["/**\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"],"mappings":";;;;;;;;;;;;;;AAYA,SAAgB,sBAAsBA,KAAa;AACjD,QAAO,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC,aAAa,GAAG,OAAO,IAAI,CAAC,MAAM,EAAE;AAClE;;;;;;;;;;;;;AAcD,SAAgB,iBAAiBC,GAAW;CAC1C,MAAM,SAAS,EAAE,QAAQ,mBAAmB,QAAQ;CACpD,MAAM,aAAa,OAAO,QAAQ,mBAAmB,QAAQ;CAC7D,MAAM,cAAc,sBAAsB,WAAW;AACrD,QAAO,YAAY,QAAQ,QAAQ,IAAI,CAAC,MAAM;AAC/C;;;;;;;;;;;;;AAcD,SAAgB,uCAAuCA,GAAW;AAChE,QAAO,EAAE,QAAQ,SAAS,IAAI;AAC/B;;;;;;;;;;;;;;AAeD,SAAgB,SAASC,OAAeC,WAAmB;AACzD,KAAI,MAAM,UAAU,WAAW;AAC7B,SAAO;CACR;AACD,SAAQ,EAAE,MAAM,MAAM,GAAG,UAAU,CAAC;AACrC"}
|